o
    hõ                    @   s@  d dl Z d dlZd dlZd dlZd dlmZ d dlmZm	Z	m
Z
mZmZ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mZ e rSd d	lmZ eeZ G d
d dZ!eG dd dZ"eG dd de"Z#eG dd de"Z$G dd de!Z%de%fddZ&de%fddZ'dejj(j)fddZ*dd Z+edrejj(j,e%e&e*e%j- de%j e'd  ej.j(/e%e+ G d!d" d"e%Z0G d#d$ d$e%Z1G d%d& d&e1Z2G d'd( d(e1Z3G d)d* d*e!Z4G d+d, d,e!Z5G d-d. d.e5Z6G d/d0 d0e!Z7G d1d2 d2e!Z8G d3d4 d4e!Z9G d5d6 d6Z:G d7d8 d8e5Z;dS )9    N)	dataclass)AnyDictIterableListOptionalTupleUnion)version)"is_torch_greater_or_equal_than_2_6   )PretrainedConfig)is_hqq_availableis_optimum_quanto_availableis_torch_greater_or_equallogging)	Quantizerc                       s   e Zd ZdZdZ fddZ	ddejdejded	e	e
eef  d
eejejf f
ddZdde	e d
efddZd
e	e fddZddede	e d
efddZdejfddZedd Z  ZS )Cachezf
    Base, abstract class for all caches. The actual data structure is specific to each subclass.
    Fc                    s   t    d S N)super__init__self	__class__ l/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/transformers/cache_utils.pyr      s   zCache.__init__N
key_statesvalue_states	layer_idxcache_kwargsreturnc                 C      t d)a  
        Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`.

        Parameters:
            key_states (`torch.Tensor`):
                The new key states to cache.
            value_states (`torch.Tensor`):
                The new value states to cache.
            layer_idx (`int`):
                The index of the layer to cache the states for.
            cache_kwargs (`Dict[str, Any]`, `optional`):
                Additional arguments for the cache subclass. These are specific to each subclass and allow new types of
                cache to be created.

        Return:
            A tuple containing the updated key and value states.
        z.Make sure to implement `update` in a subclass.NotImplementedError)r   r   r   r   r    r   r   r   update!   s   zCache.updater   c                 C   r"   )YReturns the sequence length of the cached states. A layer index can be optionally passed.z6Make sure to implement `get_seq_length` in a subclass.r#   r   r   r   r   r   get_seq_length;   s   zCache.get_seq_lengthc                 C   r"   )zKReturns the maximum sequence length (i.e. max capacity) of the cache objectz;Make sure to implement `get_max_cache_shape` in a subclass.r#   r   r   r   r   get_max_cache_shape@      zCache.get_max_cache_shapenew_seq_lengthc                 C   s2   |   }| |}|dur|| |kr|| S |S )zTGiven the sequence length of the new inputs, returns the usable length of the cache.N)r)   r(   )r   r+   r   
max_lengthprevious_seq_lengthr   r   r   get_usable_lengthD   s
   
zCache.get_usable_lengthbeam_idxc                 C   s   t t| jD ]:}| j|  r%| j| j}| j| d||| j|< | j|  rA| j| j}| j| d||| j|< qdS )DReorders the cache for beam search, given the selected beam indices.r   N)rangelen	key_cachenumeldeviceindex_selecttovalue_cache)r   r/   r   r5   r   r   r   reorder_cacheO   s   zCache.reorder_cachec                 C   s   t d t| dr| jS d S )NzuThe `seen_tokens` attribute is deprecated and will be removed in v4.41. Use the `cache_position` model input instead._seen_tokens)loggerwarning_oncehasattrr:   r   r   r   r   seen_tokensY   s   
zCache.seen_tokensr   r   )__name__
__module____qualname____doc__is_compileabler   torchTensorintr   r   strr   r   r%   r(   r)   r.   
LongTensorr9   propertyr>   __classcell__r   r   r   r   r      s,    

r   c                   @   st   e Zd ZU dZded< edd Zdeee	j
f fddZd	eeef fd
dZdd Zdd Zdd Zdd ZdS )CacheConfigz&
    Base class for cache configs
    Ncache_implementationc                 K   s^   | di |}g }|  D ]\}}t||r!t||| || q|D ]}||d q$|S )ar  
        Constructs a CacheConfig instance from a dictionary of parameters.
        Args:
            config_dict (Dict[str, Any]): Dictionary containing configuration parameters.
            **kwargs: Additional keyword arguments to override dictionary values.

        Returns:
            CacheConfig: Instance of CacheConfig constructed from the dictionary.
        Nr   )itemsr=   setattrappendpop)clsconfig_dictkwargsconfig	to_removekeyvaluer   r   r   	from_dictm   s   

zCacheConfig.from_dictjson_file_pathc                 C   sZ   t |ddd}|  }tj|dddd }|| W d   dS 1 s&w   Y  dS )	a  
        Save this instance to a JSON file.

        Args:
            json_file_path (`str` or `os.PathLike`):
                Path to the JSON file in which this configuration instance's parameters will be saved.
            use_diff (`bool`, *optional*, defaults to `True`):
                If set to `True`, only the difference between the config instance and the default
                `QuantizationConfig()` is serialized to JSON file.
        wzutf-8)encoding   T)indent	sort_keys
N)opento_dictjsondumpswrite)r   rZ   writerrS   json_stringr   r   r   to_json_file   s
   "zCacheConfig.to_json_filer!   c                 C   s   t | jS )z
        Serializes this instance to a Python dictionary. Returns:
            `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
        )copydeepcopy__dict__r   r   r   r   rb      s   zCacheConfig.to_dictc                 c   s*    t | j D ]	\}}||fV  q	dS )zTallows `dict(obj)` for situations where obj may be a dict or QuantizationConfigMixinN)ri   rj   rk   rN   )r   attrrX   r   r   r   __iter__   s   zCacheConfig.__iter__c                 C   s   | j j d|   S )N )r   r@   to_json_stringr   r   r   r   __repr__   s   zCacheConfig.__repr__c                 C   s   t j| jddd S )z
        Serializes this instance to a JSON formatted string.
        Returns:
            str: JSON formatted string representing the configuration instance.
        r]   )r^   r`   )rc   rd   rk   r   r   r   r   ro      s   zCacheConfig.to_json_stringc                    sP   g  |  D ]\}}t| |rt| ||  | q fdd|  D }|S )a  
        Updates attributes of this class instance with attributes from `kwargs` if they match existing attributes,
        returning all the unused kwargs.

        Args:
            kwargs (`Dict[str, Any]`):
                Dictionary of attributes to tentatively update this class.

        Returns:
            `Dict[str, Any]`: Dictionary containing all the key-value pairs that were not used to update the instance.
        c                    s   i | ]\}}| vr||qS r   r   ).0rW   rX   rV   r   r   
<dictcomp>   s    z&CacheConfig.update.<locals>.<dictcomp>)rN   r=   rO   rP   )r   rT   rW   rX   unused_kwargsr   rr   r   r%      s   

zCacheConfig.update)r@   rA   rB   rC   __annotations__classmethodrY   r	   rH   osPathLikerh   r   r   rb   rm   rp   ro   r%   r   r   r   r   rL   e   s   
 
	rL   c                   @   st   e Zd ZdZddddddejdfded	ee d
ee dee dee dee deej	 dee fddZ
dd ZdS )QuantizedCacheConfiga  
    Configuration class for quantized cache settings.

    Attributes:
        backend (`str`, *optional*, defaults to `"quanto"`):
            Backend to use when performing quantization, Can be one of [`quanto`, `HQQ`]
        nbits (`Optional[int]`, *optional*, defaults to 4):
            Number of bits, can be 2 or 4 for the `quanto` backend and one of [1, 2, 3, 4, 8] for the `HQQ` backend. Defaults to 2.
        axis_key (`int`, *optional*, defaults to 0):
            Axis over which to perform grouping for the key tensors. Can be [0, -1] for `quanto` backend and [0, 1] for `HQQ` backend.
        axis_value (`int`, *optional*, defaults to 0):
            Axis over which to perform grouping for the value tensors. Can be [0, -1] for `quanto` backend and [0, 1] for `HQQ` backend.
        q_group_size (`Optional[int]`, *optional*, defaults to 64):
            Size of the quantization group, should be a divisor of the model's hidden dimension.
            Defaults to 64.
        residual_length (`Optional[int]`, *optional*, defaults to 128):
            Length of the residual cache which will always be stored in original precision.
            Defaults to 128.
        compute_dtype (`torch.dtype`, *optional*, defaults to `torch.float16`):
            The default dtype used for computations in the model. Keys and Values will be cast to this dtype after dequantization.
        device (`str`, *optional*, defaults to `"cpu"`):
            Device on which to perform computations, should be same as the model's device.
    quanto   r   @      cpubackendnbitsaxis_key
axis_valueq_group_sizeresidual_lengthcompute_dtyper5   c	           	      C   s4   || _ || _|| _|| _|| _|| _|| _|| _d S r   )r   r   r   r   r   r   r   r5   )	r   r   r   r   r   r   r   r   r5   r   r   r   r      s   
zQuantizedCacheConfig.__init__c                 C   s   d}| j dvrt|jdd| j d| jdkr"t|jdd| jd| jdk r2t|jd	d| jd| jd
vrBt|jdd| jd| jd
vrRt|jdd| jddS )-Validates if the arguments passed are correctvSome of the keys in `cache_config` are defined incorrectly. `{key}` should be {correct_value}` but found {found_value}r   r]      r{      r   z2 or 4 or 8rW   correct_valuefound_valuer   r   za positive integerr   )r   r   r   z`1` or `0`, `-1`r   z`1` or `0` or `-1`N)r   
ValueErrorformatr   r   r   r   r   incorrect_arg_msgr   r   r   validate   sV   




