o �J�h4��@s�ddlZddlZddlZddlZddlmZddlmZm Z m Z m Z m Z m Z ddlZddlmZddlmZddlmZmZmZmZddlmZe�rQdd lmZe�e�ZGd d �d ej j!�Z"eGd d �d ��Z#eGdd�de#��Z$eGdd�de#��Z%Gdd�de"�Z&Gdd�de&�Z'Gdd�de&�Z(Gdd�de(�Z)Gdd�de(�Z*Gdd�de"�Z+Gdd�de"�Z,Gd d!�d!e,�Z-Gd"d#�d#e"�Z.Gd$d%�d%e"�Z/Gd&d'�d'�Z0Gd(d)�d)e,�Z1dS)*�N)� dataclass)�Any�Dict�List�Optional�Tuple�Union��version�)�PretrainedConfig)�is_hqq_available�is_optimum_quanto_available�is_torchdynamo_compiling�logging)�deprecate_kwarg)� Quantizerc s�eZdZdZ�fdd�Z ddejdejdedee e e fd e ejejff d d �Z ddeed efd d�Zd eefdd�Zd eefdd�Zddedeed efdd�Zdejfdd�Zedd��Z�ZS)�Cachezf Base, abstract class for all caches. The actual data structure is specific to each subclass. cst���dS�N)�super�__init__��self�� __class__��VC:\pinokio\api\whisper-webui.git\app\env\lib\site-packages\transformers\cache_utils.pyr szCache.__init__N� key_states� value_states� layer_idx� cache_kwargs�returncC�td��)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)rrrrr rrr�update#sz Cache.updatercCr")�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#�rrrrr�get_seq_length=szCache.get_seq_lengthcCst�d�|��S)Nz�`get_max_cache()` is deprecated for all Cache classes. Use `get_max_cache_shape()` instead. Calling `get_max_cache()` will raise error from v4.48)�logger� warning_once�get_max_cache_shaperrrr�get_max_lengthFs�zCache.get_max_lengthcCr")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#rrrrr+M�zCache.get_max_cache_shape�new_seq_lengthcCs2|��}|�|�}|dur|||kr||S|S)zTGiven the sequence length of the new inputs, returns the usable length of the cache.N)r+r()rr.r� max_lengthZprevious_seq_lengthrrr�get_usable_lengthQs  zCache.get_usable_length�beam_idxcCs�tt|j��D]:}|j|gkr%|j|j}|j|�d|�|��|j|<|j|gkrA|j|j}|j|�d|�|��|j|<qdS)�DReorders the cache for beam search, given the selected beam indices.rN)�range�len� key_cache�device� index_select�to� value_cache)rr1rr6rrr� reorder_cache\s  ��zCache.reorder_cachecCst�d�t|d�r |jSdS)NzuThe `seen_tokens` attribute is deprecated and will be removed in v4.41. Use the `cache_position` model input instead.� _seen_tokens)r)r*�hasattrr;rrrr� seen_tokensfs � zCache.seen_tokensr�r)�__name__� __module__� __qualname__�__doc__r�torch�Tensor�intrr�strrrr%r(r,r+r0� LongTensorr:�propertyr=� __classcell__rrrrrs, ����� �   rc@steZdZUdZded<edd��Zdeee j ffdd�Z d e ee ffd d �Zd d �Zdd�Zdd�Zdd�ZdS)� CacheConfigz& Base class for cache configs N�cache_implementationcKs^|di|��}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�valuerrr� from_dictzs    �zCacheConfig.from_dict�json_file_pathcCsZt|ddd��}|��}tj|ddd�d}|�|�Wd�dS1s&wYdS) 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. �wzutf-8)�encoding�T)�indent� sort_keys� N)�open�to_dict�json�dumps�write)rrX�writerrQZ json_stringrrr� to_json_file�s   "�zCacheConfig.to_json_filer!cCs 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__rrrrr`�s zCacheConfig.to_dictccs*�t�|j���D] \}}||fVq dS)zTallows `dict(obj)` for situations where obj may be a dict or QuantizationConfigMixinN)rfrgrhrL)r�attrrVrrr�__iter__�s� �zCacheConfig.__iter__cCs|jj�d|����S)N� )rr?�to_json_stringrrrr�__repr__�szCacheConfig.__repr__cCstj|jdd�dS)z� Serializes this instance to a JSON formatted string. Returns: str: JSON formatted string representing the configuration instance. r[)r\r^)rarbrhrrrrrl�szCacheConfig.to_json_stringc sPg�|��D]\}}t||�rt|||���|�q�fdd�|��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. csi|] \}}|�vr||�qSrr)�.0rUrV�rTrr� <dictcomp>�sz&CacheConfig.update.<locals>.<dictcomp>)rLr<rMrN)rrRrUrV� unused_kwargsrrorr%�s    �zCacheConfig.update)r?r@rArB�__annotations__� classmethodrWrrF�os�PathLikererrr`rjrmrlr%rrrrrJrs   rJc@steZdZdZddddddejdfded eed eed eed eed eedeej deefdd�Z dd�Z dS)�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 presicion. Defaults to 128. compute_dtype (`torch.dtype`, *optional*, defaults to `torch.float16`): The defualt 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_dtyper6c Cs4||_||_||_||_||_||_||_||_dSr)r|r}r~rr�r�r�r6) rr|r}r~rr�r�r�r6rrrr�s  zQuantizedCacheConfig.__init__cCs�d}|jdvrt|jdd|jd���|jdkr"t|jdd|jd���|jdkr2t|jd d|jd���|jd vrBt|jd d |jd���|jd vrRt|jd d|jd���dS)�-Validates if the arguments passed are correct�vSome of the keys in `cache_config` are defined incorrectly. `{key}` should be {correct_value}` but found {found_value}�r r[�rx�r}z 2 or 4 or 8�rUZ correct_valueZ found_valuerr�za positive integerr�)rr �����r~z`1` or `0`, `-1`rz`1` or `0` or `-1`N)r}� ValueError�formatr�r�r~r�rZincorrect_arg_msgrrr�validatesV� �� �� �� �� ���zQuantizedCacheConfig.validateN) r?r@rArBrC�float16rFrrE�dtyperr�rrrrrv�s8�������� � rvc@s0eZdZdZdZd dedefdd�Zdd �Zd S) �StaticCacheConfigz8 Configuration class for static cache settings. �staticr{� batch_size� max_cache_lencCs||_||_||_dSr)r�r�r6)rr�r�r6rrrr>s zStaticCacheConfig.__init__cCsHd}|jdkrt|jdd|jd���|jdkr"t|jdd|jd���dS)r�r�rr�z> 0r�r�N)r�r�r�r�r�rrrr�Cs&� �� ���zStaticCacheConfig.validateN)r{)r?r@rArBrKrErr�rrrrr�6s  r�c s�eZdZdZeddd�d/deeddf�fdd� �Zd edee e j fd d �Z d d �Z dd�Z d/de j de j d edeeeefde e j e j ff dd�Zd0d eedefdd�Zdeefdd�Zde e e j e e j ffdd�Zeeddd� d1dee e e jdeddfdd���Zdefd d!�Zeddd� d/d"ed#edededfd$d%��Zeeddd�d/d&eddeddfd'd(���Zd)efd*d+�Zd,e j fd-d.�Z�ZS)2� 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() ``` �num_hidden_layers�4.47.0r Nr!cs t���d|_g|_g|_dS�Nr)rrr;r5r9)rr�rrrrws  zDynamicCache.__init__rcCs8|t|�kr|j||j|fStdt|��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 )r4r5r9�KeyErrorr'rrr� __getitem__~s zDynamicCache.__getitem__ccs.�tt|��D] }|j||j|fVqdS)z� Support for backwards-compatible `past_key_value` iteration, e.g. `for x in past_key_value:` to iterate over keys and values N�r3r4r5r9r'rrrrj�s��zDynamicCache.__iter__cC� 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. )r4r5rrrr�__len__�� zDynamicCache.__len__rrr cCs�|dkr|j|jd7_|durot|j�|kr=tt|j�|�D]}|j�g�|j�g�q!|j�|�|j�|�n2t|j|�dkrQ||j|<||j|<ntj|j||gdd�|j|<tj|j||gdd�|j|<|j||j|fS)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;�shaper4r5r3rNr9rC�cat)rrrrr �_rrrr%�s    zDynamicCache.updatercCsNt|j�dkpt|j�|kpt|j|�dk}|s#|j|jd}|Sd}|S�r&rr��r4r5r�)rrZis_empty_layerZlayer_seq_lengthrrrr(�s ���zDynamicCache.get_seq_lengthcCsdS)zeReturns the maximum sequence length of the cache object. DynamicCache does not have a maximum length.Nrrrrrr+�sz DynamicCache.get_max_cache_shapecCs4d}tt|��D]}||j||j|ff7}q|S)z�Converts the `DynamicCache` instance into the its equivalent in the legacy cache format. Used for backward compatibility.rr�)r� legacy_cacherrrr�to_legacy_cache�szDynamicCache.to_legacy_cache�past_key_valuescCs>|�}|durtt|��D]}||\}}|�|||�q |S)zwConverts a cache in the legacy cache format into an equivalent `DynamicCache`. Used for backward compatibility.N)r3r4r%)rPr�r��cacherrrrrr�from_legacy_cache�s  zDynamicCache.from_legacy_cacher/cCs�|dkr |��t|�}|��|krdS||_tt|j��D]+}|j|gkrI|j|dd|�dd�f|j|<|j|dd|�dd�f|j|<qdS)z�Crop 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.rN.)r(�absr;r3r4r5r9)rr/�idxrrr�crop�s ""��zDynamicCache.crop�full_batch_size� split_sizecsbg}td|��D]&�t�}|j|_��fdd�|jD�|_��fdd�|jD�|_|�|�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`rc�g|] }|�����qSrr�rn�tensor��ir�rr� <listcomp>�z,DynamicCache.batch_split.<locals>.<listcomp>cr�rrr�r�rrr�r�)r3r�r;r5r9rN)rr�r�r��outZ current_splitrr�r� batch_split�s zDynamicCache.batch_split�splitscsv|�}tt|d��D]-��fdd�|D�}�fdd�|D�}|gkr8tj|dd�}tj|dd�}|�||��q |S)��This is the opposite of the above `batch_split()` method. This will be used by `stack_model_outputs` in `generation.utils`rc�$g|]}|j�gkr|j��qSr)r5�rn�current�r�rrr��$z2DynamicCache.from_batch_splits.<locals>.<listcomp>cr�r)r9r�r�rrr�r�r�)r3r4rCr�r%)rPr�r�r�r5r9� layer_keys� layer_valuesrr�r�from_batch_splits s�zDynamicCache.from_batch_splits�repeatscCsJtt|��D]}|j|j|dd�|j|<|j|j|dd�|j|<qdS)�TRepeat the cache `repeats` times in the batch dimension. Used in contrastive search.rr�N)r3r4r5�repeat_interleaver9)rr�rrrr�batch_repeat_interleaves�z$DynamicCache.batch_repeat_interleave�indicescCsFtt|��D]}|j||df|j|<|j||df|j|<qdS)�XOnly keep the `indices` in the batch dimension of the cache. Used in contrastive search..Nr�)rr�rrrr�batch_select_indicess�z!DynamicCache.batch_select_indicesrr>)NN)r?r@rArBrrrErrrrCrDr�rjr�rrFrr%r(r+r�rs� FloatTensorr�r�r�r�r�r�rIrrrrr�^sb   ����� �/ " ���� ���� �   r�c s�eZdZdZd�fdd� Zdefdd�Zdefd d �Zdedee e j fd d �Z d e j fdd�Z dde j de j dedeeeefde e j e j ff dd�ZdZdZ�ZS)�OffloadedCachea� A drop-in replacement for DynamicCache that conserves GPU memory at the expense of more CPU memory. Useful for generating from models with very long context. In addition to the default CUDA 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!Ncs8tj��s td��t���g|_tj��|_d|_ dS)Nz*OffloadedCache can only be used with a GPU) rC�cuda� is_available� RuntimeErrorrr�original_device�Stream�prefetch_streamr1rrrrr3s    zOffloadedCache.__init__rcCs�|t|�kr?tj�|j��(|j|}|j|j|dd�|j|<|j|j|dd�|j|<Wd�dS1s8wYdSdS)z'Starts prefetching the next layer cacheT�� non_blockingN) r4rCr��streamr�r�r5r8r9)rrr6rrr�prefetch_layer;s  "��zOffloadedCache.prefetch_layercCsXt|�dkr*|dt|�}|j|jddd�|j|<|j|jddd�|j|<dSdS)z)Moves the previous layer cache to the CPUr[r r{Tr�N)r4r5r8r9)rrZprev_layer_idxrrr�evict_previous_layerDs �z#OffloadedCache.evict_previous_layercCs�|t|�krOtj����|�|�|j|}|j��|j|}|j |}|j dur@|j � |�|_ |� d|j �}|� d|j �}|� |dt|��||fStdt|��d|����)z_Gets the cache for this layer to the device. Prefetches the next and evicts the previous layer.Nrr r�r�)r4rCr��current_stream� synchronizer�r�r�r5r9r1r8r7r�r�)rrr�� key_tensor� value_tensorrrrr�Ls       zOffloadedCache.__getitem__r1cCs|`|��|_dS)zTSaves the beam indices and reorders the cache when the tensor is back to its device.N)r1�clone�rr1rrrr:bszOffloadedCache.reorder_cacherrr cCs�|dkr|j|jd7_t|j�|krtd��t|j�|kr9|j�|�|j�|�|j�|j�|� |�n||\}}t j ||gdd�|j|<t j ||gdd�|j|<|j||j|fS)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. rr�zWOffloadedCache does not support model usage where layers are skipped. Use DynamicCache.r�) r;r�r4r5r�rNr9r�r6r�rCr�)rrrrr r�r�rrrr%is    zOffloadedCache.update�r!Nr)r?r@rArBrrEr�r�rrrCrDr�rGr:rrrFrr%r�r�rIrrrrr�&s*   ����� �* r�c s�eZdZdZdeddf�fdd� Z ddejdejd ed e e e e fde ejejff d d �Zdd e edefdd�Zdd�Zdd�Z�ZS)�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!Ncs\t���g|_g|_|j|_|j|_|j|_|j|_|j|_|j |_ |j |_ t���dSr) rr�_quantized_key_cache�_quantized_value_cacher}r�r�r~rr�r6�rr�rrrr�s zQuantizedCache.__init__rrrr c Cs�|dkr|j|jd7_t|j�|krtd��t|j�|kra|j�|j|��|j d��|j �|j|��|j d��|j�t j d|j|jd��|j�t j d|j|jd��||}}||fS|�|j|�}|�|j |�}||j||g}||j||g}t j|dd�}t j|dd�}|j|��dkr�|j|jdd|jkr�|j|��|j d�|j|<|j|��|j d�|j |<t j d|j|jd�|j|<t j d|j|jd�|j|<||fSt j|j||gdd�|j|<t j|j||gdd�|j|<||fS) Nrr�zWQuantizedCache does not support model usage where layers are skipped. Use DynamicCache.)�axis�r�r6r�rxr )r;r�r4r5r�r�rN� _quantize� contiguousr~r�rrC�zerosr�r6r9� _dequantizer�r�r�) rrrrr Zkeys_to_returnZvalues_to_returnZ dequant_keyZ dequant_valuerrrr%�s: �  ��zQuantizedCache.updatercCs*t|j�|kr dS|dkr|jS|jdS)r&rr )r4r5r;r'rrrr(�szQuantizedCache.get_seq_lengthcCr")z:Quantizes a key/value using a defined quantization method.z1Make sure to implement `_quantize` in a subclass.r#)rr�r�rrrr��r-zQuantizedCache._quantizecCr")zDDequantizes back the tensor that was quantized by `self._quantize()`z3Make sure to implement `_dequantize` in a subclass.r#)rZq_tensorrrrr��r-zQuantizedCache._dequantizerr>)r?r@rArBrvrrCrDrErrrFrrr%r(r�r�rIrrrrr��s$ ����� �+ r�c�:eZdZdZdeddf�fdd� Zdd�Zd d �Z�ZS) �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!Ncs�t��|�t�r+t�tj�d��}|t�d�kr!td|�d���ddlm }m }m }|j dvr8t d|j ����|jd vrEt d |j����|jd vrRt d |j����|j d krY|n||_|�|_dS) Nzoptimum-quantoz0.2.5zzYou need optimum-quanto package version to be greater or equal than 0.2.5 to use `QuantoQuantizedCache`. Detected version �.r)� MaxOptimizer�qint2�qint4)r[rxzA`nbits` for `quanto` backend has to be one of [`2`, `4`] but got )rr�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 rx)rrrr �parse� importlib�metadata� ImportError�optimum.quantor�r�r�r}r�r~r�qtype� optimizer)rr�Zoptimum_quanto_versionr�r�r�rrrrs$  �    � zQuantoQuantizedCache.__init__cCsHt�r"ddlm}|�||j||j�\}}|||j||||j�}|SdS)Nr)�quantize_weight)rr�r�r�r�r�)rr�r�r��scaleZ zeropoint�qtensorrrrr�'s  �zQuantoQuantizedCache._quantizecCs|��Sr)� dequantize)rr�rrrr�0sz QuantoQuantizedCache._dequantize� r?r@rArBrJrr�r�rIrrrrr��s  r�cr�) �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!Ncsdt��|�|jdvrtd|j����|jdvr td|j����|jdvr-td|j����t|_dS)Nr�zM`nbits` for `HQQ` backend has to be one of [`1`, `2`, `3`, `4`, `8`] but got )rr 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 )rrr}r�r~r� HQQQuantizer� quantizerr�rrrrPs   �   zHQQQuantizedCache.__init__cCsJ|jj|||j|j|j|jd�\}}|j|d<|jj|||jd�||fS)N)r�r6r�r}� group_sizer�)�metar6)r�quantizer6r�r}r�r�)rr�r�r�rrrrr�_s � zHQQQuantizedCache._quantizecCs|\}}|j�||�}|Sr)rr�)rr�Z quant_tensorrr�rrrr�lszHQQQuantizedCache._dequantizer�rrrrr4s  rc s�eZdZdZdZdededdf�fdd� Zed d ��Zd e j d e j d e j de j fdd�Z d e j d e j d e j de e j e j ffdd�Z ddeedefdd�Zdeefdd�Z dd e j de j dedeeeefde e j e j ff dd�Z�ZS)� 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!Ncs>t���g|_g|_||_||_i|_d|_d|_d|_ dSr�) rrr5r9rr�cos_sin_rerotation_cache� _cos_cache� _sin_cacher;)rrrrrrr�s  zSinkCache.__init__cCsH|dd|jdd�f}|d|jddd�f}tj| |fdd�S)N.r�r[r�)r�rCr�)�x�x1�x2rrr� _rotate_half�szSinkCache._rotate_halfr�cos�sincCs|||�|�|}|Sr)r)rrrrZrotated_key_statesrrr�_apply_key_rotary_pos_emb�sz#SinkCache._apply_key_rotary_pos_embc Cs�|jd|jvrk|�tj�}|�tj�}||j|jdd�}||j|jd �}||j|jdd�}||j|jd �}||||}| |||} |�|j��d�| �|j��d�f|j|jd<|j|jdS)Nr�r)r�r r8rC�float32rr�� unsqueeze) rrrrZ original_cosZ shifted_cosZ original_sinZ shifted_sin�rerotation_cos�rerotation_sinrrr�_get_rerotation_cos_sin�s  �z!SinkCache._get_rerotation_cos_sinrrcCs"t|j�|kr dS|j|jdSr�r�r'rrrr(�szSinkCache.get_seq_lengthcC�|jS)zfReturns the maximum sequence length of the cache object, in case of SinkCache it is the window length.)rrrrrr+�szSinkCache.get_max_cache_shaperr cCs�|�d�}|�d�}|�d�}|duo|du}|dkr%|j|jd7_|rk|dkrk|��dkr8||_||_n3|jdurH|d|_|d|_n#|jjd|jkrktj|j|dgdd �|_tj|j|dgdd �|_t |j �|kr|j � |�|j � |�n�|jd|� |�|jkr�tj|j ||gdd �|j |<tj|j ||gdd �|j |<n�|j |dd�dd�|j |j|jdd�f} |�r|�||jd|j�|jd|j��\} } |dur�| d d|�f| d |d�f} } |�| | | �} |du�rtj| | fd d �} |j |dd�dd�d|j�f} tj| | |gdd �|j |<|j |dd�dd�d|j�f}|j |dd�dd�|j |j|jdd�f}tj|||gdd �|j |<|j ||j |fS) 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. rr�partial_rotation_sizeNrr�r[)r.r�.r�)�getr;r�r�r r rrCr�r4r5rNr9r(rrr)rrrrr rrrZ using_ropeZ keys_to_keeprrZ keys_passZ sink_keysZ sink_valuesZvalues_to_keeprrrr%�sX          (��� ""(�zSinkCache.updater>r)r?r@rArB� is_slidingrEr� staticmethodrrCrDrrrrr(r+rrFrr%rIrrrrrrsL  ��� ���� � ������rcs�eZdZdZdddejddfdedededejdej de ed e e ee e ejeffd df�fd d � Z dd ejdejdede e e efd eejejff dd�Zdde ed efdd�Zd e efdd�Zdd�Zedd��Z�ZS)� 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. batch_size (`int`): The 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`): The maximum sequence length with which the model will be used. device (`torch.device` or `str`): The device on which the cache should be initialized. Should be the same as the layer. dtype (`torch.dtype`, *optional*, defaults to `torch.float32`): The default `dtype` to use when initializing the layer. 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, 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, 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() ``` NrSr�r�r6r��max_batch_size�layer_device_mapr!c s�t���|durt�d|jj�d��|p||_|dur |jn||_t |d�r+|j n|j |j |_ ||_ t|dd�dur@|j n|j|_g|_g|_|j|j|j|j f}t|j�D]h} |durd|| } n|} tj||j | d�} tj||j | d�} t�s�|�d| ��tj||| d��|�d| ��tj||| d��t|d| ���} t|d| ���} tj�| �tj�| �|j�| �|j�| �qYdS)N�The 'batch_size' argument of �l is deprecated and will be removed in v4.49. Use the more precisely named 'max_batch_size' argument instead.�head_dim�num_key_value_headsr�Z key_cache_Z value_cache_)rrr)r*rr?r�max_position_embeddingsr�r<r"� hidden_size�num_attention_headsr��getattrr#r5r9r�r3r�rCr�r�register_buffer�_dynamo�mark_static_addressrN) rrSr�r�r6r�rr� cache_shaper�� layer_device�new_layer_key_cache�new_layer_value_cacherrrrVsB � ���    �zStaticCache.__init__rrrr cCs�|�d�}|j|}|j|}|�|j�}|�|j�}|dur-|�|�|�|�||fSz|�d||�|�d||�W||fStyb||dd�dd�|f<||dd�dd�|f<Y||fSw)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. �cache_positionNr[)rr5r9r8r��copy_� index_copy_r$)rrrrr r/�k_out�v_outrrrr%�s$        � ��zStaticCache.updatercCs|j|djdd���S)�MReturns the sequence length of the cached states that were seen by the model.�rrr�r�)r5�any�sumr'rrrr(�szStaticCache.get_seq_lengthcCrr�r�rrrrr+��zStaticCache.get_max_cache_shapecC�4tt|j��D]}|j|��|j|��qdS�z4Resets the cache values while preserving the objectsN�r3r4r5�zero_r9r'rrr�reset���zStaticCache.resetcC�t�d|jj�d��|jS�NzThe 'batch_size' attribute of zr is deprecated and will be removed in v4.49. Use the more precisely named 'self.max_batch_size' attribute instead.�r)r*rr?rrrrrr����zStaticCache.batch_sizerr>)r?r@rArBrCrr rEr6r�rrrrFrrDrrr%r(r+r>rHr�rIrrrrr-sT+�������� �?����� �2rcs�eZdZdZdZdddejddfdedededej dej d e ed e e ee eej effd df�fd d � Z ddejdejdede e eefd eejf dd�Zd e efdd�Zdd�Z�ZS)�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. batch_size (`int`): The 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`): The maximum sequence length with which the model will be used. device (`torch.device` or `str`): The device on which the cache should be initialized. Should be the same as the layer. dtype (`torch.dtype`, *optional*, defaults to `torch.float32`): The default `dtype` to use when initializing the layer. 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, 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, 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() ``` TNrSr�r�r6r�rrr!c sFt|d�r |jdurtd��t|j|�}t�j|||||||d�dS)N�sliding_window��Setting `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.)rSr�r�r6r�rr)r<rEr��minrr)rrSr�r�r6r�rrrrrrs �  �zSlidingWindowCache.__init__rrrr c Cs�|�d�}|j|}|j|}|jd|jkrQ|dd�dd�|j d�dd�f}|dd�dd�|j d�dd�f}|j||7<|j||7<||fStj|jtj|jd�� d�}|� d|jd�}||jdk} || d� �d|j} |dd�dd�| f}|dd�dd�| f}z|� d||�|� d||�Wnt y�||dd�dd�|f<||dd�dd�|f<Ynw|j|��|j|��|j||7<|j||7<||fS)Nr/rr�r r�r[)rr5r9r�r�rC�ones�longr6�cumsum�clamprEr1r$r=) rrrrr r/r2r3�slicing�to_shiftr�rrrr%/s6   $$ �zSlidingWindowCache.updatecCrrr8rrrrr+^r9z&SlidingWindowCache.get_max_cache_shapecCs4tt|j��D]}|j|��|j|��qdSrr<r'rrrr>as�zSlidingWindowCache.resetr)r?r@rArBrrCrr rEr6r�rrrrFrrDrrr%r+r>rIrrrrrD�sP4�������� � ����� �/rDc sZeZdZdZdedef�fdd� Zdedeee j fdd �Z d d �Z deee j ee j ffd d �Z e d1deeee jddfdd��Zd2deedefdd�Zdd�Zde jfdd�Zdefdd�Zdefdd�Zed d!d"� d1d#ed$ed edd%fd&d'��Zeed d!d"� d1d(edd eddfd)d*���Zd+efd,d-�Zd.e j fd/d0�Z�ZS)3�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_cachecsLt���||_||_i|_tt|j��D]}t|� |�dk�|j|<qdSr�) rrrOrP� is_updatedr3r4r5�boolr()rrOrPrrrrr�s �zEncoderDecoderCache.__init__rr!cCsP|t|�kr|jj||jj||jj||jj|fStdt|��d|����r�)r4rOr5r9rPr�r'rrrr��s     �zEncoderDecoderCache.__getitem__cCr�r�)r4rOrrrrr��r�zEncoderDecoderCache.__len__cCsRd}t|j�dkr"t|j��|j���D] \}}|||f7}q|S|j��}|S)z\Converts the `EncoderDecoderCache` instance into its equivalent in the legacy cache format.rr)r4rP�ziprOr�)rr�� self_attn� cross_attnrrrr��s � �z#EncoderDecoderCache.to_legacy_cacheNr�cCs�|t�t�d�}|durFtt|��D]3}||dd�\}}|j�|||�t||�dkrE||dd�\}}|j�|||�d|j|<q|S)zUConverts a cache in the legacy cache format into an equivalent `EncoderDecoderCache`.)rOrPNr[T)r�r3r4rOr%rPrQ)rPr�r�rrrrrrr��s� �z%EncoderDecoderCache.from_legacy_cachercCs |j�|�S)r&)rOr(r'rrrr(�s z"EncoderDecoderCache.get_seq_lengthcCs�t|jd�r |j��t|jd�r|j��nt|jd�s4t|jd�s4td|j���d|j���d���|jD]}d|j|<q7dS)Nr>z�Neither 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<rOr>rPr��__str__rQr'rrrr>�s    ���  �zEncoderDecoderCache.resetr1cCs|j�|�|j�|�dS)r2N)rOr:rPr�rrrr:�s z!EncoderDecoderCache.reorder_cache�methodcCsDt|jt�r t|jt�s td|�d|j���d|j���d���dS)N�`z)` is only defined for dynamic cache, got rVrW)� isinstancerOr�rPr�rX)rrYrrr�check_dynamic_cache�s � ����z'EncoderDecoderCache.check_dynamic_cache�maximum_lengthcCs|�|jj�|j�|�dS)z�Crop 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?rO)rr]rrrr��szEncoderDecoderCache.cropr�r�r r�r�zList[EncoderDecoderCache]c CsV|�|jj�|j�||�}|j�||�}g}t||�D] \}}|�t||��q|S)r�)r\r�r?rOrPrSrNrN) rr�r�r�rOrPr�rTrUrrrr��szEncoderDecoderCache.batch_splitr�cs�t�}t�}tt|d��D]H�tj�fdd�|D�dd�}tj�fdd�|D�dd�}|�||��tj�fdd�|D�dd�}tj�fdd�|D�dd�}|�||��q|||�S)r�rc�g|]}|jj��qSr)rOr5r�r�rrr��z9EncoderDecoderCache.from_batch_splits.<locals>.<listcomp>r�cr^r)rOr9r�r�rrr�r_cr^r)rPr5r�r�rrr�r_cr^r)rPr9r�r�rrr�r_)r�r3r4rCr�r%)rPr�r�rOrPr�r�rr�rr��s z%EncoderDecoderCache.from_batch_splitsr�cC�*|�|jj�|j�|�|j�|�dS)r�N)r\r�r?rOrP)rr�rrrr� � z+EncoderDecoderCache.batch_repeat_interleaver�cCr`)r�N)r\r�r?rOrP)rr�rrrr�raz(EncoderDecoderCache.batch_select_indicesrr>)r?r@rArBrrrErrrCrDr�r�r�rsrr�r�r(r>rGr:rFr\r�rr�r�r�r�rIrrrrrNhsR " �� � ���� � ����rNcs�eZdZdZdddejddfdedededeej e fdej d e ed e e eee ej effd df�fd d � Zdd�Zdd�Z d!dejdejdede e e efd eejf dd�Zd e efdd�Zd"de efdd�Zdd�Zedd ��Z�ZS)#� 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. batch_size (`int`): The 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`): The maximum sequence length with which the model will be used. device (`torch.device` or `str`, *optional*, defaults to `"cpu"`): The device on which the cache should be initialized. Should be the same as the layer. dtype (torch.dtype, *optional*, defaults to `torch.float32`): The default `dtype` to use when initializing the layer. 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, 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, 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() ``` Nr{rSr�r�r6r�rrr!cs|t���|durt�d|jj�d��t|d�r|jdur"td��||_ |p(||_ t|d�r2|j n|j |j |_ ||_|jdurD|j n|j|_tjdd�t|j�D�tj|d�|_g|_g|_|j|j||j f}|j|jt|j|�|j f} t|j�D]@} |dur�|| } n|} |j| s�|n| } tj| |j| d�} tj| |j| d�}tj�| �tj�|�|j�| �|j�|�q{dS) Nr r!rErFr"cSsg|] }t|d� �qS)r[)rR)rnr�rrrr�fsz(HybridCache.__init__.<locals>.<listcomp>r�)rrr)r*rr?r<rEr�r�rr"r%r&r�r#rCr�r3r�rRrr5r9r�rGr�r)r*rN)rrSr�r�r6r�rrZglobal_cache_shapeZsliding_cache_shaper�r,r+r-r.rrrrDsN �� ��� �    �zHybridCache.__init__c Csl|jd|kr?|dd�dd�| d�dd�f}|dd�dd�| d�dd�f}|j||7<|j||7<||fStj|tj|jd��d�}|�d|d�}||dk} || d� �d|} |dd�dd�| f}|dd�dd�| f}||dd�dd�|f<||dd�dd�|f<|j|� �|j|� �|j||7<|j||7<||fS)Nrr�r r�) r�r5r9rCrHrIr6rJrKrEr=) rr/rrrr2r3r�rLrMr�rrr�_sliding_update�s&"" zHybridCache._sliding_updatecCsH||dd�dd�|f<||dd�dd�|f<||j|<||j|<||fSr)r5r9)rr/rrrr2r3r�rrr�_static_update�s   zHybridCache._static_updaterrrr c CsT|�d�}|�d�}|j|}|j|}|r|j} n|j} | |||||||jd�S)Nr/rEr[)rr5r9rcrdr�) rrrrr r/rEr2r3� update_fnrrrr%�s    �zHybridCache.updatecCrrr8rrrrr+�r9zHybridCache.get_max_cache_shapercCs*|dkrtd��|j|djdd���S)Nrz�`get_seq_length` on `HybridCache` may get inconsistent results depending on the layer index. Using the `layer_idx` argument is not supported.r5r�r�)r�r5r6r7r'rrrr(�s �zHybridCache.get_seq_lengthcCr:r;r<r'rrrr>�r?zHybridCache.resetcCr@rArBrrrrr��rCzHybridCache.batch_sizerr>)r?r@rArBrCrr rErr6rFr�rrrrcrdrDrrr%r+r(r>rHr�rIrrrrrbsX-���� ���� �< ����� � rbc @s�eZdZdZdejddfdededejde e ej e fde ef dd �Z d ed ejd ejd ejfdd�Zd edejfdd�Zdd�Zedd��ZdS)� MambaCacheaV 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. batch_size (`int`): The 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. Attributes: dtype: (`torch.dtype`): The default `dtype` used to initializing the cache. intermediate_size: (`int`): Model's intermediate_size taken from config. ssm_state_size: (`int`): Model's state_size taken from config. conv_kernel_size: (`int`): Model's convolution kernel size taken from config conv_states: (`torch.Tensor`): A tensor of shape `[layer_idx, batch_size, intermediate_size, conv_kernel_size]` that holds convolutional states. ssm_states: (`torch.Tensor`): A tensor of shape `[layer_idx, batch_size, intermediate_size, ssm_state_size]` that holds ssm states 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, 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() ``` NrSr�r�r6rcCs�|durt�d|jj�d��||_|p||_|j|_|j|_|j |_ t j |j |j|j|j ||d�|_t j |j |j|j|j||d�|_t j�|j�t j�|j�dS)Nr r!�r6r�)r)r*rr?r�r�intermediate_size� state_sizeZssm_state_size� conv_kernel�conv_kernel_sizerCr�r�� conv_states� ssm_statesr)r*)rrSr�r�r6rrrrr s6� �� zMambaCache.__init__r�new_conv_stater/r!cCsx|j|}|�d|jd�}|jddd�}|j|j|jd�|dd�dd�|f<|j|��|j||7<|j|S)Nrr r�)�shifts�dimsrg)rlrKrk�rollr8r6r�r=)rrrnr/Z conv_staterrr�update_conv_state3s $ zMambaCache.update_conv_state� new_ssm_statecCs|�|jj�|j|<|j|Sr)r8rmr6)rrrsrrr�update_ssm_state?s zMambaCache.update_ssm_statecCs|j��|j��dSr)rlr=rmrrrrr>Cs zMambaCache.resetcCr@rArBrrrrr�GrCzMambaCache.batch_size)r?r@rArBrCr�r rEr�rrr6rFrrDrGrrrtr>rHr�rrrrrf�s<2����� �'��� � rfc@sReZdZdZde�d�dfdededeede e ejfdeej d e e ejfd ee ee e ejeffd dfd d �Z d%dejdejdedee e efd eejejff dd�Zd&deed efdd�Zd eefdd�Zd'dd�Zed efdd��Zdeedfdejd eejejffdd �Zded dfd!d"�Zded dfd#d$�ZdS)(�OffloadedStaticCachea 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. Should be the same as the layer device. 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`. Attributes: key_cache (`List[torch.Tensor]`): Off-loaded key cache tensors. First one will be on device, where-as the others are off-loaded. value_cache (`List[torch.Tensor]`): Off-loaded value cache tensors. First one will be on device, where-as the others are off-loaded. max_batch_size (`int`): The maximum batch size with which this cache can be used. max_cache_len (`int`): The maximum sequence length with which this cache can be used. device (`torch.device`): The device on which the cache is used. offload_device (`torch.device`): The device used to offload to. dtype (`torch.dtype`): The `dtype` used to initializing the cache. 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 ``` Nr{rSrr�r6r��offload_devicerr!cCsd||_|dur |jn||_|durt�|�n|d|_t�|�|_|dur'|ntj|_t|d�r3|j n|j |j }t |dd�durD|j n|j } || |j|f} g|_g|_t|j�D] } | dkrb|jn|j}|�| |�\} } |j�| �|j�| �qYg|_g|_td�D]} |�| |j�\} } |j�| �|j�| �q�d|_|jjdkr�tj��|_dSd|_dS)Nrr"r#r[r�)rr$r�rCr6rvrr�r<r"r%r&r'r#r5r9r3r��_create_key_value_cache_tensorsrN�_device_key_cache�_device_value_cacher;�typer�r��_prefetch_stream)rrSrr�r6r�rvrr"r#r+r�r5r9rrrr�s4  ��   &zOffloadedStaticCache.__init__rrrr cCs|dkr|j|jd7_|jd}|jd}n|jdur)tj�|j�� |j�|j |d@}|j |d@}|� |d�|durG|� d�nd}|durw|�|�|�|�|dkrs|j|�|�|j��|j|�|�|j��||fSz|�d||�|�d||�Wnty�||dd�dd�|f<||dd�dd�|f<Ynw|dkr�|�|j�}|�|j�}|�|j�}z|j|�d||�|j|�d||�W||fSty�||j|dd�dd�|f<||j|dd�dd�|f<Y||fSw||fS)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. rr�Nr r/r[)r;r�r5r9r{rCr��default_streamr6� wait_streamrxry�_prefetch_layerrr0r8rvr1r$)rrrrr r2r3r/rrrr%�sL     � �    ��zOffloadedStaticCache.updatercCr)r4�r;r'rrrr(�z#OffloadedStaticCache.get_seq_lengthcCr)z9Returns the maximum sequence length of the cached states.r8rrrrr+sz(OffloadedStaticCache.get_max_cache_shapecCs:d|_tt|j��D]}|j|��|j|��q dS)z5Resets the cache values while preserving the objects.rN)r;r3r4r5r=r9r'rrrr>$s �zOffloadedStaticCache.resetcCrrrrrrrr=1r�z OffloadedStaticCache.seen_tokensr�.cCsV|t�d�k}tj||j||d�}tj||j||d�}tj�|�tj�|�||fS)a8Creates 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�r6� pin_memory)rCr6r�r�r)r*)rr�r6� is_cpu_devicer5r9rrrrw7s   z4OffloadedStaticCache._create_key_value_cache_tensorscCsh|t|j�kr dS|jdur-tj�|j��|�|�Wd�dS1s&wYdS|�|�dS)zMPrefetch a layer to the device. Needs to be called in order of layer indices.N)r4r5r{rCr�r��_prefetch_layer_in_contextr'rrrr~Qs  "�z$OffloadedStaticCache._prefetch_layercCs@|j|d@j|j|dd�|j|d@j|j|dd�dS)z6Performs the actual copy of the layer to device cache.r Tr�N)rxr0r5ryr9r'rrrr�_s"z/OffloadedStaticCache._prefetch_layer_in_contextrr>r�)r?r@rArBrCr6r rErrrFr�rrrDrrr%r(r+r>rHr=rwr~r�rrrrruPs`B���� �� �� �>����� �S   �� �ru)2rf�importlib.metadatar�rart� dataclassesr�typingrrrrrrrC� packagingr �configuration_utilsr �utilsr rrrZutils.deprecationrZhqq.core.quantizerr� get_loggerr?r)�nn�ModulerrJrvr�r�r�r�r�rrrrDrNrbrfrurrrr�<module>sN       W`b'IrZB><0 2Dt
Memory