o
    ZhKU                     @  s   d dl mZ d dlmZ d dlmZmZ d dlmZ d dl	m
Z
 d dlmZmZmZ g dZdZd	Zd
ZdZdZdZdZdZdZeG dd dZG dd dZG dd dZG dd dZdS )    )annotations)	dataclass)AnyOptional)QConfigMapping)BackendConfig)_get_quant_type_to_str_quant_type_from_str	QuantType)ConvertCustomConfigFuseCustomConfigPrepareCustomConfigStandaloneModuleConfigEntryZstandalone_module_nameZstandalone_module_classZ%float_to_observed_custom_module_classZ)observed_to_quantized_custom_module_classZnon_traceable_module_nameZnon_traceable_module_classZinput_quantized_idxsZoutput_quantized_idxspreserved_attributesc                   @  s.   e Zd ZU ded< ded< ded< ded< d	S )
r   Optional[QConfigMapping]qconfig_mappingtuple[Any, ...]example_inputsOptional[PrepareCustomConfig]prepare_custom_configOptional[BackendConfig]backend_configN)__name__
__module____qualname____annotations__ r   r   U/var/www/auris/lib/python3.10/site-packages/torch/ao/quantization/fx/custom_config.pyr   $   s
   
 r   c                   @  s   e Zd ZdZd6ddZdd Zd7ddZd8ddZej	fd9ddZ
d:d d!Zd;d$d%Zd<d(d)Zd<d*d+Zd=d-d.Zed>d1d2Zd?d3d4Zd5S )@r   a  
    Custom configuration for :func:`~torch.ao.quantization.quantize_fx.prepare_fx` and
    :func:`~torch.ao.quantization.quantize_fx.prepare_qat_fx`.

    Example usage::

        prepare_custom_config = PrepareCustomConfig()             .set_standalone_module_name("module1", qconfig_mapping, example_inputs,                 child_prepare_custom_config, backend_config)             .set_standalone_module_class(MyStandaloneModule, qconfig_mapping, example_inputs,                 child_prepare_custom_config, backend_config)             .set_float_to_observed_mapping(FloatCustomModule, ObservedCustomModule)             .set_non_traceable_module_names(["module2", "module3"])             .set_non_traceable_module_classes([NonTraceableModule1, NonTraceableModule2])             .set_input_quantized_indexes([0])             .set_output_quantized_indexes([0])             .set_preserved_attributes(["attr1", "attr2"])
    returnNonec                 C  s4   i | _ i | _i | _g | _g | _g | _g | _g | _d S N)standalone_module_namesstandalone_module_classesfloat_to_observed_mappingnon_traceable_module_namesnon_traceable_module_classesinput_quantized_indexesoutput_quantized_indexesr   selfr   r   r   __init__B   s   
zPrepareCustomConfig.__init__c                 C      dd | j  D }d| dS )Nc                 S  "   i | ]\}}t |d kr||qS r   len.0kvr   r   r   
<dictcomp>M      " z0PrepareCustomConfig.__repr__.<locals>.<dictcomp>zPrepareCustomConfig()__dict__itemsr)   Zdict_nonemptyr   r   r   __repr__L      zPrepareCustomConfig.__repr__module_namestrr   r   r   r   r   r   r   r   c                 C     t ||||| j|< | S )a|  
        Set the configuration for running a standalone module identified by ``module_name``.

        If ``qconfig_mapping`` is None, the parent ``qconfig_mapping`` will be used instead.
        If ``prepare_custom_config`` is None, an empty ``PrepareCustomConfig`` will be used.
        If ``backend_config`` is None, the parent ``backend_config`` will be used instead.
        )r   r!   )r)   r=   r   r   r   r   r   r   r   set_standalone_module_nameP      
z.PrepareCustomConfig.set_standalone_module_namemodule_classtypec                 C  r?   )a}  
        Set the configuration for running a standalone module identified by ``module_class``.

        If ``qconfig_mapping`` is None, the parent ``qconfig_mapping`` will be used instead.
        If ``prepare_custom_config`` is None, an empty ``PrepareCustomConfig`` will be used.
        If ``backend_config`` is None, the parent ``backend_config`` will be used instead.
        )r   r"   )r)   rB   r   r   r   r   r   r   r   set_standalone_module_classd   rA   z/PrepareCustomConfig.set_standalone_module_classfloat_classobserved_class