zQuantizedCacheConfig.validateN)r@   rA   rB   rC   rE   float16rH   r   rG   dtyper   r   r   r   r   r   ry      s8    	
ry   c                   @   s0   e Zd ZdZdZddedefddZdd	 Zd
S )StaticCacheConfigz8
    Configuration class for static cache settings.
    staticr~   
batch_sizemax_cache_lenc                 C   s   || _ || _|| _d S r   )r   r   r5   )r   r   r   r5   r   r   r   r   1  s   
zStaticCacheConfig.__init__c                 C   sH   d}| j dkrt|jdd| j d| jdkr"t|jdd| jddS )r   r   r   r   z> 0r   r   N)r   r   r   r   r   r   r   r   r   6  s&   

zStaticCacheConfig.validateN)r~   )r@   rA   rB   rC   rM   rG   r   r   r   r   r   r   r   )  s
    r   c                       sh  e Zd ZdZd-deddf fddZdedeee	j
  fdd	Zd
d Zdd Z	d-de	j
de	j
dedeeeef  dee	j
e	j
f f
ddZd.dee defddZdee fddZdeee	j
 ee	j
 f fddZed-deeee	j   dd fddZdefddZd ed!eded  fd"d#Zed$ed  dd fd%d&Zd'efd(d)Zd*e	j
fd+d,Z  ZS )/DynamicCachea  
    A cache that grows dynamically as more tokens are generated. This is the default for generative models.

    It stores the Key and Value states as a list of tensors, one for each layer. The expected shape for each tensor is
    `[batch_size, num_heads, seq_len, head_dim]`.

    Example:

        ```python
        >>> from transformers import AutoTokenizer, AutoModelForCausalLM, DynamicCache

        >>> model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
        >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")

        >>> inputs = tokenizer(text="My name is Qwen2", return_tensors="pt")

        >>> # Prepare a cache class and pass it to model's forward
        >>> past_key_values = DynamicCache()
        >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
        >>> outputs.past_key_values # access cache filled with key/values from generation
        DynamicCache()
        ```
    N_distributed_cache_datar!   c                    sR   t    d| _g | _g | _|d ur%|D ]\}}| j| | j| qd S d S Nr   )r   r   r:   r3   r8   rP   )r   r   r   r   r   r   r   r   j  s   
zDynamicCache.__init__r   c                 C   s8   |t | k r| j| | j| fS tdt |  d| z
        Support for backwards-compatible `past_key_value` indexing, e.g. `past_key_value[0][0].shape[2]` to get the
        sequence length.
        Cache only has . layers, attempted to access layer with index )r2   r3   r8   KeyErrorr'   r   r   r   __getitem__{  s   zDynamicCache.__getitem__c                 c   s.    t t| D ]}| j| | j| fV  qdS )z
        Support for backwards-compatible `past_key_value` iteration, e.g. `for x in past_key_value:` to iterate over
        keys and values
        Nr1   r2   r3   r8   r'   r   r   r   rm     s   zDynamicCache.__iter__c                 C   
   t | jS z
        Support for backwards-compatible `past_key_value` length, e.g. `len(past_key_value)`. This value corresponds
        to the number of layers in the model.
        )r2   r3   r   r   r   r   __len__     
