
    *`i<              
          d dl Z d dlZd dlmZ d dlmZ d dlmZmZm	Z	m
Z
mZmZmZmZmZ d dlZd dlZd dlmZmZ  edd          Zerd d	lmZ g d
ZdZdeded         fdZdedefdZd9dedefdZdej        j         dedej        j         fdZ!dedefdZ"dededefdZ#	 d:dee         dee         de	egef         fdZ$ G d  d!          Z%	 d;d"ej&        d#ee'         d$e'deej&                 fd%Z(d;d&Z)d'ej&        dej&        fd(Z*d)ej&        d*ee'         dej&        fd+Z+e j,        d,e-d-ed.efd/            Z.e j,        d0ee         d-ed1ee         fd2            Z/ G d3 d4e0          Z1d5ede'fd6Z2d5ede'fd7Z3d5ede'fd8Z4dS )<    N)wraps)MappingProxyType)	TYPE_CHECKINGAnyCallableDictIterableListMappingOptionalTypeVar)
AutoConfigPretrainedConfigTr   )boundModelCompressor)"infer_compressor_from_model_configfix_fsdp_module_nametensor_follows_mask_structurereplace_moduleis_compressed_tensors_configgetattr_chain
deprecated	Aliasablecombine_shardsshard_tensorpack_bitmasksunpack_bitmasks
patch_attrpatch_attrsParameterizedDefaultDictget_num_attn_headsget_num_kv_headsget_head_dim_fsdp_wrapped_modulepretrained_model_name_or_pathreturnr   c                     ddl m} ddlm} t	          j        |           } |j        |          }|dS |                    d          } |j        |fi |} |j        ||          }|S )a  
    Given a path to a model config, extract a sparsity config if it exists and return
    the associated ModelCompressor

    :param pretrained_model_name_or_path: path to model config on disk or HF hub
    :return: matching compressor if config contains a sparsity config
    r   r   )CompressionConfigNformatconfig)	compressed_tensors.compressorsr   compressed_tensors.configr*   r   from_pretrainedparse_sparsity_configgetload_from_registry)r'   r   r*   r-   sparsity_configr+   
compressors          t/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/compressed_tensors/utils/helpers.pyr   r   C   s     ?>>>>>;;;;;;'(EFFF;o;FCCOt  **F:':6UU_UUO33F?SSSJ    namec                 v    |                      t          dz   d                               dt          z   d          S )z
    Remove FSDP wrapper prefixes from a module name
    Accounts for scenario where FSDP_WRAPPER_NAME is
    at the end of the name, as well as in the middle.
    :param name: name to strip
    :return: stripped name
    . )replaceFSDP_WRAPPER_NAME)r8   s    r6   r   r   [   s;     <<)C/44<<  r7   2:4maskc                 F   t          t          t          |                    d                              \  }}|                     d|          } | dk                        d          }t          j        ||k                                              st                      dS )a,  
    :param tensor: tensor to check
    :param mask: mask structure to check for, in the format "n:m"
    :return: True if the tensor follows the mask structure, False otherwise.
        Note, some weights can incidentally be zero, so we check for
        atleast n zeros in each chunk of size m
    :r      )dimT)
tuplemapintsplitviewsumtorchallitem
ValueError)tensorr?   nmzero_countss        r6   r   r   h   s     S$**S//**++DAq[[QF Q;###**K
 9[A%&&++-- ll4r7   model
new_modulec                     d|v rL|                     dd          d         }|t          |          dz   d          }|                     |          }nd}| }|}t          |||           d S )Nr:   rC   r   r;   )rsplitlenget_submodulesetattr)rS   r8   rT   parent_name
child_nameparents         r6   r   r      s|    
d{{kk#q))!,#k**Q.001
$$[11
FJ
+++++r7   compression_configc                 R    	 ddl m} t          | |          S # t          $ r Y dS w xY w)z
    Returns True if CompressedTensorsConfig is available from transformers and
    compression_config is an instance of CompressedTensorsConfig

    See: https://github.com/huggingface/transformers/pull/31704
    r   )CompressedTensorsConfigF)&transformers.utils.quantization_configr_   
isinstanceImportError)r]   r_   s     r6   r   r      sM    RRRRRR,.EFFF   uus    
&&obj	chain_strc                    t          |          dk    rd}|d         }nd|v rd}|d         }nd}|                    d          }| }|D ]<}t          ||          s|r|c S t          | d|           t	          ||          }=|S )z
    Chain multiple getattr calls, separated by `.`

    :param obj: base object whose attributes are being retrieved
    :param chain_str: attribute names separated by `.`
    :param default: default value, throw error otherwise
    rC   Tr   defaultFr:   z object has no attribute )rW   rH   hasattrAttributeErrorgetattr)	rc   rd   argskwargshas_defaultrf   
attr_namesres	attr_names	            r6   r   r      s     4yyA~~q'	f		#%%J
C & &	sI&& 	S S$%Q%Qi%Q%QRRRc9%%Jr7   future_namemessagec                 4     dt           dt           f fd}|S )z
    Decorator to mark functions as deprecated

    :param new_function: Function called in place of deprecated function
    :param message: Deprecation message, replaces default deprecation message
    funcr(   c                 n      j          d	d dz  t                      fd            }|S )Nz6 is deprecated and will be removed in a future releasez. Please use z	 instead.c                  L    t          j        t          d            | i |S )N   )
stacklevel)warningswarnDeprecationWarning)rj   rk   rs   rq   s     r6   wrappedz.deprecated.<locals>.decorator.<locals>.wrapped   s0    M'#5!DDDD4((((r7   )__name__r   )rs   r{   rp   rq   s   ` r6   	decoratorzdeprecated.<locals>.decorator   sq     ?=XXX  &A;AAAA	t	) 	) 	) 	) 	) 
	) r7   )r   )rp   rq   r}   s   `` r6   r   r      s=     a       " r7   c                   J    e Zd ZdZedeeef         fd            Zd Zd Z	dS )r   z
    A mixin for enums to allow aliasing of enum members

    Example:
    >>> class MyClass(Aliasable, int, Enum):
    >>>     ...
    r(   c                      t                      N)NotImplementedError r7   r6   get_aliaseszAliasable.get_aliases   s    !###r7   c                    t          || j                  rf|                                 }| j        |j        k    pA|                    | j        | j                  |                    |j        |j                  k    S |                                 }|                    | j        | j                  }|                    ||          }||k    S r   )ra   	__class__r   valuer2   )selfotheraliases