quant_typer
   c                 C  s8   |t jkr	td|| jvri | j|< || j| |< | S )a5  
        Set the mapping from a custom float module class to a custom observed module class.

        The observed module class must have a ``from_float`` class method that converts the float module class
        to the observed module class. This is currently only supported for static quantization.
        zQset_float_to_observed_mapping is currently only supported for static quantization)r
   STATIC
ValueErrorr#   )r)   rE   rF   rG   r   r   r   set_float_to_observed_mappingx   s   


z1PrepareCustomConfig.set_float_to_observed_mappingmodule_names	list[str]c                 C  
   || _ | S )zZ
        Set the modules that are not symbolically traceable, identified by name.
        )r$   )r)   rK   r   r   r   set_non_traceable_module_names      z2PrepareCustomConfig.set_non_traceable_module_namesmodule_classes
list[type]c                 C  rM   )z[
        Set the modules that are not symbolically traceable, identified by class.
        )r%   )r)   rP   r   r   r    set_non_traceable_module_classes   rO   z4PrepareCustomConfig.set_non_traceable_module_classesindexes	list[int]c                 C  rM   )z
        Set the indexes of the inputs of the graph that should be quantized.
        Inputs are otherwise assumed to be in fp32 by default instead.
        )r&   r)   rS   r   r   r   set_input_quantized_indexes      z/PrepareCustomConfig.set_input_quantized_indexesc                 C  rM   )z
        Set the indexes of the outputs of the graph that should be quantized.
        Outputs are otherwise assumed to be in fp32 by default instead.
        )r'   rU   r   r   r   set_output_quantized_indexes   rW   z0PrepareCustomConfig.set_output_quantized_indexes
attributesc                 C  rM   z
        Set the names of the attributes that will persist in the graph module even if they are not used in
        the model's ``forward`` method.
        r   r)   rY   r   r   r   set_preserved_attributes   rW   z,PrepareCustomConfig.set_preserved_attributesprepare_custom_config_dictdict[str, Any]c                 C  s\  ddd}dd
d}ddd}|  }| tg D ]\}}}}	}
||t}||	t}||
t}|||||| q| tg D ]\}}}}	}
||t}||	t}||
t}|||||| q>| ti  D ]\}}t|}| D ]\}}|||| qrqf|	| t
g  || tg  || tg  || tg  || tg  |S )a  
        Create a ``PrepareCustomConfig`` from a dictionary with the following items:

            "standalone_module_name": a list of (module_name, qconfig_mapping, example_inputs,
            child_prepare_custom_config, backend_config) tuples

            "standalone_module_class" a list of (module_class, qconfig_mapping, example_inputs,
            child_prepare_custom_config, backend_config) tuples

            "float_to_observed_custom_module_class": a nested dictionary mapping from quantization
            mode to an inner mapping from float module classes to observed module classes, e.g.
            {"static": {FloatCustomModule: ObservedCustomModule}}

            "non_traceable_module_name": a list of modules names that are not symbolically traceable
            "non_traceable_module_class": a list of module classes that are not symbolically traceable
            "input_quantized_idxs": a list of indexes of graph inputs that should be quantized
            "output_quantized_idxs": a list of indexes of graph outputs that should be quantized
            "preserved_attributes": a list of attributes that persist even if they are not used in ``forward``

        This function is primarily for backward compatibility and may be removed in the future.
        objr   dict_keyr>   r   r   c                 S  D   t | ts	| du r| S t | trt| S td| dt|  d)zn
            Convert the given object into a QConfigMapping if possible, else throw an exception.
            Nz7Expected QConfigMapping in prepare_custom_config_dict["	"], got '')
