
    Pi              
          d dl Z d dlmZ d dlmZmZ d dlZd dlmZ d dl	m
Z
 d dlmZ d dlmZmZmZ d dlmZmZ d d	lmZ d
 Ze G d de
                      ZeZ ee          dej        j        defd            Z G d de
          ZeZ ee          dej        j        dedej        j        fd            Z	 ddej        j        de
deeej        j        ege f                  dej        j        fdZ!dS )    N)	dataclass)CallableOptional)to_sparse_semi_structured)AOBaseConfig)WeightNormSparsifier)
_is_linear_linear_extra_repr)_replace_with_custom_fn_if_matches_filter)_QUANTIZE_CONFIG_HANDLER register_quantize_module_handler)BlockSparseTensorc                 `   |                     dt                    }g }|                                 D ]+\  }} |||          r|                    d| di           ,t	          ddd          }|                    | |           |                                 |                                 dS )	zO
    This function simulates 2:4 sparsity on all linear layers in a model.
    	filter_fn
tensor_fqnz.weightg      ?)         )sparsity_levelsparse_block_shapezeros_per_blockN)popr	   named_modulesappendr   preparestepsquash_mask)modelkwargsr   sparse_confignamemod
sparsifiers          o/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/torchao/sparsity/sparse_api.pyapply_fake_sparsityr%      s     

;
33IM((** C C	c9S$ 	C  ,40@0@0@!ABBB%vq  J um,,,OO    c                   $    e Zd ZU dZeed<   d ZdS )BlockSparseWeightConfig@   	blocksizec                 D    t           j                            d           d S )Nz(torchao.sparsity.BlockSparseWeightConfigtorch_C_log_api_usage_onceselfs    r$   __post_init__z%BlockSparseWeightConfig.__post_init__5   s    $$%OPPPPPr&   N)__name__
__module____qualname__r*   int__annotations__r2    r&   r$   r(   r(   1   s:         IsQ Q Q Q Qr&   r(   moduleconfigc                     |j         }t          j        | j        |          }t          j                            |d          | _        t          j        t          |           | _
        | S NF)requires_grad)r*   r   
from_denseweightr-   nn	Parametertypes
MethodTyper
   
extra_repr)r9   r:   r*   
new_weights       r$   _block_sparse_weight_transformrF   =   sW    
  I"-fmYGGJH&&z&GGFM();VDDFMr&   c                       e Zd ZdZd ZdS )SemiSparseWeightConfigze
    Configuration for converting the weight of linear modules to semi-structured (2:4) sparsity
    c                 D    t           j                            d           d S )Nz'torchao.sparsity.SemiSparseWeightConfigr,   r0   s    r$   r2   z$SemiSparseWeightConfig.__post_init__N   s    $$%NOOOOOr&   N)r3   r4   r5   __doc__r2   r8   r&   r$   rH   rH   I   s2         P P P P Pr&   rH   returnc                     t          | j                  }t          j                            |d          | _        t          j        t          |           | _        | S r<   )	r   r?   r-   r@   rA   rB   rC   r
   rD   )r9   r:   rE   s      r$   _semi_sparse_weight_transformrM   V   sJ    
 +6=99JH&&z&GGFM();VDDFMr&   r   r   c                     t           j                            d           t          t	          |                   }t          | ||t          n||f           dS )a  Convert the weight of linear modules in the model with `apply_tensor_subclass`.
    This function is essentially the same as quantize, put for sparsity subclasses.

    Currently, we support three options for sparsity:
        - semi-structured (2:4) sparsity with `semi_sparse_weight`
        - int8 dynamic quantization + 2:4 sparsity with `layout=SemiSparseLayout`
        - int4 weight-only quantization + 2:4 sparsity with `layout=SparseMarlinLayout`

    Args:
        model (torch.nn.Module): input model
        config (AOBaseConfig): a workflow configuration object
        filter_fn (Optional[Callable[[torch.nn.Module, str], bool]]): function that takes a nn.Module instance and fully qualified name of the module, returns True if we want to apply the specified workflow to this module.

    **Example:**
    ::
            import torch
            import torch.nn as nn
            from torchao.sparsity import sparsify_

            def filter_fn(module: nn.Module, fqn: str) -> bool:
                return isinstance(module, nn.Linear)

            m = nn.Sequential(nn.Linear(32, 1024), nn.Linear(1024, 32))

            # for 2:4 sparsity
            from torchao.sparse_api import semi_sparse_weight
            m = sparsify_(m, semi_sparse_weight(), filter_fn)

            # for int8 dynamic quantization + 2:4 sparsity
            from torchao.dtypes import SemiSparseLayout
            m = quantize_(m, Int8DynamicActivationInt8WeightConfig(layout=SemiSparseLayout), filter_fn)
    ztorchao.sparsity.sparsify_N)
extra_args)r-   r.   r/   r   typer   r	   )r   r:   r   handlers       r$   	sparsify_rR   a   sd    J 
H  !=>>>&tF||4G-'

Y9	     r&   )N)"rB   dataclassesr   typingr   r   r-   torch.sparser   torchao.core.configr   <torchao.prototype.sparsity.sparsifier.weight_norm_sparsifierr   torchao.quantization.quant_apir	   r
   r   %torchao.quantization.transform_moduler   r   torchao.sparsity.blocksparser   r%   r(   block_sparse_weightr@   ModulerF   rH   semi_sparse_weightrM   strboolrR   r8   r&   r$   <module>r`      s    ! ! ! ! ! ! % % % % % % % %  2 2 2 2 2 2 , , , , , ,              
        ; : : : : :  & Q Q Q Q Ql Q Q Q .  "!"9::HO#   ;:P P P P P\ P P P ,  "!"899HO" X_   :9 CG, ,8?,, %(/3!7!=>?, X_	, , , , , ,r&   