self_valueother_values        r6   __eq__zAliasable.__eq__   s    eT^,, 
	-&&((G:, DJ
33;;u{EK889
 &&((G TZ<<J!++eU33K,,r7   c                 j    | j                             | j        | j                  }t          |          S r   )r   r2   r   hash)r   canonical_values     r6   __hash__zAliasable.__hash__   s+    ,**4:tzBBO$$$r7   N)
r|   
__module____qualname____doc__staticmethodr   strr   r   r   r   r7   r6   r   r      sk          $c3h $ $ $ \$- - -% % % % %r7   r   rO   shard_sizesrD   c                     t          |          |                     |          k    rt          d          g }d}|D ]5}||z   }|                     |||          }|                    |           |}6|S )a  
    Shards a tensor into a list of tensors along a given dimension.

    raises: ValueError: If the sum of shard_sizes does not match the
        size of the tensor along the given dimension.

    :param tensor: The input tensor to shard.
    :param shard_sizes : List of sizes for each shard along the specified dimension.
    :param dim : The dimension along which to shard the tensor.
    :returns: A list of tensors sharded along the specified dimension.
    zSSum of shard_sizes must equal the size of the tensor along the specified dimension.r   )rJ   sizerN   narrowappend)rO   r   rD   shards	start_idxr   end_idxshards           r6   r   r      s     ;6;;s++++-
 
 	

 FI  d"c9d33e		Mr7   c                    | st          d          d | D             }t          |          dk    rt          d          t          | d         j                  }t	          fd| D                       |<   t          j        || d         j        | d         j                  }d}| D ]>}|j                 }|	                    ||          
                    |           ||z  }?|S )z
    Combine decompressed shards along a given dimension using `narrow`.

    :param shards: List of decompressed shard tensors.
    :param dim: Dimension to combine along (default: 0).
    :return: Combined decompressed tensor.
    zThe list of shards is empty.c                     h | ]	}|j         