zDynamicCache.__len__r   r   r    c                 C   s   |dkr|  j |jd 7  _ |durst| j|krCtt| j|D ]}| jtg  | jtg  q!| j| | j| n0| j| 	 sU|| j|< || j|< ntj
| j| |gdd| j|< tj
| j| |gdd| j|< | j| | j| fS )a  
        Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`.

        Parameters:
            key_states (`torch.Tensor`):
                The new key states to cache.
            value_states (`torch.Tensor`):
                The new value states to cache.
            layer_idx (`int`):
                The index of the layer to cache the states for.
            cache_kwargs (`Dict[str, Any]`, `optional`):
                Additional arguments for the cache subclass. No additional arguments are used in `DynamicCache`.

        Return:
            A tuple containing the updated key and value states.
        r   Ndim)r:   shaper2   r3   r1   rP   rE   tensorr8   r4   cat)r   r   r   r   r    _r   r   r   r%     s    
zDynamicCache.updater   c                 C   sL   t | jdkpt | j|kp| j|   }|s"| j| jd }|S d}|S r&   r   r   )r2   r3   r4   r   )r   r   is_empty_layerlayer_seq_lengthr   r   r   r(     s   zDynamicCache.get_seq_lengthc                 C   s   dS )zeReturns the maximum sequence length of the cache object. DynamicCache does not have a maximum length.Nr   r   r   r   r   r)     s   z DynamicCache.get_max_cache_shapec                 C   s4   d}t t| D ]}|| j| | j| ff7 }q|S )zConverts the `DynamicCache` instance into the its equivalent in the legacy cache format. Used for
        backward compatibility.r   r   )r   legacy_cacher   r   r   r   to_legacy_cache  s   zDynamicCache.to_legacy_cachepast_key_valuesc                 C   s>   |  }|durt t|D ]}|| \}}|||| q|S )zwConverts a cache in the legacy cache format into an equivalent `DynamicCache`. Used for
        backward compatibility.N)r1   r2   r%   rR   r   cacher   r   r   r   r   r   from_legacy_cache  s   zDynamicCache.from_legacy_cacher,   c                 C   s   |dk r|   t| }|   |krdS || _tt| jD ]+}| j|  rI| j| dd|ddf | j|< | j| dd|ddf | j|< qdS )zCrop the past key values up to a new `max_length` in terms of tokens. `max_length` can also be
        negative to remove `max_length` tokens. This is used in assisted decoding and contrastive search.r   N.)r(   absr:   r1   r2   r3   r4   r8   )r   r,   idxr   r   r   crop  s   ""zDynamicCache.cropfull_batch_size
split_sizec                    sb   g }t d|D ]& t }| j|_ fdd| jD |_ fdd| jD |_|| q|S )Split the current instance into a list of `DynamicCache` by the batch size. This will be used by
        `_split_model_inputs()` in `generation.utils`r   c                       g | ]
}|    qS r   r   rq   r   ir   r   r   
<listcomp>      z,DynamicCache.batch_split.<locals>.<listcomp>c                    r   r   r   r   r   r   r   r     r   )r1   r   r:   r3   r8   rP   )r   r   r   outcurrent_splitr   r   r   batch_split  s   zDynamicCache.batch_splitsplitsc                    sv   |  }t t|d D ]-  fdd|D } fdd|D }|g kr8tj|dd}tj|dd}|||  q|S )This is the opposite of the above `batch_split()` method. This will be used by `stack_model_outputs` in
        `generation.utils`r   c                    $   g | ]}|j    r|j   qS r   )r3   r4   rq   currentr   r   r   r        $ z2DynamicCache.from_batch_splits.<locals>.<listcomp>c                    r   r   )r8   r4   r   r   r   r   r     r   r   )r1   r2   rE   r   r%   )rR   r   r   r3   r8   
layer_keyslayer_valuesr   r   r   from_batch_splits  s   zDynamicCache.from_batch_splitsrepeatsc                 C   sJ   t t| D ]}| j| j|dd| j|< | j| j|dd| j|< qdS )TRepeat the cache `repeats` times in the batch dimension. Used in contrastive search.r   r   N)r1   r2   r3   repeat_interleaver8   )r   r   r   r   r   r   batch_repeat_interleave  s   z$DynamicCache.batch_repeat_interleaveindicesc                 C   sF   t t| D ]}| j| |df | j|< | j| |df | j|< qdS )XOnly keep the `indices` in the batch dimension of the cache. Used in contrastive search..Nr   )r   r   r   r   r   r   batch_select_indices  s   z!DynamicCache.batch_select_indicesr   r?   )r@   rA   rB   rC   r   r   rG   r   r   rE   rF   r   rm   r   r   r   rH   r   r%   r(   r)   r   rv   FloatTensorr   r   r   r   r   r   rK   r   r   r   r   r   Q  s:    

/"$
r   dynamic_cachec                 C   sD   t | ts	tdtstd t| dt| dd}tjj	
|S )zTFlattens DynamicCache into flat list of tensors for `torch.export.export` to consumezFThis pytree flattening function should only be applied to DynamicCachez[DynamicCache + torch.export is tested on torch 2.6.0+ and may not work on earlier versions.r3   r8   r3   r8   )
isinstancer   RuntimeErrorr   r;   r<   getattrrE   utils_pytree_dict_flattenr   
dictionaryr   r   r   _flatten_dynamic_cache  s   
r   c                 C   s$   t | dt | dd}tjj|S )Nr3   r8   r   )r   rE   r   r   _dict_flatten_with_keysr   r   r   r    _flatten_with_keys_dynamic_cache1  s   r   contextc                 C   s8   t jj| |}t }| D ]
\}}t||| q|S r   )rE   r   r   _dict_unflattenr   rN   rO   )valuesr   r   r   kvr   r   r   _unflatten_dynamic_cache9  s
   r   c                 C   s(   t | dt | dd}tjj|d S )Nr3   r8   r   r   )r   rE   r   r   tree_flatten)r   specr   r   r   r   _flatten_dynamic_cache_for_fxD  s   r   z2.3.)serialized_type_nameflatten_with_keys_fnc                       s   e Zd ZdZd fddZdefddZdefd	d
Zdedee	e
j  fddZde
jfddZ	dde
jde
jdedeeeef  de	e
je
jf f
ddZdZdZ  ZS )OffloadedCachea  
    A drop-in replacement for DynamicCache that conserves accelerator(GPU, XPU) memory at the expense of more CPU memory.
    Useful for generating from models with very long context.

    In addition to the default accelerator stream, where all forward() computations happen,
    this class uses another stream, the prefetch stream, which it creates itself.
    Since scheduling of operations on separate streams happens independently, this class uses
    the prefetch stream to asynchronously prefetch the KV cache of layer k+1 when layer k is executing.
    The movement of the layer k-1 cache to the CPU is handled by the default stream as a simple way to
    ensure the eviction is scheduled after all computations on that cache are finished.
    r!   Nc                    s   t j s tdddrt j s tdtdddrd d t   g | _d | _	tdddr5t 
 nt j
 | _	d | _d S )N2.7T
accept_devz*OffloadedCache can only be used with a GPUz or XPU )rE   cudais_availabler   xpur   r   r   original_deviceprefetch_streamStreamr/   r   r   r   r   r   e  s(   


zOffloadedCache.__init__r   c                 C   s   |t | k rHtdddr| jntj| j( | j| }| j| j|dd| j|< | j	| j|dd| j	|< W d   dS 1 sAw   Y  dS dS )z'Starts prefetching the next layer cacher   Tr   non_blockingN)
r2   r   r   rE   r   streamr   r3   r7   r8   )r   r   r5   r   r   r   prefetch_layerw  s   

"zOffloadedCache.prefetch_layerc                 C   sX   t | dkr*|d t |  }| j| jddd| j|< | j| jddd| j|< dS dS )z)Moves the previous layer cache to the CPUr]   r   r~   Tr   N)r2   r3   r7   r8   )r   r   prev_layer_idxr   r   r   evict_previous_layer  s
   z#OffloadedCache.evict_previous_layerc                 C   s   |t | k r]tdddrtj   ntj   | | | j| }| j	  | j
| }| j| }| jdurN| j|| _|d| j}|d| j}| |d t |   ||fS tdt |  d| )	z_Gets the cache for this layer to the device. Prefetches the next and evicts the previous layer.r   Tr   Nr   r   r   r   )r2   r   rE   acceleratorcurrent_streamsynchronizer   r  r   r   r3   r8   r/   r7   r6   r   r   )r   r   r   
key_tensorvalue_tensorr   r   r   r     s    





zOffloadedCache.__getitem__r/   c                 C   s   | ` | | _ dS )zTSaves the beam indices and reorders the cache when the tensor is back to its device.N)r/   cloner   r/   r   r   r   r9     s   zOffloadedCache.reorder_cacher   r   r    c                 C   s   |dkr|  j |jd 7  _ t| j|k rtdt| j|kr9| j| | j| | j|j | 	| n| | \}}t
j||gdd| j|< t
j||gdd| j|< | j| | j| fS )a  
        Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`.
        Parameters:
            key_states (`torch.Tensor`):
                The new key states to cache.
            value_states (`torch.Tensor`):
                The new value states to cache.
            layer_idx (`int`):
                The index of the layer to cache the states for.
            cache_kwargs (`Dict[str, Any]`, `optional`):
                Additional arguments for the cache subclass. No additional arguments are used in `OffloadedCache`.
        Return:
            A tuple containing the updated key and value states.
        r   r   zWOffloadedCache does not support model usage where layers are skipped. Use DynamicCache.r   )r:   r   r2   r3   r   rP   r8   r   r5   r  rE   r   )r   r   r   r   r    r  r  r   r   r   r%     s   zOffloadedCache.updater!   Nr   )r@   rA   rB   rC   r   rG   r   r  r   r   rE   rF   r   rI   r9   r   r   rH   r   r%   r   r   rK   r   r   r   r   r   X  s*    
*r   c                       s   e Zd ZdZdeddf fddZ	ddejdejd	ed
e	e
eef  deejejf f
ddZdd	e	e defddZdd Zdd Z  ZS )QuantizedCacheaK  
    A quantizer cache similar to what is described in the [KIVI: A Tuning-Free Asymmetric 2bit Quantization for KV Cache paper](https://arxiv.org/abs/2402.02750).
    It allows the model to generate longer sequence length without allocating too much memory for Key and Value cache by applying quantization.

    The cache has two types of storage, one for original precision and one for the quantized cache. A `residual length` is set as a maximum capacity for the
    original precision cache. When the length goes beyond maximum capacity, the original precision cache is discarded and moved into the quantized cache. The
    quantization is done per-channel with a set `q_group_size` for both Keys and Values, in contrast to what was described in the paper.

    It stores Keys and Values a list of quantized tensors (tuples in case we need to store metadata), one for each layer. Additionally, it stores the Key and
    Value in original precision states as a list of tensors, one for each layer. The size of each tensor
    is `[batch_size, num_heads, seq_len - residual_length, head_dim]`
    cache_configr!   Nc                    s\   t    g | _g | _|j| _|j| _|j| _|j| _|j| _|j	| _	|j
| _
t    d S r   )r   r   _quantized_key_cache_quantized_value_cacher   r   r   r   r   r   r5   r   r  r   r   r   r     s   
zQuantizedCache.__init__r   r   r   r    c           	      C   s  |dkr|  j |jd 7  _ t| j|k rtdt| j|kra| j| j| | j	d | j
| j| | jd | jtjd|j|jd | jtjd|j|jd ||}}||fS | | j| }| | j
| }|| j| |g}|| j| |g}tj|dd}tj|dd}| j|  dkr| j| jd d | jkr| j| | j	d| j|< | j| | jd| j
|< tjd|j|jd| j|< tjd|j|jd| j|< ||fS tj| j| |gdd| j|< tj| j| |gdd| j|< ||fS )	Nr   r   zWQuantizedCache does not support model usage where layers are skipped. Use DynamicCache.)axisr   r5   r   r{   r   )r:   r   r2   r3   r   r  rP   	_quantize
contiguousr   r  r   rE   zerosr   r5   r8   _dequantizer   r   r   )	r   r   r   r   r    keys_to_returnvalues_to_returndequant_keydequant_valuer   r   r   r%     s:   

zQuantizedCache.updater   c                 C   s*   t | j|kr	dS |dkr| jS | jd S )r&   r   r   )r2   r3   r:   r'   r   r   r   r(   #  s   zQuantizedCache.get_seq_lengthc                 C   r"   )z:Quantizes a key/value using a defined quantization method.z1Make sure to implement `_quantize` in a subclass.r#   )r   r   r  r   r   r   r  ,  r*   zQuantizedCache._quantizec                 C   r"   )zDDequantizes back the tensor that was quantized by `self._quantize()`z3Make sure to implement `_dequantize` in a subclass.r#   )r   q_tensorr   r   r   r  0  r*   zQuantizedCache._dequantizer   r?   )r@   rA   rB   rC   ry   r   rE   rF   rG   r   r   rH   r   r   r%   r(   r  r  rK   r   r   r   r   r
    s$    
+	r
  c                       :   e Zd ZdZdeddf fddZdd Zd	d
 Z  ZS )QuantoQuantizedCachea  
    Quantized Cache class that uses `quanto` as a backend to perform quantization. Current implementation supports `int2` and `int4` dtypes only.

    Parameters:
        cache_config (`QuantizedCacheConfig`):
            A configuration containing all the arguments to be used by the quantizer, including axis, qtype and group size.

    Example:

        ```python
        >>> # Run pip install quanto first if you don't have it yet
        >>> from transformers import AutoTokenizer, AutoModelForCausalLM, QuantoQuantizedCache, QuantizedCacheConfig

        >>> model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
        >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")

        >>> inputs = tokenizer(text="My name is Qwen2", return_tensors="pt")

        >>> # Prepare a cache class and pass it to model's forward
        >>> cache_config = QuantizedCacheConfig(nbits=4)
        >>> past_key_values = QuantoQuantizedCache(cache_config=cache_config)
        >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
        >>> outputs.past_key_values # access cache filled with key/values from generation
        QuantoQuantizedCache()
        ```
    r  r!   Nc                    s   t  | t r+ttjd}|tdkr!td| dddlm	}m
}m} | jdvr8td| j | jd	vrEtd
| j | jd	vrRtd| j | jdkrY|n|| _| | _d S )Nzoptimum-quantoz0.2.5zzYou need optimum-quanto package version to be greater or equal than 0.2.5 to use `QuantoQuantizedCache`. Detected version r   r   )MaxOptimizerqint2qint4)r]   r{   zA`nbits` for `quanto` backend has to be one of [`2`, `4`] but got )r   r   zE`axis_key` for `quanto` backend has to be one of [`0`, `-1`] but got zG`axis_value` for `quanto` backend has to be one of [`0`, `-1`] but got r{   )r   r   r   r
   parse	importlibmetadataImportErroroptimum.quantor  r  r  r   r   r   r   qtype	optimizer)r   r  optimum_quanto_versionr  r  r  r   r   r   r   Q  s$   




zQuantoQuantizedCache.__init__c                 C   sH   t  r"ddlm} | || j|| j\}}||| j|||| j}|S d S )Nr   )quantize_weight)r   r#  r'  r%  r$  r   )r   r   r  r'  scale	zeropointqtensorr   r   r   r  j  s   zQuantoQuantizedCache._quantizec                 C   s   |  S r   )
dequantize)r   r*  r   r   r   r  s  s   z QuantoQuantizedCache._dequantize	r@   rA   rB   rC   rL   r   r  r  rK   r   r   r   r   r  5  s
    	r  c                       r  )HQQQuantizedCachea  
    Quantized Cache class that uses `HQQ` as a backend to perform quantization. Current implementation supports `int2`, `int4`, `int8` dtypes.

    Parameters:
        cache_config (`QuantizedCacheConfig`):
            A configuration containing all the arguments to be used by the quantizer, including axis, qtype and group size.

    Example:

        ```python
        >>> # Run pip install hqq first if you don't have it yet
        >>> from transformers import AutoTokenizer, AutoModelForCausalLM, HQQQuantizedCache, QuantizedCacheConfig

        >>> model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
        >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")

        >>> inputs = tokenizer(text="My name is Qwen2", return_tensors="pt")

        >>> # Prepare a cache class and pass it to model's forward
        >>> cache_config = QuantizedCacheConfig(nbits=4, axis_key=1, axis_value=1)
        >>> past_key_values = HQQQuantizedCache(cache_config=cache_config)
        >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
        >>> outputs.past_key_values # access cache filled with key/values from generation
        HQQQuantizedCache()
        ```
    r  r!   Nc                    sd   t  | | jdvrtd| j | jdvr td| j | jdvr-td| j t| _d S )Nr   zM`nbits` for `HQQ` backend has to be one of [`1`, `2`, `3`, `4`, `8`] but got )r   r   zA`axis_key` for `HQQ` backend has to be one of [`0`, `1`] but got zC`axis_value` for `HQQ` backend has to be one of [`0`, `1`] but got )r   r   r   r   r   r   HQQQuantizer	quantizerr  r   r   r   r     s   




zHQQQuantizedCache.__init__c                 C   sJ   | j j||| j| j| j| jd\}}| j|d< | j j||| jd ||fS )N)r  r5   r   r   
group_sizer   )metar5   )r/  quantizer5   r   r   r   r   )r   r   r  r*  r1  r   r   r   r    s   

zHQQQuantizedCache._quantizec                 C   s   |\}}| j ||}|S r   )r/  r+  )r   r*  quant_tensorr1  r   r   r   r   r    s   zHQQQuantizedCache._dequantizer,  r   r   r   r   r-  w  s
    r-  c                       s   e Zd ZdZdZdededdf fddZed	d
 Zde	j
de	j
de	j
de	j
fddZde	j
de	j
de	j
dee	j
e	j
f fddZddee defddZdee fddZ	dde	j
de	j
dedeeeef  dee	j
e	j
f f
ddZ  ZS )	SinkCachea  
    A cache that as described in the [Attention Sinks paper](https://arxiv.org/abs/2309.17453). It allows the model to
    generate beyond the length of its context window, without losing fluency in the conversation. As it discards past
    tokens, the model will lose the ability to generate tokens that depend on the context that was discarded.

    It stores the Key and Value states as a list of tensors, one for each layer. The expected shape for each tensor is
    `[batch_size, num_heads, seq_len, head_dim]`.

    Parameters:
        window_length (`int`):
            The length of the context window.
        num_sink_tokens (`int`):
            The number of sink tokens. See the original paper for more information.

    Example:

        ```python
        >>> from transformers import AutoTokenizer, AutoModelForCausalLM, SinkCache

        >>> model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
        >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")

        >>> inputs = tokenizer(text="My name is Qwen2", return_tensors="pt")

        >>> # Prepare a cache class and pass it to model's forward
        >>> past_key_values = SinkCache(window_length=256, num_sink_tokens=4)
        >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
        >>> outputs.past_key_values # access cache filled with key/values from generation
        SinkCache()
        ```
    Twindow_lengthnum_sink_tokensr!   Nc                    s>   t    g | _g | _|| _|| _i | _d | _d | _d| _	d S r   )
r   r   r3   r8   r5  r6  cos_sin_rerotation_cache
_cos_cache
_sin_cacher:   )r   r5  r6  r   r   r   r     s   

zSinkCache.__init__c                 C   sH   | dd | j d d f }| d| j d d d f }tj| |fddS )N.r   r]   r   )r   rE   r   )xx1x2r   r   r   _rotate_half  s   zSinkCache._rotate_halfr   cossinc                 C   s   || |  ||  }|S r   )r=  )r   r   r>  r?  rotated_key_statesr   r   r   _apply_key_rotary_pos_emb  s   z#SinkCache._apply_key_rotary_pos_embc           
      C   s   |j d | jvrk|tj}|tj}|| j|j d  d  }|| j|j d   }|| j|j d  d  }|| j|j d   }|| ||  }| | ||  }	||jd|	|jdf| j|j d < | j|j d  S )Nr   r   )r   r7  r7   rE   float32r6  r   	unsqueeze)
r   r   r>  r?  original_cosshifted_cosoriginal_sinshifted_sinrerotation_cosrerotation_sinr   r   r   _get_rerotation_cos_sin  s   z!SinkCache._get_rerotation_cos_sinr   r   c                 C   s"   t | j|kr	dS | j| jd S r   )r2   r3   r   r'   r   r   r   r(     s   zSinkCache.get_seq_lengthc                 C      | j S )zfReturns the maximum sequence length of the cache object, in case of SinkCache it is the window length.)r5  r   r   r   r   r)     s   zSinkCache.get_max_cache_shaper   r    c                 C   s  |du ri }| d}| d}| d}|duo|du}|dkr+|  j|jd 7  _|rq|dkrq| dkr>|| _|| _n3| jdu rN|d | _|d | _n#| jjd | jk rqtj| j|d gdd	| _tj| j|d gdd	| _t	| j
|kr| j
| | j| n|jd | | | jk rtj| j
| |gdd	| j
|< tj| j| |gdd	| j|< n| j
| dddd| j | j |jd  df }	|r| || jd| j | jd| j \}
}|dur|	d
d|f |	d
|df }	}| |	|
|}	|durtj|	|fdd	}	| j
| ddddd| jf }tj||	|gdd	| j
|< | j| ddddd| jf }| j| dddd| j | j |jd  df }tj|||gdd	| j|< | j
| | j| fS )a;  
        Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`.

        Parameters:
            key_states (`torch.Tensor`):
                The new key states to cache.
            value_states (`torch.Tensor`):
                The new value states to cache.
            layer_idx (`int`):
                The index of the layer to cache the states for.
            cache_kwargs (`Dict[str, Any]`, `optional`):
                Additional arguments for the cache subclass. The following arguments can be used in `SinkCache`: `sin`,
                `cos` and `partial_rotation_size`. These arguments are used with models using RoPE, to recompute the
                rotation as the tokens are shifted.

        Return:
            A tuple containing the updated key and value states.
        Nr?  r>  partial_rotation_sizer   r   r]   )r   .r   .r   )getr:   r   r   r8  r9  r5  rE   r   r2   r3   rP   r8   r(   r6  rJ  rA  )r   r   r   r   r    r?  r>  rL  
