o
    IhKU                     @  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StandaloneModuleConfigEntrystandalone_module_namestandalone_module_class%float_to_observed_custom_module_class)observed_to_quantized_custom_module_classnon_traceable_module_namenon_traceable_module_classinput_quantized_idxs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$   Z/var/www/vscode/kcb/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r1   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)   )r1   rF   r   r   r   r   r$   r$   r%   set_standalone_module_nameP      
z.PrepareCustomConfig.set_standalone_module_namemodule_classtypec                 C  rH   )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*   )r1   rK   r   r   r   r   r$   r$   r%   set_standalone_module_classd   rJ   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+   )r1   rN   rO   rP   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,   )r1   rT   r$   r$   r%   set_non_traceable_module_names      z2PrepareCustomConfig.set_non_traceable_module_namesmodule_classes
list[type]c                 C  rV   )z[
        Set the modules that are not symbolically traceable, identified by class.
        )r-   )r1   rY   r$   r$   r%    set_non_traceable_module_classes   rX   z4PrepareCustomConfig.set_non_traceable_module_classesindexes	list[int]c                 C  rV   )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.   r1   r\   r$   r$   r%   set_input_quantized_indexes      z/PrepareCustomConfig.set_input_quantized_indexesc                 C  rV   )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/   r^   r$   r$   r%   set_output_quantized_indexes   r`   z0PrepareCustomConfig.set_output_quantized_indexes
attributesc                 C  rV   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   r1   rb   r$   r$   r%   set_preserved_attributes   r`   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_keyrG   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_dictrR   rL   ri   rj   r$   r$   r%   _get_qconfig_mapping      

z;PrepareCustomConfig.from_dict.<locals>._get_qconfig_mappingr   c                 S  rk   )zs
            Convert the given object into a PrepareCustomConfig if possible, else throw an exception.
            Nz<Expected PrepareCustomConfig in prepare_custom_config_dict["rl   rm   )rn   r   ro   rp   rR   rL   rq   r$   r$   r%   _get_prepare_custom_config   s   

zAPrepareCustomConfig.from_dict.<locals>._get_prepare_custom_configr   c                 S  rk   )zm
            Convert the given object into a BackendConfig if possible, else throw an exception.
            Nz6Expected BackendConfig in prepare_custom_config_dict["rl   rm   )rn   r   ro   rp   rR   rL   rq   r$   r$   r%   _get_backend_config   rs   z:PrepareCustomConfig.from_dict.<locals>._get_backend_configN)ri   r   rj   rG   r&   r   )ri   r   rj   rG   r&   r   )ri   r   rj   rG   r&   r   )getSTANDALONE_MODULE_NAME_DICT_KEYrI    STANDALONE_MODULE_CLASS_DICT_KEYrM   FLOAT_TO_OBSERVED_DICT_KEYrA   r	   rS   rW   "NON_TRACEABLE_MODULE_NAME_DICT_KEYr[   #NON_TRACEABLE_MODULE_CLASS_DICT_KEYr_    INPUT_QUANTIZED_INDEXES_DICT_KEYra   !OUTPUT_QUANTIZED_INDEXES_DICT_KEYrf   PRESERVED_ATTRIBUTES_DICT_KEY)clsrg   rr   rt   ru   confrF   qconfig_dictr   _prepare_custom_config_dictbackend_config_dictr   r   r   rK   quant_type_namecustom_module_mappingrP   rN   rO   r$   r$   r%   rp      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   r   rg   r$   r$   r%   _make_tupleF  s   z0PrepareCustomConfig.to_dict.<locals>._make_tupler   N)r   r   r   r   )r)   rA   rw   appendr*   rx   r+   ry   r   r7   r,   rz   r-   r{   r.   r|   r/   r}   r   r~   )r1   r   drF   sm_config_entryrK   rP   r+   r$   r$   r%   r   @  sF   





zPrepareCustomConfig.to_dictNr&   r'   )rF   rG   r   r   r   r   r   r   r   r   r&   r   )rK   rL   r   r   r   r   r   r   r   r   r&   r   )rN   rL   rO   rL   rP   r
   r&   r   )rT   rU   r&   r   )rY   rZ   r&   r   )r\   r]   r&   r   )rb   rU   r&   r   )rg   rh   r&   r   r&   rh   )r    r!   r"   __doc__r2   rD   rI   rM   r
   rQ   rS   rW   r[   r_   ra   rf   classmethodrp   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   r0   r$   r$   r%   r2     s   
zConvertCustomConfig.__init__c                 C  r3   )Nc                 S  r4   r5   r6   r8   r$   r$   r%   r<     r=   z0ConvertCustomConfig.__repr__.<locals>.<dictcomp>zConvertCustomConfig(r>   r?   rB   r$   r$   r%   rD     rE   zConvertCustomConfig.__repr__rO   rL   quantized_classrP   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   )r1   rO   r   rP   r$   r$   r%   !set_observed_to_quantized_mapping  s   

z5ConvertCustomConfig.set_observed_to_quantized_mappingrb   rU   c                 C  rV   rc   rd   re   r$   r$   r%   rf     r`   z,ConvertCustomConfig.set_preserved_attributesconvert_custom_config_dictrh   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.
        )rv   OBSERVED_TO_QUANTIZED_DICT_KEYrA   r	   r   rf   r~   )r   r   r   r   r   rP   rO   r   r$   r$   r%   rp     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   rA   r   r   r7   r   r~   )r1   r   rP   r   r$   r$   r%   r     s   
zConvertCustomConfig.to_dictNr   )rO   rL   r   rL   rP   r
   r&   r   )rb   rU   r&   r   )r   rh   r&   r   r   )r    r!   r"   r   r2   rD   r
   rQ   r   rf   r   rp   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(   rd   r0   r$   r$   r%   r2     s   
zFuseCustomConfig.__init__c                 C  r3   )Nc                 S  r4   r5   r6   r8   r$   r$   r%   r<     r=   z-FuseCustomConfig.__repr__.<locals>.<dictcomp>zFuseCustomConfig(r>   r?   rB   r$   r$   r%   rD     rE   zFuseCustomConfig.__repr__rb   rU   c                 C  rV   rc   rd   re   r$   r$   r%   rf     r`   z)FuseCustomConfig.set_preserved_attributesfuse_custom_config_dictrh   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.
        )rf   rv   r~   )r   r   r   r$   r$   r%   rp     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   )r7   r   r~   )r1   r   r$   r$   r%   r     s   
zFuseCustomConfig.to_dictNr   )rb   rU   r&   r   )r   rh   r&   r   r   )
r    r!   r"   r   r2   rD   rf   r   rp   r   r$   r$   r$   r%   r     s    

	r   N)
__future__r   dataclassesr   typingr   r   torch.ao.quantizationr   $torch.ao.quantization.backend_configr    torch.ao.quantization.quant_typer   r	   r
   __all__rw   rx   ry   r   rz   r{   r|   r}   r~   r   r   r   r   r$   r$   r$   r%   <module>   s.   		  Ja