S r   )dtype).0r   s     r6   	<setcomp>z!combine_shards.<locals>.<setcomp>$  s    444EEK444r7   rC   z$All shards must have the same dtype.r   c              3   2   K   | ]}|j                  V  d S r   )shape)r   r   rD   s     r6   	<genexpr>z!combine_shards.<locals>.<genexpr>*  s*      @@5;s+@@@@@@r7   )r   device)rN   rW   listr   rJ   rK   zerosr   r   r   copy_)r   rD   shard_dtypestotal_shapecombinedshard_offsetr   
shard_sizes    `      r6   r   r     s     97888 54V444L
<1?@@@ vay''K@@@@@@@@@K {;fQiofQiFVWWWH L # #[%
\:66<<UCCC
"Or7   	bytemasksc                     t          j        |                                  dd          }t          j        |          }|S )a  
    Converts a bytemask tensor to a bitmask tensor to reduce memory. Shape RxC will be
    compressed to R x ceil(C/8)

    :param bytemasks: mask tensor where each byte corresponds to a weight
    :return: mask tensor where each bit corresounds to a weight
    rB   little)axisbitorder)numpypackbitsrK   
from_numpy)r   packed_bits_numpypacked_bits_torchs      r6   r   r   9  s=     y'8'8rHUUU():;;r7   packed_bitmasksoriginal_shapec                    t          j        |                                                                  d|d         d          }t          j        |                    |                              t                              }|S )a#  
    Converts a bitmask tensor back to a bytemask tensor for use during decompression

    :param packed_bitmasks: mask tensor where each bit corresponds to a weight
    :param original_shape: dense shape to decompress to
    :return: boolean mask of weights in the original dense shape
    rB   r   )r   countr   )r   
unpackbitscpurK   r   reshapeastypebool)r   r   unpacked_bitsunpacked_bitmasks_torchs       r6   r   r   G  s     $##%%R 	  M $.n--44T::  #"r7   baseattrr   c              #     K   t                      }t          | ||          }t          | ||           	 dV  ||urt          | ||           dS t          | |           dS # ||urt          | ||           w t          | |           w xY w)a  
    Patch the value of an object attribute. Original value is restored upon exit

    :param base: object which has the attribute to patch
    :param attr: name of the the attribute to patch
    :param value: used to replace original value

    Usage:
    >>> from types import SimpleNamespace
    >>> obj = SimpleNamespace()
    >>> with patch_attr(obj, "attribute", "value"):
    ...     assert obj.attribute == "value"
    >>> assert not hasattr(obj, "attribute")
    N)objectri   rY   delattr)r   r   r   	_sentineloriginal_values        r6   r    r    a  s        IT433ND$ **D$/////D$ **D$////D$s   A! !(B	basesvaluesc           	   #      K   t          j                    5 }t          | |          D ])\  }}|                    t	          |||                     *dV  ddd           dS # 1 swxY w Y   dS )a  
    Same as `patch_attr` but for a list of objects to patch
    Patch attribute for a list of objects with list of values.
    Original values are restored upon exit

    :param bases: objects which has the attribute to patch
    :param attr: name of the the attribute to patch
    :param values: used to replace original values. Must be same
        length as bases

    Usage:
    >>> from types import SimpleNamespace
    >>> obj1 = SimpleNamespace()
    >>> obj2 = SimpleNamespace()
    >>> with patch_attr([obj1, obj2], "attribute", ["value1", "value2"]):
    ...     assert obj1.attribute == "value1"
    ...     assert obj2.attribute == "value2"
    >>> assert not hasattr(obj1, "attribute")
    >>> assert not hasattr(obj2, "attribute")
    N)
contextlib	ExitStackzipenter_contextr    )r   r   r   stackr   r   s         r6   r!   r!   ~  s      , 
			 5uf-- 	? 	?KD%
4u = =>>>>                 s   ?A""A&)A&c                   h    e Zd ZdZdeegef         fdZdedefdZ ei           dde	defd	Z
d
S )r"   a
  
    Similar to `collections.DefaultDict`, but upon fetching a key which is missing,
    the key is passed as arguments to the `default_factory`

    :param default_factory: function which takes a key as input and returns the
        corresponding default value
    default_factoryc                 <    || _         t          i           | _        d S r   )r   r   _factory_kwargs)r   r   s     r6   __init__z!ParameterizedDefaultDict.__init__  s     ./33r7   keyr(   c                     t          |t                    r | j        |i | j        }n | j        |fi | j        }|| |<   |S r   )ra   rE   r   r   )r   r   r   s      r6   __missing__z$ParameterizedDefaultDict.__missing__  s\    c5!! 	F(D(#F1EFFEE(D(EE0DEEES	r7   )factory_kwargsr   c                h    t          | d|          5  | |         cddd           S # 1 swxY w Y   dS )a"  
        Similar to `__getitem__`, but allows passing kwargs to factory function

        :param \*args: args whose tuple will value will be treated as key
        :param factory_kwargs: keyword arguments to pass to `default_factory`
        :return: dictionary entry for given key
        r   N)r    )r   r   rj   s      r6   r2   zParameterizedDefaultDict.get  s     /@@ 	 	:	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   '++N)r|   r   r   r   r   r   r   r   r   r   r2   r   r7   r6   r"   r"     s         4#(< 4 4 4 4s s     4D3CB3G3G 	 	 	 	C 	 	 	 	 	 	r7   r"   r-   c                     t          | d          r| j        S t          | d          rt          | d          r| j        | j        z  S t	          d|            )z
    Get the number of attention heads used by a model

    :param config: model config
    :return: num_attention_heads of model
    num_attention_headshidden_sizehead_dimzCannot determine num_attention_heads from config. Config must define either `num_attention_heads` or both `hidden_size` and `head_dim`. )rg   r   r   r   rN   r,   s    r6   r#   r#     sy     v,-- 
))		'	' 
GFJ,G,G 
!V_44  
 
 	
r7   c                 T    t          | d          r| j        S t          d|            )z
    Get the number of key-value attention heads used by a model

    :param config: model config
    :return: num_key_value_heads of model
    num_key_value_headsz\Cannot determine num_key_value_heads from config. Config must define `num_key_value_heads`. )rg   r   rN   r,   s    r6   r$   r$     sF     v,-- 
)) /&,/ /
 
 	
r7   c                     t          | d          r| j        S t          | d          rt          | d          r| j        | j        z  S t	          d|            )z
    Get the number of dimensions used by the attention heads of a model

    :param config: model config
    :return: head_dim of model
    r   r   r   z}Cannot determine head_dim from config. Config must define either `head_dim` or both `hidden_size` and `num_attention_heads`. )rg   r   r   r   rN   r,   s    r6   r%   r%     sy     vz"" 
		'	' 
GF<Q,R,R 
!V%???  
 
 	
r7   )r>   )NN)r   )5r   rx   	functoolsr   typesr   typingr   r   r   r   r	   r
   r   r   r   r   rK   transformersr   r   r   r.   r   __all__r=   r   r   r   r   r   nnModuler   r   r   r   r   TensorrG   r   r   r   r   contextmanagerr   r    r!   dictr"   r#   r$   r%   r   r7   r6   <module>r      s\              " " " " " "
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
   5 5 5 5 5 5 5 5 GCz"""  ?>>>>>>  * + #&    0
s 
s 
 
 
 
      2	,%(/ 	, 	,%(/ 	, 	, 	, 	,S T    s s     @ AE #08qc1f   <% % % % % % % %@ >? L'+Cy7:	%,   @   BU\ el    #\#379#
\# # # #4  V  3  s        8 x} C #    6    t   B
/ 
C 
 
 
 
*
- 
# 
 
 
 
"
) 
c 
 
 
 
 
 
r7   