using_ropekeys_to_keeprH  rI  	keys_pass	sink_keyssink_valuesvalues_to_keepr   r   r   r%     s\   




 (
""(zSinkCache.updater?   r   )r@   rA   rB   rC   
is_slidingrG   r   staticmethodr=  rE   rF   rA  r   rJ  r   r(   r)   r   rH   r   r%   rK   r   r   r   r   r4    sL     


	r4  c                       s   e Zd ZdZdZddejdfdedede	e de
ejedf dejd	e	eee
eejef f  d
df fddZ	ddejdejdede	eeef  d
eejejf f
ddZdde	e d
efddZd
e	e fddZdd Z  ZS )StaticCachea	  
    Static Cache class to be used with `torch.compile(model)` and `torch.export()`.

    Parameters:
        config (`PretrainedConfig`):
            The configuration file defining the shape-related attributes required to initialize the static cache.
        max_batch_size (`int`):
            The maximum batch size with which the model will be used. Note that a new instance must be instantiated if a
            smaller batch size is used. If you are manually setting the batch size, make sure to take into account the
            number of beams if you are running beam search
        max_cache_len (`int`, *optional*):
            The maximum sequence length with which the model will be used.
        device (`torch.device` or `str`, *optional*):
            The device on which the cache should be initialized. If you're using more than 1 computation device, you
            should pass the `layer_device_map` argument instead.
        dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
            The default `dtype` to use when initializing the layer.
        layer_device_map (`Optional[Dict[int, Union[str, torch.device, int]]]]`, *optional*):
            Mapping between the layers and its device. This is required when you are manually initializing the cache
            and the model is split between different gpus. You can know which layers mapped to which device by
            checking the associated device_map: `model.hf_device_map`.


    Example:

        ```python
        >>> from transformers import AutoTokenizer, AutoModelForCausalLM, StaticCache

        >>> model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf")
        >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf")

        >>> inputs = tokenizer(text="My name is Llama", return_tensors="pt")

        >>> # Prepare a cache class and pass it to model's forward
        >>> # Leave empty space for 10 new tokens, which can be used when calling forward iteratively 10 times to generate
        >>> max_generated_length = inputs.input_ids.shape[1] + 10
        >>> past_key_values = StaticCache(config=model.config, max_batch_size=1, max_cache_len=max_generated_length, device=model.device, dtype=model.dtype)
        >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
        >>> outputs.past_key_values # access cache filled with key/values from generation
        StaticCache()
        ```
    TNrU   max_batch_sizer   r5   r   layer_device_mapr!   c                    s  t    || _|d u r|jn|| _t|dr|jn|j|j | _|| _	t