isinstancer   dict	from_dictrI   rC   r`   ra   r   r   r   _get_qconfig_mapping      

z;PrepareCustomConfig.from_dict.<locals>._get_qconfig_mappingr   c                 S  rb   )zs
            Convert the given object into a PrepareCustomConfig if possible, else throw an exception.
            Nz<Expected PrepareCustomConfig in prepare_custom_config_dict["rc   rd   )re   r   rf   rg   rI   rC   rh   r   r   r   _get_prepare_custom_config   s   

zAPrepareCustomConfig.from_dict.<locals>._get_prepare_custom_configr   c                 S  rb   )zm
            Convert the given object into a BackendConfig if possible, else throw an exception.
            Nz6Expected BackendConfig in prepare_custom_config_dict["rc   rd   )re   r   rf   rg   rI   rC   rh   r   r   r   _get_backend_config   rj   z:PrepareCustomConfig.from_dict.<locals>._get_backend_configN)r`   r   ra   r>   r   r   )r`   r   ra   r>   r   r   )r`   r   ra   r>   r   r   )getSTANDALONE_MODULE_NAME_DICT_KEYr@    STANDALONE_MODULE_CLASS_DICT_KEYrD   FLOAT_TO_OBSERVED_DICT_KEYr9   r	   rJ   rN   "NON_TRACEABLE_MODULE_NAME_DICT_KEYrR   #NON_TRACEABLE_MODULE_CLASS_DICT_KEYrV    INPUT_QUANTIZED_INDEXES_DICT_KEYrX   !OUTPUT_QUANTIZED_INDEXES_DICT_KEYr]   PRESERVED_ATTRIBUTES_DICT_KEY)clsr^   ri   rk   rl   confr=   qconfig_dictr   Z_prepare_custom_config_dictZbackend_config_dictr   r   r   rB   quant_type_namecustom_module_mappingrG   rE   rF   r   r   r   rg      s   










zPrepareCustomConfig.from_dictc                 C  s.  d	dd}i }| j  D ]\}}t|vrg |t< |t ||| q| j D ]\}}t|vr4g |t< |t ||| q(| j D ]\}}t|vrPi |t< ||t t|< qDt	| j
dkre| j
|t< t	| jdkrq| j|t< t	| jdkr}| j|t< t	| jdkr| j|t< t	| jdkr| j|t< |S )
z
        Convert this ``PrepareCustomConfig`` to a dictionary with the items described in
        :func:`~torch.ao.quantization.fx.custom_config.PrepareCustomConfig.from_dict`.
        keyr   er   c                 S  s:   |j r|j  nd }|jr|j nd }| ||j||jfS r    )r   to_dictr   r   r   )r{   r|   rx   r^   r   r   r   _make_tupleF  s   z0PrepareCustomConfig.to_dict.<locals>._make_tupler   N)r{   r   r|   r   )r!   r9   rn   appendr"   ro   r#   rp   r   r/   r$   rq   r%   rr   r&   rs   r'   rt   r   ru   )r)   r~   dr=   Zsm_config_entryrB   rG   r#   r   r   r   r}   @  sF   





zPrepareCustomConfig.to_dictNr   r   )r=   r>   r   r   r   r   r   r   r   r   r   r   )rB   rC   r   r   r   r   r   r   r   r   r   r   )rE   rC   rF   rC   rG   r
   r   r   )rK   rL   r   r   )rP   rQ   r   r   )rS   rT   r   r   )rY   rL   r   r   )r^   r_   r   r   r   r_   )r   r   r   __doc__r*   r;   r@   rD   r
   rH   rJ   rN   rR   rV   rX   r]   classmethodrg   r}   r   r   r   r   r   .   s"    





	
	

	 r   c                   @  sT   e Zd ZdZdddZdd ZejfdddZdddZ	e
dddZdddZdS )r   a;  
    Custom configuration for :func:`~torch.ao.quantization.quantize_fx.convert_fx`.

    Example usage::

        convert_custom_config = ConvertCustomConfig()             .set_observed_to_quantized_mapping(ObservedCustomModule, QuantizedCustomModule)             .set_preserved_attributes(["attr1", "attr2"])
    r   r   c                 C  s   i | _ g | _d S r    )observed_to_quantized_mappingr   r(   r   r   r   r*     s   
zConvertCustomConfig.__init__c                 C  r+   )Nc                 S  r,   r-   r.   r0   r   r   r   r4     r5   z0ConvertCustomConfig.__repr__.<locals>.<dictcomp>zConvertCustomConfig(r6   r7   r:   r   r   r   r;     r<   zConvertCustomConfig.__repr__rF   rC   quantized_classrG   r
   c                 C  s&   || j vr
i | j |< || j | |< | S )a  
        Set the mapping from a custom observed module class to a custom quantized module class.

        The quantized module class must have a ``from_observed`` class method that converts the observed module class
        to the quantized module class.
        )r   )r)   rF   r   rG   r   r   r   !set_observed_to_quantized_mapping  s   