|dd d u r/|jn|j| _g | _g | _| j| j| j| jf}|d urLt|nd }t|jD ]7}|d ur^|| }	n|}	tj|| j	|	d}
tj|| j	|	d}tj|
 tj| | j|
 | j| qSd S )Nhead_dimnum_key_value_headsr  )r   r   rW  max_position_embeddingsr   r=   rY  hidden_sizenum_attention_heads_dtyper   rZ  r3   r8   rE   r5   r1   num_hidden_layersr  _dynamomark_static_addressrP   )r   rU   rW  r   r5   r   rX  cache_shaper   layer_devicenew_layer_key_cachenew_layer_value_cacher   r   r   r     s2   
	
zStaticCache.__init__r   r   r   r    c                 C   s   |du ri }| d}| j| }| j| }||j}||j}|du r3|| || ||fS z|d|| |d|| W ||fS  tyh   ||dddd|f< ||dddd|f< Y ||fS w )a'  
        Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`.
        It is VERY important to index using a tensor, otherwise you introduce a copy to the device.

        Parameters:
            key_states (`torch.Tensor`):
                The new key states to cache.
            value_states (`torch.Tensor`):
                The new value states to cache.
            layer_idx (`int`):
                The index of the layer to cache the states for.
            cache_kwargs (`Dict[str, Any]`, `optional`):
                Additional arguments for the cache subclass. The `StaticCache` needs the `cache_position` input
                to know how where to write in the cache.

        Return:
            A tuple containing the updated key and value states.
        Ncache_positionr]   )rM  r3   r8   r7   r   copy_index_copy_r$   )r   r   r   r   r    rf  k_outv_outr   r   r   r%     s(   




zStaticCache.updater   c                 C   s   | j | d jdd S )MReturns the sequence length of the cached states that were seen by the model.r   r   r   r   )r3   anysumr'   r   r   r   r(     s   zStaticCache.get_seq_lengthc                 C   rK  r   r   r   r   r   r   r)        zStaticCache.get_max_cache_shapec                 C   4   t t| jD ]}| j|   | j|   qdS 4Resets the cache values while preserving the objectsNr1   r2   r3   zero_r8   r'   r   r   r   reset     zStaticCache.resetr   r?   )r@   rA   rB   rC   rD   rE   rB  r   rG   r   r	   r5   rH   r   r   r   rF   r   r   r%   r(   r)   rv  rK   r   r   r   r   rV  r  sJ    +1
2rV  c                       s   e Zd ZdZdZdZddejdfdede	de
e	 deejedf dejd	e
ee	eeeje	f f  d
df fddZ	ddejdejde	de
eeef  d
eejejf f
ddZd
e
e	 fddZdd Z  ZS )SlidingWindowCachea;  
    Sliding Window Cache class to be used with `torch.compile` for models like Mistral that support sliding window attention.
    Every time when we try to update the cache, we compute the `indices` based on `cache_position >= self.config.sliding_window - 1`,
    if true(which means the cache can not hold all the old key value states and new states together because of the sliding window constraint),
    we need to do a cycle shift based on `indices` to replace the oldest states by the new key value states passed in.

    The `to_shift` is only true once we are above sliding_window. Thus with `sliding_window==64`:

    indices = (slicing + to_shift[-1].int()-1) % self.config.sliding_window
    tensor([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
        19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
        37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
        55, 56, 57, 58, 59, 60, 61, 62, 63,  0])

    We overwrite the cache using these, then we always write at cache_position (clamped to `sliding_window`)

    Parameters:
        config (`PretrainedConfig`):
            The configuration file defining the shape-related attributes required to initialize the static cache.
        max_batch_size (`int`):
            The maximum batch size with which the model will be used. Note that a new instance must be instantiated if a
            smaller batch size is used.
        max_cache_len (`int`, *optional*):
            The maximum sequence length with which the model will be used.
        device (`torch.device` or `str`, *optional*):
            The device on which the cache should be initialized. If you're using more than 1 computation device, you
            should pass the `layer_device_map` argument instead.
        dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
            The default `dtype` to use when initializing the layer.
        layer_device_map (`Optional[Dict[int, Union[str, torch.device, int]]]]`, *optional*):
            Mapping between the layers and its device. This is required when you are manually initializing the cache
            and the model is split between different gpus. You can know which layers mapped to which device by
            checking the associated device_map: `model.hf_device_map`.

    Example:

        ```python
        >>> from transformers import AutoTokenizer, AutoModelForCausalLM, SlidingWindowCache

        >>> model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-Instruct-v0.3")
        >>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.3")

        >>> inputs = tokenizer(text="My name is Mistral", return_tensors="pt")

        >>> # Prepare a cache class and pass it to model's forward
        >>> # Leave empty space for 10 new tokens, which can be used when calling forward iteratively 10 times to generate
        >>> max_generated_length = inputs.input_ids.shape[1] + 10
        >>> past_key_values = SlidingWindowCache(config=model.config, max_batch_size=1, max_cache_len=max_generated_length, device=model.device, dtype=model.dtype)
        >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
        >>> outputs.past_key_values # access cache filled with key/values from generation
        SlidingWindowCache()
        ```
    TNrU   rW  r   r5   r   rX  r!   c                    sD   t |dr
|jd u rtdt|j|}t j||||||d d S )Nsliding_windowSetting `cache_implementation` to 'sliding_window' requires the model config supporting sliding window attention, please check if there is a `sliding_window` field in the model config and it's not set to None.)rU   rW  r   r5   r   rX  )r=   ry  r   minr   r   r   rU   rW  r   r5   r   rX  r   r   r   r   J  s   	
zSlidingWindowCache.__init__r   r   r   r    c                 C   s  |d u ri }| d}| j| }| j| }||j}||j}|jd | jkrc|d d d d | j d d d f }|d d d d | j d d d f }| j|  |7  < | j|  |7  < ||fS tj| jtj	|j
dd}|d| jd }|| jd k}	||	d   d | j }
|d d d d |
f }|d d d d |
f }z|d|| |d|| W n ty   ||d d d d |f< ||d d d d |f< Y nw | j|   | j|   | j|  |7  < | j|  |7  < ||fS )Nrf  r   r  r   r   r]   )rM  r3   r8   r7   r   r   r   rE   oneslongr5   cumsumclamprG   rh  r$   ru  )r   r   r   r   r    rf  ri  rj  slicingto_shiftr   r   r   r   r%   c  s>   


$$zSlidingWindowCache.updatec                 C   rK  r   ro  r   r   r   r   r)     rp  z&SlidingWindowCache.get_max_cache_shapec                 C   4   t t| jD ]}| j|   | j|   qd S r   rt  r'   r   r   r   rv       zSlidingWindowCache.resetr   )r@   rA   rB   rC   rT  rD   rE   rB  r   rG   r   r	   r5   rH   r   r   r   rF   r   r   r%   r)   rv  rK   r   r   r   r   rx    sJ    6
3rx  c                       s2  e Zd ZdZdedef fddZdedeee	j
  fdd	Zd
d Zdeee	j
 ee	j
 f fddZe	d.deeee	j   dd fddZd/dee defddZdd Zde	jfddZdefddZdefddZd ed!edd"fd#d$Zed%ed  dd fd&d'Zd(efd)d*Zd+e	j
fd,d-Z  ZS )0EncoderDecoderCachea  
    Base, abstract class for all encoder-decoder caches. Can be used to hold combinations of self-attention and
    cross-attention caches.

    Example:

        ```python
        >>> from transformers import AutoProcessor, AutoModelForCausalLM, DynamicCache, EncoderDecoderCache

        >>> model = AutoModelForCausalLM.from_pretrained("openai/whisper-small")
        >>> processor = AutoProcessor.from_pretrained("openai/whisper-small")

        >>> inputs = processor(audio=YOUR-AUDIO, return_tensors="pt")

        >>> # Prepare cache classes for encoder and decoder and pass it to model's forward
        >>> self_attention_cache = DynamicCache()
        >>> cross_attention_cache = DynamicCache()
        >>> past_key_values = EncoderDecoderCache(self_attention_cache, cross_attention_cache)
        >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
        >>> outputs.past_key_values # access cache filled with key/values from generation
        EncoderDecoderCache()
        ```

    self_attention_cachecross_attention_cachec                    s\   t    || _|| _t| jdd| _i | _tt|j	D ]}t
||dk| j|< qd S )NrD   Fr   )r   r   r  r  r   rD   
is_updatedr1   r2   r3   boolr(   )r   r  r  r   r   r   r   r     s   
zEncoderDecoderCache.__init__r   r!   c                 C   sP   |t | k r| jj| | jj| | jj| | jj| fS tdt |  d| r   )r2   r  r3   r8   r  r   r'   r   r   r   r     s   



zEncoderDecoderCache.__getitem__c                 C   r   r   )r2   r  r   r   r   r   r     r   zEncoderDecoderCache.__len__c                 C   sR   d}t | jdkr"t| j | j D ]\}}||| f7 }q|S | j }|S )z\Converts the `EncoderDecoderCache` instance into  its equivalent in the legacy cache format.r   r   )r2   r  zipr  r   )r   r   	self_attn
cross_attnr   r   r   r     s   
z#EncoderDecoderCache.to_legacy_cacheNr   c                 C   s   | t  t  d}|durFtt|D ]3}|| dd \}}|j||| t|| dkrE|| dd \}}|j||| d|j|< q|S )zUConverts a cache in the legacy cache format into an equivalent `EncoderDecoderCache`.)r  r  Nr]   T)r   r1   r2   r  r%   r  r  r   r   r   r   r     s   
z%EncoderDecoderCache.from_legacy_cacher   c                 C   s   | j |S )r&   )r  r(   r'   r   r   r   r(     s   z"EncoderDecoderCache.get_seq_lengthc                 C   s   t | jdr| j  t | jdr| j  nt | jds4t | jds4td| j  d| j  d| jD ]}d| j|< q7d S )Nrv  zNeither self nor cross-attention cache have valid `.reset()` methods. `.reset()` should only be called on compatible cache classes, such as `StaticCache` or `SlidingWindowCache`. Got " for the self attention cache and  for the cross attention cache.F)r=   r  rv  r  r   __str__r  r'   r   r   r   rv    s   

zEncoderDecoderCache.resetr/   c                 C   s   | j | | j| dS )r0   N)r  r9   r  r  r   r   r   r9     s   z!EncoderDecoderCache.reorder_cachemethodc                 C   sD   t | jtrt | jts td| d| j  d| j  dd S )N`z)` is only defined for dynamic cache, got r  r  )r   r  r   r  r   r  )r   r  r   r   r   check_dynamic_cache  s   

z'EncoderDecoderCache.check_dynamic_cachemaximum_lengthc                 C   s   |  | jj | j| dS )zCrop the past key values up to a new `maximum_length` in terms of tokens. `maximum_length` can also be
        negative to remove `maximum_length` tokens. This is used in assisted decoding and contrastive search.N)r  r   r@   r  )r   r  r   r   r   r     s   zEncoderDecoderCache.cropr   r   zList[EncoderDecoderCache]c                 C   sV   |  | jj | j||}| j||}g }t||D ]\}}|t|| q|S )r   )r  r   r@   r  r  r  rP   r  )r   r   r   r  r  r   r  r  r   r   r   r   #  s   zEncoderDecoderCache.batch_splitr   c                    s   t  }t  }tt|d D ]H tj fdd|D dd}tj fdd|D dd}|||  tj fdd|D dd}tj fdd|D dd}|||  q| ||S )r   r   c                       g | ]}|j j  qS r   )r  r3   r   r   r   r   r   6      z9EncoderDecoderCache.from_batch_splits.<locals>.<listcomp>r   c                    r  r   )r  r8   r   r   r   r   r   7  r  c                    r  r   )r  r3   r   r   r   r   r   :  r  c                    r  r   )r  r8   r   r   r   r   r   ;  r  )r   r1   r2   rE   r   r%   )rR   r   r  r  r   r   r   r   r   r   /  s   
z%EncoderDecoderCache.from_batch_splitsr   c                 C   *   |  | jj | j| | j| dS )r   N)r  r   r@   r  r  )r   r   r   r   r   r   ?     z+EncoderDecoderCache.batch_repeat_interleaver   c                 C   r  )r   N)r  r   r@   r  r  )r   r   r   r   r   r   E  r  z(EncoderDecoderCache.batch_select_indicesr   r?   )r@   rA   rB   rC   r   r   rG   r   r   rE   rF   r   r   r   rv   r   r   r   r(   rv  rI   r9   rH   r  r   r   r   r   r   rK   r   r   r   r   r    s.    
"r  c                       s   e Zd ZdZddejdfdededee de	ej
edf dejdeeee	eej
ef f  d	df fd
dZdd Zdd Z	ddejdejdedeeeef  d	eejejf f
ddZd	ee fddZddee fddZdd Z  ZS )HybridCachea:
  
    Hybrid Cache class to be used with `torch.compile` for Gemma2 models that alternate between a local sliding window attention
    and global attention in every other layer. Under the hood, Hybrid Cache leverages ["SlidingWindowCache"] for sliding window attention
    and ["StaticCache"] for global attention. For more information, see the documentation of each subcomponeent cache class.

    Parameters:
        config (`PretrainedConfig):
            The configuration file defining the shape-related attributes required to initialize the static cache.
        max_batch_size (`int`):
            The maximum batch size with which the model will be used. Note that a new instance must be instantiated if a
            smaller batch size is used.
        max_cache_len (`int`, *optional*):
            The maximum sequence length with which the model will be used.
        device (`torch.device` or `str`, *optional*):
            The device on which the cache should be initialized. If you're using more than 1 computation device, you
            should pass the `layer_device_map` argument instead.
        dtype (torch.dtype, *optional*, defaults to `torch.float32`):
            The default `dtype` to use when initializing the layer.
        layer_device_map (`Optional[Dict[int, Union[str, torch.device, int]]]]`, *optional*):
            Mapping between the layers and its device. This is required when you are manually initializing the cache
            and the model is split between different gpus. You can know which layers mapped to which device by
            checking the associated device_map: `model.hf_device_map`.

    Example:

        ```python
        >>> from transformers import AutoTokenizer, AutoModelForCausalLM, HybridCache

        >>> model = AutoModelForCausalLM.from_pretrained("google/gemma-2-2b")
        >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b")

        >>> inputs = tokenizer(text="My name is Gemma", return_tensors="pt")

        >>> # Prepare a cache class and pass it to model's forward
        >>> # Leave empty space for 10 new tokens, which can be used when calling forward iteratively 10 times to generate
        >>> max_generated_length = inputs.input_ids.shape[1] + 10
        >>> past_key_values = HybridCache(config=model.config, max_batch_size=1, max_cache_len=max_generated_length, device=model.device, dtype=model.dtype)
        >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
        >>> outputs.past_key_values # access cache filled with key/values from generation
        HybridCache()
        ```
    NrU   rW  r   r5   r   rX  r!   c                    s  t    t|dr|jd u rtd|| _|| _t|dr!|jn|j|j	 | _|| _
|jd u r3|j	n|j| _t|dr?|jnd tj fddt|jD tjd| _g | _g | _| j| j|| jf}| j| jt|j|| jf}|d ur~t|tr~t|nd }t|jD ]@}	|d ur||	 }
n|}
| j|	 s|n|}tj|| j
|
d	}tj|| j
|
d	}tj| tj| | j| | j| qd S )
Nry  rz  rY  sliding_window_patternr]   c                       g | ]
}t |d    qS r   r  rq   r   layer_switchr   r   r     r   z(HybridCache.__init__.<locals>.<listcomp>)r   r  )r   r   r=   ry  r   r   rW  rY  r\  r]  r^  rZ  r  rE   r   r1   r_  r  rT  r3   r8   r{  r   rH   r5   r  r`  ra  rP   )r   rU   rW  r   r5   r   rX  global_cache_shapesliding_cache_shaper   rc  rb  rd  re  r   r  r   r   |  sJ   
	
 
zHybridCache.__init__c                 C   sl  |j d |kr?|d d d d | d d d f }|d d d d | d d d f }| j|  |7  < | j|  |7  < ||fS tj|tj|jdd}|d|d }||d k}	||	d 	  d | }
|d d d d |
f }|d d d d |
f }||d d d d |f< ||d d d d |f< | j| 
  | j| 
  | j|  |7  < | j|  |7  < ||fS )Nr   r  r   r   )r   r3   r8   rE   r}  r~  r5   r  r  rG   ru  )r   rf  r   r   r   ri  rj  r   r  r  r   r   r   r   _sliding_update  s&   ""zHybridCache._sliding_updatec                 C   H   ||d d d d |f< ||d d d d |f< || j |< || j|< ||fS r   r   r   rf  r   r   r   ri  rj  r   r   r   r   _static_update  
   

zHybridCache._static_updater   r   r   r    c           
   	   C   s   |d u ri }| d}| d}| j| j|jkr%| j| |j| j|< | j| j|jkr:| j| |j| j|< | j| }| j| }||j}||j}|rV| j}	n| j}	|	|||||||jd S )Nrf  ry  r]   )	rM  r3   r5   r7   r8   r   r  r  r   )
r   r   r   r   r    rf  ry  ri  rj  	update_fnr   r   r   r%     s0   



zHybridCache.updatec                 C   rK  r   ro  r   r   r   r   r)      rp  zHybridCache.get_max_cache_shaper   c                 C   s*   |dkrt d| j| d jdd S Nr   z`get_seq_length` on `HybridCache` may get inconsistent results depending on the layer index. Using the `layer_idx` argument is not supported.rl  r   r   )r   r3   rm  rn  r'   r   r   r   r(     s
   zHybridCache.get_seq_lengthc                 C   rq  rr  rt  r'   r   r   r   rv    rw  zHybridCache.resetr   r?   )r@   rA   rB   rC   rE   rB  r   rG   r   r	   r5   rH   r   r   r   r  r  rF   r   r   r%   r)   r(   rv  rK   r   r   r   r   r  L  sL    39
'r  c                       s   e Zd ZdZdZddejdfdedede	e de
ejedf dejd	e	eee
eejef f  d
df fddZdd Zdd Zdd Z	d dejdejdede	eeef  d
eejejf f
ddZd
e	e fddZd!de	e fddZdd Z  ZS )"HybridChunkedCachea;
  
    Hybrid Cache class to be used with `torch.compile` for Gemma2 models that alternate between a local sliding window attention
    and global attention in every other layer. Under the hood, Hybrid Cache leverages ["SlidingWindowCache"] for sliding window attention
    and ["StaticCache"] for global attention. For more information, see the documentation of each subcomponeent cache class.

    Parameters:
        config (`PretrainedConfig):
            The configuration file defining the shape-related attributes required to initialize the static cache.
        max_batch_size (`int`):
            The maximum batch size with which the model will be used. Note that a new instance must be instantiated if a
            smaller batch size is used.
        max_cache_len (`int`, *optional*):
            The maximum sequence length with which the model will be used.
        device (`torch.device` or `str`, *optional*):
            The device on which the cache should be initialized. If you're using more than 1 computation device, you
            should pass the `layer_device_map` argument instead.
        dtype (torch.dtype, *optional*, defaults to `torch.bfloat16`):
            The default `dtype` to use when initializing the layer.
        layer_device_map (`Optional[Dict[int, Union[str, torch.device, int]]]]`, *optional*):
            Mapping between the layers and its device. This is required when you are manually initializing the cache
            and the model is split between different gpus. You can know which layers mapped to which device by
            checking the associated device_map: `model.hf_device_map`.

    Example:

        ```python
        >>> from transformers import AutoTokenizer, AutoModelForCausalLM, HybridCache

        >>> model = AutoModelForCausalLM.from_pretrained("google/gemma-2-2b")
        >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b")

        >>> inputs = tokenizer(text="My name is Gemma", return_tensors="pt")

        >>> # Prepare a cache class and pass it to model's forward
        >>> # Leave empty space for 10 new tokens, which can be used when calling forward iteratively 10 times to generate
        >>> max_generated_length = inputs.input_ids.shape[1] + 10
        >>> past_key_values = HybridCache(config=model.config, max_batch_size=1, max_cache_len=max_generated_length, device=model.device, dtype=model.dtype)
        >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
        >>> outputs.past_key_values # access cache filled with key/values from generation
        HybridCache()
        ```
    TNrU   rW  r   r5   r   rX  r!   c                    s   t    t|dr|jd u rt| dd| _n|j| _|| _|| _t|d|j|j	 | _