z5ConvertCustomConfig.set_observed_to_quantized_mappingrY   rL   c                 C  rM   rZ   r[   r\   r   r   r   r]     rW   z,ConvertCustomConfig.set_preserved_attributesconvert_custom_config_dictr_   c                 C  s^   |  }| ti  D ]\}}t|}| D ]\}}|||| qq|| tg  |S )a  
        Create a ``ConvertCustomConfig`` from a dictionary with the following items:

            "observed_to_quantized_custom_module_class": a nested dictionary mapping from quantization
            mode to an inner mapping from observed module classes to quantized module classes, e.g.::
            {
            "static": {FloatCustomModule: ObservedCustomModule},
            "dynamic": {FloatCustomModule: ObservedCustomModule},
            "weight_only": {FloatCustomModule: ObservedCustomModule}
            }
            "preserved_attributes": a list of attributes that persist even if they are not used in ``forward``

        This function is primarily for backward compatibility and may be removed in the future.
        )rm   OBSERVED_TO_QUANTIZED_DICT_KEYr9   r	   r   r]   ru   )rv   r   rw   ry   rz   rG   rF   r   r   r   r   rg     s    

zConvertCustomConfig.from_dictc                 C  sT   i }| j  D ]\}}t|vri |t< ||t t|< qt| jdkr(| j|t< |S )z
        Convert this ``ConvertCustomConfig`` to a dictionary with the items described in
        :func:`~torch.ao.quantization.fx.custom_config.ConvertCustomConfig.from_dict`.
        r   )r   r9   r   r   r/   r   ru   )r)   r   rG   r   r   r   r   r}     s   
zConvertCustomConfig.to_dictNr   )rF   rC   r   rC   rG   r
   r   r   )rY   rL   r   r   )r   r_   r   r   r   )r   r   r   r   r*   r;   r
   rH   r   r]   r   rg   r}   r   r   r   r   r   v  s    


	r   c                   @  sD   e Zd ZdZdddZdd Zdd
dZedddZdddZ	dS )r   z
    Custom configuration for :func:`~torch.ao.quantization.quantize_fx.fuse_fx`.

    Example usage::

        fuse_custom_config = FuseCustomConfig().set_preserved_attributes(["attr1", "attr2"])
    r   r   c                 C  s
   g | _ d S r    r[   r(   r   r   r   r*     s   
zFuseCustomConfig.__init__c                 C  r+   )Nc                 S  r,   r-   r.   r0   r   r   r   r4     r5   z-FuseCustomConfig.__repr__.<locals>.<dictcomp>zFuseCustomConfig(r6   r7   r:   r   r   r   r;     r<   zFuseCustomConfig.__repr__rY   rL   c                 C  rM   rZ   r[   r\   r   r   r   r]     rW   z)FuseCustomConfig.set_preserved_attributesfuse_custom_config_dictr_   c                 C  s   |  }| |tg  |S )a/  
        Create a ``ConvertCustomConfig`` from a dictionary with the following items:

            "preserved_attributes": a list of attributes that persist even if they are not used in ``forward``

        This function is primarily for backward compatibility and may be removed in the future.
        )r]   rm   ru   )rv   r   rw   r   r   r   rg     s
   	
zFuseCustomConfig.from_dictc                 C  s    i }t | jdkr| j|t< |S )z
        Convert this ``FuseCustomConfig`` to a dictionary with the items described in
        :func:`~torch.ao.quantization.fx.custom_config.ConvertCustomConfig.from_dict`.
        r   )r/   r   ru   )r)   r   r   r   r   r}     s   
zFuseCustomConfig.to_dictNr   )rY   rL   r   r   )r   r_   r   r   r   )
r   r   r   r   r*   r;   r]   r   rg   r}   r   r   r   r   r     s    

	r   N)
__future__r   dataclassesr   typingr   r   Ztorch.ao.quantizationr   Z$torch.ao.quantization.backend_configr   Z torch.ao.quantization.quant_typer   r	   r
   __all__rn   ro   rp   r   rq   rr   rs   rt   ru   r   r   r   r   r   r   r   r   <module>   s.   		  Ja