|| _t| dr=|j| _nt|dd  fdd	t|jD | _g | _g | _d
d	 t|jD | _d S )Nry  attention_chunk_sizei    rY  no_rope_layersr  r]   c                    r  r  r  r  r  r   r   r   ]  r   z/HybridChunkedCache.__init__.<locals>.<listcomp>c                 S      g | ]}d qS r?   r   rq   r   r   r   r   r   a      )r   r   r=   ry  r   get_text_configr   rW  r\  r]  rY  r^  r  rT  r1   r_  r3   r8   cumulative_lengthr|  r   r  r   r   F  s   
	
zHybridChunkedCache.__init__c           
      C   s   t | j|kr	d S |jd }|j}| j|| j| jf}| j|| j| jf}| j| r*|n|}t	j
|| j|d}t	j
|| j|d}	t	j| t	j|	 | j| | j|	 d S )Nr   r  )r2   r3   r   r5   rW  r   rY  ry  rT  rE   r  r^  r`  ra  rP   r8   )
r   r   r   rZ  r5   r  r  rb  rd  re  r   r   r   initialise_cache_layerc  s"   
z)HybridChunkedCache.initialise_cache_layerc                 C   s  | j | }| j |  |jd 7  < ||k}	|	rgtj|d d d d dd d d f |fdd}
tj|d d d d dd d d f |fdd}|jd dkrf| j| |
 | j| | | j| | j| fS na|	s||jd  |kr|dkr{|}
|}nMtj|d d d d d |d d f |fdd}
tj|d d d d d |d d f |fdd}n| j| d|| | j| d|| | j| | j| fS | j| |
d d d d | d d d f  | j| |d d d d | d d d f  |
|fS )Nr   r   r   r]   r   )r  r   rE   r   r3   rg  r8   rh  )r   rf  r   r   r   ri  rj  r   r  is_fullfull_key_statesfull_value_statesr   r   r   r  z  s.   
...0..z"HybridChunkedCache._sliding_updatec                 C   r  r   r   r  r   r   r   r    r  z!HybridChunkedCache._static_updater   r   r   r    c           	   	   C   s   |d u ri }| d}| || | j| }| j| }||j}||j}| j| r0| j}n| j}||||||||j	d S )Nrf  r]   )
rM  r  r3   r8   r7   r   rT  r  r  r   )	r   r   r   r   r    rf  ri  rj  r  r   r   r   r%     s(   



zHybridChunkedCache.updatec                 C   rK  r   ro  r   r   r   r   r)     rp  z&HybridChunkedCache.get_max_cache_shaper   c                 C   s<   |dkrt dt| jdkrdS | j| d jdd S r  )r   r2   r3   rm  rn  r'   r   r   r   r(     s   z!HybridChunkedCache.get_seq_lengthc                 C   sN   t t| jD ]}| j|   | j|   qdd t t| jD | _dS )rs  c                 S   r  r?   r   r  r   r   r   r     r  z,HybridChunkedCache.reset.<locals>.<listcomp>N)r1   r2   r3   ru  r8   r  r'   r   r   r   rv    s   zHybridChunkedCache.resetr   r?   )r@   rA   rB   rC   rD   rE   bfloat16r   rG   r   r	   r5   rH   r   r   r   r  r  r  rF   r   r   r%   r)   r(   rv  rK   r   r   r   r   r    sP    -"
 r  c                   @   s   e Zd ZdZdZejdfdededej	de
ejedf fdd	Zd
edejdejdejfddZd
edejfddZdd ZdS )
MambaCachea  
    Cache for mamba model which does not have attention mechanism and key value states.

    Arguments:
        config (`PretrainedConfig):
            The configuration file defining the shape-related attributes required to initialize the static cache.
        max_batch_size (`int`):
            The maximum batch size with which the model will be used. Note that a new instance must be instantiated if a smaller batch size is used.
        dtype (`torch.dtype`, *optional*, defaults to `torch.float16`):
            The default `dtype` to use when initializing the layer.
        device (`torch.device` or `str`, *optional*):
            The device on which the cache should be initialized. Should be the same as the layer.

    Example:

        ```python
        >>> from transformers import AutoTokenizer, MambaForCausalLM, MambaCache

        >>> model = MambaForCausalLM.from_pretrained("state-spaces/mamba-130m-hf")
        >>> tokenizer = AutoTokenizer.from_pretrained("state-spaces/mamba-130m-hf")

        >>> inputs = tokenizer(text="My name is Mamba", return_tensors="pt")

        >>> # Prepare a cache class and pass it to model's forward
        >>> past_key_values = MambaCache(config=model.config, max_batch_size=1, device=model.device, dtype=model.dtype)
        >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
        >>> outputs.past_key_values
        MambaCache()
        ```
    TNrU   rW  r   r5   c                 C   s   || _ || _|j| _|j| _|j| _g | _g | _|d ur!t	
|nd }t|jD ]6}t	j| j | j| j|| jd}t	j| j | j| j|| jd}t	j| t	j| | j| | j| q(d S )Nr5   r   )rW  r^  intermediate_size
state_sizessm_state_sizeconv_kernelconv_kernel_sizeconv_states
ssm_statesrE   r5   r1   r_  r  r`  ra  rP   )r   rU   rW  r   r5   r   
conv_state	ssm_stater   r   r   r      s8   zMambaCache.__init__r   new_conv_staterf  r!   c                 C   s   | j | j|jkr| j | |j| j |< | j | }|d| jd }|jddd}|j|j|jd|d d d d |f< | j |   | j |  |7  < | j | S )Nr   r   r   )shiftsdimsr  )r  r5   r7   r  r  rollr   ru  )r   r   r  rf  r  r   r   r   update_conv_state%  s   
$
zMambaCache.update_conv_statenew_ssm_statec                 C   s"   | | j| j| j|< | j| S r   )r7   r  r5   )r   r   r  r   r   r   update_ssm_state6  s   
zMambaCache.update_ssm_statec                 C   r  r   )r1   r2   r  ru  r  r'   r   r   r   rv  :  r  zMambaCache.reset)r@   rA   rB   rC   rD   rE   r   r   rG   r   r	   r5   rH   r   rF   rI   r  r  rv  r   r   r   r   r    s2    
%
r  c                       s^  e Zd ZdZdZdeddfdedede	e de
eejf d	e	ej d
e
eejf de	eee
eejef f  ddf fddZ	d&dejdejdede	eeef  deejejf f
ddZd'de	e defddZde	e fddZd(ddZedefddZdeedf dejdeejejf fd d!Zdeddfd"d#Zdeddfd$d%Z  ZS ))OffloadedStaticCachea3	  
    Static cache class to be used with `torch.compile(model)` that offloads to the CPU or
    another device.

    Args:
        config (`PretrainedConfig):
            The configuration file defining the shape-related attributes required to initialize
            the static cache.
        max_batch_size (`int`):
            The maximum batch size with which the model will be used.
        max_cache_len (`int`):
            The maximum sequence length with which the model will be used.
        device (`Union[str, torch.device]`):
            The device on which the cache should be initialized. If you're using more than 1 computation device, you
            should pass the `layer_device_map` argument instead.
        dtype (`torch.dtype`, *optional*):
            The default `dtype` to use when initializing the cache.
        offload_device (`Union[str, torch.device]`, *optional*, defaults to `cpu`):
            The device to offload to. Defaults to CPU.
        layer_device_map (`Dict[int, Union[str, torch.device, int]]`, *optional*):
            Mapping between the layers and its device. This is required when you are manually initializing the cache
            and the model is splitted between differents gpus. You can know which layers mapped to which device by
            checking the associated device_map: `model.hf_device_map`.

    Example:

        ```python
        >>> from transformers import AutoTokenizer, AutoModelForCausalLM, OffloadedStaticCache

        >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
        >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")

        >>> inputs = tokenizer(text="My name is GPT2", return_tensors="pt")

        >>> # Prepare a cache class and pass it to model's forward
        >>> # Leave empty space for 10 new tokens, which can be used when calling forward iteratively 10 times to generate
        >>> max_generated_length = inputs.input_ids.shape[1] + 10
        >>> past_key_values = OffloadedStaticCache(config=model.config, max_batch_size=1, max_cache_len=max_generated_length, device=model.device, dtype=model.dtype)
        >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
        >>> past_kv_length = outputs.past_key_values # access cache filled with key/values from generation
        ```
    TNr~   rU   rW  r   r5   r   offload_devicerX  r!   c                    sx  t t|   || _|d u r|jn|| _|d u rt|nt|d | _t|| _|d ur1|ntj	| _
t|dr=|jn|j|j }t|dd d u rN|jn|j}	||	| j|f}
g | _g | _t|jD ] }|dkrl| jn| j}| |
|\}}| j| | j| qcg | _g | _tdD ]}| |
| j\}}| j| | j| qd| _| jjdkrtj | _d S d | _d S )Nr   rY  rZ  r]   r   )r   r   r   rW  r[  r   rE   r5   r  rB  r^  r=   rY  r\  r]  r   rZ  r3   r8   r1   r_  _create_key_value_cache_tensorsrP   _device_key_cache_device_value_cacher:   typer   r   _prefetch_stream)r   rU   rW  r   r5   r   r  rX  rY  rZ  rb  r   r3   r8   r   r   r   r   o  s6   
"&zOffloadedStaticCache.__init__r   r   r   r    c                 C   s  |dkr|  j |jd 7  _ | jd }| jd }n| jdur)tj| j	| j | j
|d@  }| j|d@  }| |d  |durG|dnd}|du rw|| || |dkrs| j| || j | j| || j ||fS z|d|| |d|| W n ty   ||dddd|f< ||dddd|f< Y nw |dkr|| j}|| j}|| j}z| j| d|| | j| d|| W ||fS  ty   || j| dddd|f< || j| dddd|f< Y ||fS w ||fS )a0  
        Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`.
        It is VERY important to index using a tensor, otherwise you introduce a copy to the device.

        Parameters:
            key_states (`torch.Tensor`):
                The new key states to cache.
            value_states (`torch.Tensor`):
                The new value states to cache.
            layer_idx (`int`):
                The index of the layer to cache the states for.
            cache_kwargs (`Dict[str, Any]`, *optional*):
                Additional arguments for the cache subclass. The `OffloadedStaticCache` needs the
                `cache_position` input to know how where to write in the cache.

        Return:
            A tuple containing the updated key and value states.
        r   r   Nr   rf  r]   )r:   r   r3   r8   r  rE   r   default_streamr5   wait_streamr  r  _prefetch_layerrM  rg  r7   r  rh  r$   )r   r   r   r   r    ri  rj  rf  r   r   r   r%     sL   



zOffloadedStaticCache.updater   c                 C   rK  )rk  r:   r'   r   r   r   r(        z#OffloadedStaticCache.get_seq_lengthc                 C   rK  )z9Returns the maximum sequence length of the cached states.ro  r   r   r   r   r)   	  s   z(OffloadedStaticCache.get_max_cache_shapec                 C   s:   d| _ tt| jD ]}| j|   | j|   q
dS )z5Resets the cache values while preserving the objects.r   N)r:   r1   r2   r3   ru  r8   r'   r   r   r   rv  	  s
   zOffloadedStaticCache.resetc                 C   rK  r   r  r   r   r   r   r>   	  r  z OffloadedStaticCache.seen_tokensr   .c                 C   sV   |t dk}t j|| j||d}t j|| j||d}t j| t j| ||fS )a8  Creates K/V cache tensors on a device. Pins memory for CPU tensors. Marks them as static
        addresses for non-CPU tensors.

        Args:
            shape (`Tuple[int, ...]`): Shape.
            device (`torch.device`): Device.

        Returns:
            Key and value cache tensors as a tuple.
        r~   )r   r5   
pin_memory)rE   r5   r  r^  r`  ra  )r   r   r5   is_cpu_devicer3   r8   r   r   r   r  	  s   z4OffloadedStaticCache._create_key_value_cache_tensorsc                 C   sh   |t | jkr	dS | jdur-tj| j | | W d   dS 1 s&w   Y  dS | | dS )zMPrefetch a layer to the device. Needs to be called in order of layer indices.N)r2   r3   r  rE   r   r   _prefetch_layer_in_contextr'   r   r   r   r  4	  s   
"z$OffloadedStaticCache._prefetch_layerc                 C   s@   | j |d@  j| j| dd | j|d@  j| j| dd dS )z6Performs the actual copy of the layer to device cache.r   Tr   N)r  rg  r3   r  r8   r'   r   r   r   r  B	  s   "z/OffloadedStaticCache._prefetch_layer_in_contextr   r?   r	  )r@   rA   rB   rC   rD   rE   r5   r   rG   r   r	   rH   r   r   r   rF   r   r   r%   r(   r)   rv  rJ   r>   r  r  r  rK   r   r   r   r   r  A  sb    +	?
S


r  )<ri   importlib.metadatar   rc   rw   dataclassesr   typingr   r   r   r   r   r   r	   rE   	packagingr
   transformers.pytorch_utilsr   configuration_utilsr   r   r   r   r   r   hqq.core.quantizer   r.  
get_loggerr@   r;   r   rL   ry   r   r   r   r   r   Contextr   r   register_pytree_noderA   fxregister_pytree_flatten_specr   r
  r  r-  r4  rV  rx  r  r  r  r  r  r   r   r   r   <module>   sv    $
N`b' M

 ZB> >   - K Hd