CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
cache_utils.cpython-310.pyc470 linesDownload Raw Back to __pycache__
1o

2.�Yi��@sddlmZmZddlmZddlmZmZddlZddl	m3Z4ddlmZm
Z
mZmZmZe�r7ddlmZed	d5d�Ze�e�ZGdd
�d
e�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�d�Z Gdd�de �Z!Gd d!�d!e �Z"Gd"d#�d#e �Z#Gd$d%�d%e �Z$Gd&d'�d'e�Z%Gd(d)�d)e�Z&Gd*d+�d+e!�Z'Gd,d-�d-e"�Z(Gd.d/�d/e"�Z)Gd0d1�d1e"�Z*Gd2d3�d3e"�Z+Gd4d5�d5e"�Z,Gd6d7�d7e#�Z-Gd8d9�d9e#�Z.Gd:d;�d;e �Z/dS)<�)�ABC�abstractmethod)�Iterable)�Any�OptionalN�)�PretrainedConfig)�is_hqq_available�is_quanto_greater�is_torch_greater_or_equal�is_torchdynamo_compiling�logging)�	Quantizerz2.7T�Z6accept_devc@s�eZdZdZdZdd�Zdd�Zedej	fdd	��Z7e	8d dej	dej	deee
efd
eej	ej	ffdd��Zedej	d
eeeffdd��Zed
efdd��Zed
efdd��Zdd�Zdd�Zd!dd�Zdejd
d9fdd�Zd10S)"�CacheLayerMixinz0Base, abstract class for a single layer's cache.FcCsd|_d|_d|_dS�NF)�keys�values�is_initialized��self�r��E:\DocsHouse\542 percep lab latest\PerceptionLab\PerceptionLab_Portable\python_embed\Lib\site-packages\transformers/cache_utils.py�__init__s11zCacheLayerMixin.__init__cCs12|jj�S�N)�	__class__�__name__rrrr�__repr__$s13zCacheLayerMixin.__repr__�14key_statescC�dSrr�rrrrr�lazy_initialization'�z#CacheLayerMixin.lazy_initializationN�value_states�cache_kwargs�returncCrrr�rrr#r$rrr�update*szCacheLayerMixin.update�cache_positioncCrrr)rr(rrr�get_mask_sizes/r"zCacheLayerMixin.get_mask_sizescCrrrrrrr�get_seq_length2r"zCacheLayerMixin.get_seq_lengthcCrrrrrrr�get_max_cache_shape5r"z#CacheLayerMixin.get_max_cache_shapecCs2|jr|jjddd�|_|jjddd�|_dSdS)z(Offload this layer's data to CPU device.�cpuT�Znon_blockingN)rr�torrrrr�offload8s�zCacheLayerMixin.offloadcCsH|jr |jj|jkr"|jj|jdd�|_|jj|jdd�|_dSdSdS)zcIn case of layer offloading, this allows to move the data back to the layer's device ahead of time.Tr-N)rr�devicer.rrrrr�prefetch>s�zCacheLayerMixin.prefetchcCs2|jr
|j��|j��t|d�rd|_dSdS)z4Resets the cache values while preserving the objects�cumulative_lengthrN)rrZzero_r�hasattrr2rrrr�resetDs15161718�zCacheLayerMixin.reset�beam_idxcCsH|��dkr"|j�d|�|jj��|_|j�d|�|jj��|_dSdS)z,Reorders this layer's cache for beam search.rN)r*rZindex_selectr.r0r�rr5rrr�
reorder_cacheMs�zCacheLayerMixin.reorder_cacher�r%N)r�19__module__�__qualname__�__doc__�is_compileablerrr�torch�Tensorr!r�dict�strr�tupler'�intr)r*r+r/r1r4�20LongTensorr7rrrrrs8�����21	rc@s�eZdZdZdZdejfdd�Z	ddejdejdee	e22efd	eejejffd23d�Z
dejd	eeeffd
d�Zd	efdd�Zd	efdd�Zded	dfdd�Zded	dfdd�Zdejd	dfdd�ZdS)�DynamicLayerz�24    A cache layer that grows dynamically as more tokens are generated. This is the default for generative models.25    It stores the key and value states as tensors of shape `[batch_size, num_heads, seq_len, head_dim]`.26    FrcCsH|j|j|_|_tjg|j|jd�|_tjg|j|jd�|_d|_dS)N��dtyper0T)rFr0r=�tensorrrrr rrrr!\s27z DynamicLayer.lazy_initializationNr#r$r%cCsH|js|�|�tj|j|gdd�|_tj|j|gdd�|_|j|jfS)��28        Update the key and value caches in-place, and return the necessary keys and value states.29 30        Args:31            key_states (`torch.Tensor`): The new key states to cache.32            value_states (`torch.Tensor`): The new value states to cache.33            cache_kwargs (`dict[str, Any]`, *optional*): Additional arguments for the cache.34 35        Returns:36            tuple[`torch.Tensor`, `torch.Tensor`]: The key and value states.37        �������dim)rr!r=�catrrr&rrrr'bs3839zDynamicLayer.updater(cCs"d}|jd}|��|}||fS)zDReturn the length and offset of the cache, used to generate the maskr)�shaper*)rr(�	kv_offset�query_length�	kv_lengthrrrr){s40zDynamicLayer.get_mask_sizescCs$|jr41|j��dkrdS|jjdS)�1Returns the sequence length of the cached states.rrI)rrZnumelrMrrrrr*�szDynamicLayer.get_seq_lengthcCsdS)zeReturns the maximum sequence length of the cache object. DynamicLayer does not have a maximum length.�����rrrrrr+�sz DynamicLayer.get_max_cache_shape�42max_lengthcCs`|dkr|��t|�}|��|krdS|jdd|�dd�f|_|jdd|�dd�f|_dS)z�43        Crop the past key values up to a new `max_length` in terms of tokens. `max_length` can also be negative44        to remove `max_length` tokens.45        rN.)r*�absrr�rrSrrr�crop�szDynamicLayer.crop�repeatscCs8|��dkr|jj|dd�|_|jj|dd�|_dSdS)z8Repeat the cache `repeats` times in the batch dimension.rrJN)r*rZrepeat_interleaver�rrWrrr�batch_repeat_interleave�s�z$DynamicLayer.batch_repeat_interleave�indicescCs4|��dkr|j|df|_|j|df|_dSdS)z<Only keep the `indices` in the batch dimension of the cache.r.N)r*rr�rrZrrr�batch_select_indices�s�z!DynamicLayer.batch_select_indicesr)rr9r:r;�46is_slidingr=r>r!rr?r@rrAr'rBr)r*r+rVrYr\rrrrrDTs(47����48�rDcs�eZdZdZdZdef�fdd�Z	ddejdejd	e	e49eefd50e
ejejffdd�Zd
ejd51e
eeffdd�Zd52efdd�Zd53efdd�Zded54df�fdd�Z�ZS)�DynamicSlidingWindowLayerz�55    A cache layer that grows dynamically as more tokens are generated, up until the sliding window size.56    It stores the key and value states as tensors of shape `[batch_size, num_heads, min(seq_len, sliding_window), head_dim]`.57    T�sliding_windowcst���||_d|_dS�Nr)�superrr_r2)rr_�rrrr�s5859z"DynamicSlidingWindowLayer.__init__Nrr#r$r%cCs�|js|�|�|j|jd7_tj|j|gdd�}tj|j|gdd�}|dd�dd�|jdd�dd�f|_|dd�dd�|jdd�dd�f|_||fS)rHrIrJNr)	rr!r2rMr=rLrrr_)rrr#r$�full_key_states�full_value_statesrrrr'�s60**z DynamicSlidingWindowLayer.updater(cCsX|jd}|j|jk}t|j|jdd�}|r#|jd|}||fS|j|}||fS��NReturn the length and offset of the cache, used to generate the attention maskrr)rMr2r_�max)rr(rO�is_fullrNrPrrrr)�s6162�z(DynamicSlidingWindowLayer.get_mask_sizescC�|jS�rQ�r2rrrrr*��z(DynamicSlidingWindowLayer.get_seq_lengthcCri�z+Return the maximum cache shape of the cache�r_rrrrr+�rlz-DynamicSlidingWindowLayer.get_max_cache_shaperScs4|��|jkrtd��t��|�|jjd|_dS)z�63        Crop the past key values up to a new `max_length` in terms of tokens. `max_length` can also be64        negative to remove `max_length` tokens.65        z�Cannot `crop` a `DynamicSlidingWindowLayer` after it has seen more tokens than itssliding window (otherwise some states are lost)rIN)r*r_�66ValueErrorrarVrrMr2rUrbrrrV�s�zDynamicSlidingWindowLayer.cropr)rr9r:r;r]rBrr=r>rr?r@rrAr'r)r*r+rV�
__classcell__rrrbrr^�s$	����67�!
r^cs�eZdZdZdZdZdef�fdd�Zdej	fdd	�Z68	69ddej	dej	deee
efd
eej	ej	ffdd�Zdej	d
eeeffdd�Zd
efdd�Zd
efdd�Z�ZS)�StaticLayera�70    A static cache layer that stores the key and value states as static tensors of shape `[batch_size, num_heads, max_cache_len), head_dim]`.71    It lazily allocates its full backing tensors, and then mutates them in-place. Built for `torch.compile` support.72 73    Args:74        max_cache_len (`int`):75            Maximum number of tokens that can be stored, used for tensor preallocation.76    TF�
max_cache_lencst���||_dSr)rarrr)rrrrbrrrs7778zStaticLayer.__init__rcCs�|j\|_|_}|_|j|j|_|_tj|j|j|j|jf|j|jd�|_	tj|j|j|j|jf|j|jd�|_79t�sJtj�
|j	�tj�
|j80�d|_dS)a681        Lazy initialization of the keys and values tensors. This allows to get all properties (dtype, device,82        num_heads in case of TP etc...) at runtime directly, which is extremely practical as it avoids moving83        devices, dtypes etc later on for each `update` (which could break the static dynamo addresses as well).84 85        If this is unwanted, one can call `early_initialization(...)` on the Cache directly, which will call this86        function ahead-of-time (this is required for `torch.export` for example). Note that for `compile`, as we87        internally don't compile the prefill, this is guaranteed to have been called already when compiling.88        If compiling the prefill as well, e.g. calling `model.compile(...)` before `generate` with a static cache,89        it is still supported in general, but without guarantees depending on the compilation options (e.g. cuda graphs,90        i.e. `mode="reduce-overhead"` is known to fail). But it will in general work correctly, and prefill should91        not be compiled anyway for performances!92        rETN)rM�max_batch_size�	num_heads�head_dimrFr0r=�zerosrrrrrZ_dynamoZmark_static_addressr)rr�_rrrr!	s ��	93zStaticLayer.lazy_initializationNr#r$r%cCs�|js|�|�|dur|�d�nd}|dur|n94tj|jd|jd�}z|j�d||�|j	�d||�Wn!t95yW||jdd�dd�|f<||j	dd�dd�|f<Ynw|j|j	fS)rHNr(rI�r0�)rr!�getr=�arangerMr0r�index_copy_r�NotImplementedError)rrr#r$r(rrrr'.s96 ��zStaticLayer.updater(cCsd}|j}||fS)rfr�rr)rr(rNrPrrrr)TszStaticLayer.get_mask_sizescCs |jr|jdjdd���SdS)rQ)rrrRrJr)rr�any�sumrrrrr*Zs zStaticLayer.get_seq_lengthcCrirmr~rrrrr+`rlzStaticLayer.get_max_cache_shaper)rr9r:r;r<r]rBrr=r>r!rr?r@rrAr'r)r*r+rprrrbrrq�s&	)����97�&rqcs�eZdZdZdZdedef�fdd�Z	ddejd	ejd98e	e99eefde
ejejffdd
�Zdejde
eeffdd�Zdefdd�Z�ZS)�StaticSlidingWindowLayera�100    A static cache layer that stores the key and value states as static tensors of shape101    `[batch_size, num_heads, min(max_cache_len, sliding_window), head_dim]`. It lazily allocates its full backing102    tensors, and then mutates them in-place. Built for `torch.compile` support.103 104    Args:105        max_cache_len (`int`):106            Maximum number of tokens that can be stored, used for tensor preallocation.107        sliding_window (`int`):108            The size of the sliding window.109    Trrr_cs"t||�}t�j|d�d|_dS)Nr~r)�minrarr2)rrrr_Zeffective_max_cache_lenrbrrrts110111z!StaticSlidingWindowLayer.__init__Nrr#r$r%cCs�|js|�|�|dur|�d�nd}|dur|n112tj|jd|jd�}|j}||jk}|j|jd7_|r�|jddkr�|j	j113ddd�}|jj114ddd�}tjdgt
|jd�}	||dd�dd�|	f<||dd�dd�|	f<|j	�|�|j�|�|j	|jfStj|j	dd�dd�dd�dd�f|fdd	�}115tj|jdd�dd�dd�dd�f|fdd	�}n||jd116|jkr�|dkr�|}117|}nltj|j	dd�dd�d|�dd�f|fdd	�}118tj|jdd�dd�d|�dd�f|fdd	�}n;z|j	�d119||�|j�d120||�Wn"t�y*||j	dd�dd�|f<||jdd�dd�|f<Ynw|j	|jfS|j	�|121dd�dd�|jd�dd�f�|j�|dd�dd�|jd�dd�f�|122|fS)rHNr(rIrxrrR)�dimsrErJryr)rr!rzr=r{rMr0r2rrrZrollrrGrBZcopy_rLr|r})rrr#r$r(r2rhZnew_keys�123new_values�indexrcrdrrrr'ysJ124 �1250202�,,zStaticSlidingWindowLayer.updater(cCst|jd}|j}|j|jk}t|j|dd�}|r$||d}||fS|j||kr4|j|}||fS|}||fSre)rMrrr2rg)rr(rOr_rhrNrPrrrr)�s126�127�z'StaticSlidingWindowLayer.get_mask_sizescCrirjrkrrrrr*�rlz'StaticSlidingWindowLayer.get_seq_lengthr)rr9r:r;r]rBrr=r>rr?r@rrAr'r)r*rprrrbrr�es 	����128�Qr�cs�eZdZdZ					ddededed	ed129ef130�fdd�
Z	
ddejdejdee	e131efdeejejffdd�Z
edd��Zedd��Zdefdd�Z�ZS)�QuantizedLayera132    A quantized layer similar to what is described in the [KIVI: A Tuning-Free Asymmetric 2bit Quantization for KV Cache paper](https://huggingface.co/papers/2402.02750).133    It allows the model to generate longer sequence length without allocating too much memory for the key and value caches by134    applying quantization.135 136    The cache has two types of storage, one for original precision and one for the quantized cache. A `residual length`137    is set as a maximum capacity for the original precision cache. When the length goes beyond maximum capacity, the original138    precision cache is discarded and moved into the quantized cache. The quantization is done per-channel with a set `q_group_size`139    for both Keys and Values, in contrast to what was described in the paper.140    �r�@��nbits�axis_key�141axis_value�q_group_size�residual_lengthcs2t���||_||_||_||_||_d|_dSr`)rarr�r�r�r�r�r2�rr�r�r�r�r�rbrrr�s142143zQuantizedLayer.__init__Nrr#r$r%cCsT|j|jd7_|js,|�|�|j|��|jd�|_|j|��|jd�|_	||fS|�144|j�}|�145|j	�}tj||j
|gdd�}tj||j|gdd�}|j
��dkr�|j
jdd|jkr�|j|��|jd�|_|j|��|jd�|_	tjg|j|jd�|_
tjg|j|jd�|_||fStj|j
|gdd�|_
tj|j|gdd�|_||fS)rHrI)�axisrJr�rrE)r2rMrr!�	_quantize�146contiguousr�Z_quantized_keysr�Z_quantized_values�_dequantizer=rLrrrKr�rGrFr0)rrr#r$Zdequant_keysZdequant_valuesZkeys_to_returnZvalues_to_returnrrrr'�s&147$�zQuantizedLayer.updatecCrrr)rrGr�rrrr�'r"zQuantizedLayer._quantizecCrrr)rZq_tensorrrrr�*r"zQuantizedLayer._dequantizecCrirjrkrrrrr*-rlzQuantizedLayer.get_seq_length�r�rrr�r�r)rr9r:r;rBrr=r>rr?r@rrAr'rr�r�r*rprrrbrr��sB
����������148�)149150r�c�NeZdZ					ddedededed	ef151�fd152d�
Zdd
�Zdd�Z�ZS)�QuantoQuantizedLayerr�rr�r�r�r�r�r�r�c	s�t�j|||||d�tddd�rddlm}m}m}ntd��|jdvr-t	d	|j����|j153d154vr:t	d|j155����|jd156vrGt	d|j����|jd
krN|n||_|�|_
dS)N�r�r�r�r�r�z0.2.5Trr)�MaxOptimizer�qint2�qint4ziYou need optimum-quanto package version to be greater or equal than 0.2.5 to use `QuantoQuantizedCache`. )ryr�zA`nbits` for `quanto` backend has to be one of [`2`, `4`] but got )rrRzE`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�)rarr157�optimum.quantor�r�r��ImportErrorr�ror�r��qtype�	optimizer)	rr�r�r�r�r�r�r�r�rbrrr3s,�	�158159160161�zQuantoQuantizedLayer.__init__cCs>ddlm}|�||j||j�\}}|||j||||j�}|S)Nr)�quantize_weight)r�r�r�r�r�)rrGr�r��scaleZ	zeropoint�qtensorrrrr�YszQuantoQuantizedLayer._quantizecCs|��Sr)�162dequantize)rr�rrrr�`sz QuantoQuantizedLayer._dequantizer��rr9r:rBrr�r�rprrrbrr�2s&������&r�cr�)�HQQQuantizedLayerr�rr�r�r�r�r�r�r�cs|t�j|||||d�t�std��|jdvrtd|j����|jdvr,td|j����|jdvr9td|j����t|_	dS)Nr�z4You need to install `hqq` to use `HQQQuantizedLayer`)rry�r��zM`nbits` for `HQQ` backend has to be one of [`1`, `2`, `3`, `4`, `8`] but got )rrzA`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 )163rarr	r�r�ror�r��HQQQuantizer�	quantizerr�rbrrres$�164165�166167168zHQQQuantizedLayer.__init__cCsz|jj|||jj|jj|j|jd�\}}|jj|d<|jj|||jjd�|d�|j�|d<|d�|j�|d<||fS)N)r�r0�
compute_dtyper�Z169group_sizer�)�metar0r��zero)	r��quantizerr0rFr�r��cudar.)rrGr�r�r�rrrr��s170�zHQQQuantizedLayer._quantizecCs|\}}|j�||�}|Sr)r�r�)rr�Zquant_tensorr�rGrrrr��szHQQQuantizedLayer._dequantizer�r�rrrbrr�ds&������ r�c
@s�eZdZdZ				dFdeeedeeededefd	d171�Z	dd�Z172dGd
edefdd�ZdGd
edefdd�Z
	dHdejdejd
edeeeefdeejejff173dd�Zdedededejdejf174dd�ZdId
edefd!d"�Zd#ejd
edeeeffd$d%�ZdId
edefd&d'�Zd(d)�Zd*ejfd+d,�Zd-efd.d/�Zd0efd1d2�Zd3ejfd4d5�Z e!defd6d7��Z"e!defd8d9��Z#e!defd:d;��Z$e!defd<d=��Z%e!deefd>d?��Z&d
edeejejffd@dA�Z'dBdC�Z(dDdE�Z)dS)J�Cachean175    A `Cache` is mostly a list of `CacheLayerMixin` objects, one per model layer. It serves as a container for176    the Cache of each layer.177 178    Args:179        layers (`Optional`, *optional*):180            A list of pre-created `CacheLayerMixin`. If omitted (`None`), then `layer_class_to_replicate` will181            be used.182        layer_class_to_replicate (`type[CacheLayerMixin]`, *optional*):183            Only used if `layers` is omitted (`None`), in which case it will be used as the base class for each layer,184            and the layers will be added lazily as soon as `update` is called with a `layer_idx` greater than the current185            list of layers.186        offloading (`bool`, *optional*, defaults to `False`):187            Whether to perform offloading of the layers to `cpu`, to save GPU memory.188        offload_only_non_sliding (`bool`, *optional*, defaults to `True`):189            If `offloading` is `True`, this further decides if only the non-sliding layers will be offloaded (because190            usually the sliding layers are small in size, so there is no need to offload them, and skipping it is faster).191    NFT�layers�layer_class_to_replicate�192offloading�offload_only_non_slidingcCsz|dur|durtd��|dur|durtd��|dur|ng|_||_||_|jr;||_tr3t��ntj��|_	dSdS)NaYou can construct a Cache either from a list `layers` of all the predefined `CacheLayer`, or from a `layer_class_to_replicate`, in which case the Cache will append a new layer corresponding to `layer_class_to_replicate` for each new call to `update` with an idx not already in the Cache.z_You should provide exactly one of `layers` or `layer_class_to_replicate` to initialize a Cache.)193ror�r�r��only_non_sliding�#_is_torch_greater_or_equal_than_2_7r=ZStreamr��prefetch_stream)rr�r�r�r�rrrr�s���zCache.__init__cCs|jj�d|j�d�S)Nz(layers=�))rrr�rrrrr�szCache.__repr__�	layer_idxr�cCs�|r z||j|d��d�}Wnty|j�d�}Ynw|t|j�kr)|nd}tr0|jntj�	|j��|j|�194�Wd�dS1sJwYdS)a<195        Prefetch a given layer on its device. If `only_non_sliding` is True, it will try to prefetch only the layers196        which are non-sliding. If the `layer_idx` is outside the range, this will circle back to the first layers.197        Note that we use a non-default stream for this, to avoid blocking.198        NFr)r]r�ro�lenr�r�r�r=r��streamr1�rr�r�rrrr1�s�"�zCache.prefetchcCs$|r|j|s|j|��dSdS)a199        Offload a given `layer_idx`. If `only_non_sliding` is True, it will offload `layer_idx` only if it is a200        non-sliding layer. Note that we do it on the default stream, so that we ensure all earlier201        computation in the layer's `update` methods are finished.202        N)r]r�r/r�rrrr/�s�z
Cache.offloadrr#r$r%cCs�|jdurt|j�|kr|j�|���t|j�|ks|jr2tj�|j��	|j203�|�|d|j�|j|�
|||�\}}|jrH|�||j�||fS)a�204        Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`.205 206        Parameters:207            key_states (`torch.Tensor`):208                The new key states to cache.209            value_states (`torch.Tensor`):210                The new value states to cache.211            layer_idx (`int`):212                The index of the layer to cache the states for.213            cache_kwargs (`dict[str, Any]`, *optional*):214                Additional arguments for the cache subclass. These are specific to each subclass and allow new types of215                cache to be created.216 217        Return:218            A tuple containing the updated key and value states.219        Nr)r�r�r��appendr�r=r�Zdefault_streamr0Zwait_streamr�r1r�r'r/)rrr#r�r$rrrrrr'�s220�zCache.update�221batch_sizertrurFr0cCs2tj||d|f||d�}|jD]}|�|�qdS)z�222        Initialize all the layers in advance (it's otherwise lazily initialized on the first `update` call).223        This is useful for our `export` recipes, as `export` needs everything in advance.224        rrEN)r=rvr�r!)rr�rtrurFr0Zfake_keys_tensor�layerrrr�early_initializations225 226�zCache.early_initializationrcC� |t|j�kr	dS|j|��S)z=Returns the sequence length of the cache for the given layer.r)r�r�r*�rr�rrrr*szCache.get_seq_lengthr(cCs,|t|j�kr|jddfS|j|�|�S)a227        Return a tuple (kv_length, kv_offset) corresponding to the length and offset that will be returned for228        the given layer at `layer_idx`.229        The masks are then prepared according to the given lengths (kv_length, kv_offset) and patterns for each layer.230        r)r�r�rMr)�rr(r�rrrr)$szCache.get_mask_sizescCr�)zaReturns maximum sequence length of the cache object. Dynamic caches do not have a maximum length.rR)r�r�r+r�rrrr+0szCache.get_max_cache_shapecCs&tt|j��D]	}|j|��qdS)z$Recursively reset all layers tensorsN)�ranger�r�r4r�rrrr48s�zCache.resetr5cC�(tt|j��D]231}|j|�|�qdS)z!Reorder the cache for beam searchN)r�r�r�r7)rr5r�rrrr7=��zCache.reorder_cacherScCr�)z"Crop the cache to the given lengthN)r�r�r�rV)rrSr�rrrrVBr�z232Cache.croprWcCr�)zRepeat and interleave the cacheN)r�r�r�rY)rrWr�rrrrYGr�zCache.batch_repeat_interleaverZcCr�)zSelect indices from the cacheN)r�r�r�r\)rrZr�rrrr\Lr�zCache.batch_select_indicescCs6dd�|jD�}tt|��dkrtd|����|dS)z*Return the maximum batch size of the cachecS�g|]}|j�qSr)rs��.0r�rrr�233<listcomp>T�z(Cache.max_batch_size.<locals>.<listcomp>rz0Max batch size is not consistent across layers: r)r�r��setro�rrrrrrsQszCache.max_batch_sizecCsdd�|jD�}t|�S)z,Return the maximum cache length of the cachecSr�rr~r�rrrr�\r�z'Cache.max_cache_len.<locals>.<listcomp>)r�rgr�rrrrrYszCache.max_cache_lencCs&t|j�dkr	dStdd�|jD��S)z'Return whether the cache is compileablerFcs��|]}|jVqdSr)r<r�rrr�	<genexpr>e��z'Cache.is_compileable.<locals>.<genexpr>�r�r��allrrrrr<_szCache.is_compileablecCs"t|j�dkotdd�|jD��S)z,Return whether the cache data is initializedrcsr�r)rr�rrrr�jr�z'Cache.is_initialized.<locals>.<genexpr>r�rrrrrgs"zCache.is_initializedcCsdd�|jD�S)z9Return whether the layers of the cache are sliding windowcSsg|]}t|dd��qS)r]F)�getattrr�rrrr�osz$Cache.is_sliding.<locals>.<listcomp>�r�rrrrr]lszCache.is_slidingcCs@|t|j�kr|j|j|j|jfStdt|j��d|�����z�234        Support for backwards-compatible `past_key_values` indexing, e.g. `past_key_values[0][0].shape[2]` to get the235        sequence length.236        zCache only has z. layers, attempted to access layer with index )r�r�rr�KeyErrorr�rrr�__getitem__qs237�zCache.__getitem__ccs2�tt|��D]}|j|j|j|jfVqdS�z�238        Support for backwards-compatible `past_key_values` iteration, e.g. `for x in past_key_values:` to iterate over239        keys and values240        N)r�r�r�rrr�rrr�__iter__}s��zCache.__iter__cC�241t|j�S)zN242        This value corresponds to the number of layers in the model.243        )r�r�rrrr�__len__�s244z
Cache.__len__)NNFT)Tr�r)*rr9r:r;r�listr�type�boolrrrBr1r/r=r>r?r@rrAr'rFr0r�r*r)r+r4rCr7rVrYr\�propertyrsrrr<rr]r�r�r�rrrrr��s|�245�246��247������248�)����249� r�c	s�eZdZdZ				ddeeeejejfdee	de250de251f�fdd	�
Zd252eeejejffdd�Ze
d
eeejejfd253dfdd��Z�ZS)�DynamicCachea*254255    A cache that grows dynamically as more tokens are generated. This is the default for generative models.256    It stores the key and value states as a list of `CacheLayer`, one for each layer. The expected shape for each tensor257    in the `CacheLayer`s is `[batch_size, num_heads, seq_len, head_dim]`.258    If a config is passed, it will additionally check for sliding or hybrid cache structure, greatly reducing the259    memory requirement of the cached tensors to `[batch_size, num_heads, min(seq_len, sliding_window), head_dim]`.260 261    See `Cache` for details on common methods that are implemented by all cache classes.262 263    Args:264        ddp_cache_data (`Iterable[tuple[torch.Tensor, torch.Tensor]]`, *optional*):265            It was originally added for compatibility with `torch.distributed` (DDP). In a nutshell, it is266            `map(gather_map, zip(*caches))`, i.e. each item in the iterable contains the key and value states267            for a layer gathered across replicas by torch.distributed (shape=[global batch size, num_heads, seq_len, head_dim]).268            Note: it needs to be the 1st arg as well to work correctly269        config (`PretrainedConfig`, *optional*):270            The config of the model for which this Cache will be used. If passed, it will be used to check for sliding271            or hybrid layer structure, greatly reducing the memory requirement of the cached tensors to272            `[batch_size, num_heads, min(seq_len, sliding_window), head_dim]`.273        offloading (`bool`, *optional*, defaults to `False`):274            Whether to perform offloading of the layers to `cpu`, to save GPU memory.275        offload_only_non_sliding (`bool`, *optional*, defaults to `False`):276            If `offloading` is `True`, this further decides if only the non-sliding layers will be offloaded (because277            usually the sliding layers are small in size, so there is no need to offload them, and skipping it is faster).278 279    Example:280 281    ```python282    >>> from transformers import AutoTokenizer, AutoModelForCausalLM, DynamicCache283 284    >>> model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct")285    >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")286 287    >>> inputs = tokenizer(text="My name is Qwen2", return_tensors="pt")288 289    >>> # Prepare a cache class and pass it to model's forward290    >>> past_key_values = DynamicCache(config=model.config)291    >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)292    >>> outputs.past_key_values # access cache filled with key/values from generation293    ```294    NF�ddp_cache_data�configr�r�c
s$g}|durS|jdd�}t|dd�pt|dd��t|dd�}|dur.�fdd�t|j�D�}t|d�r;|d|j�}|D]}|d	vrL|�t�d295��q=|�t��q=|durvt	|�D]\}	\}296}|durk|�t��||	�297|298|�\}}q[t|�dkr�t�j
t||d�dSt�j
|||d
�dS)NT��decoderr_�attention_chunk_size�layer_typescsg|]299}�dur300dnd�qS)N�sliding_attention�full_attentionr�r�rwrnrrr�����z)DynamicCache.__init__.<locals>.<listcomp>�num_kv_shared_layers)r��chunked_attentionrnr)r�r�r��r�r�r�)�get_text_configr�r��num_hidden_layersr3r�r�r^rD�	enumerater'r�rar)
rr�r�r�r�r�Zdecoder_configr��301layer_typer�rr#rwrbrnrr�s:�302�303304�zDynamicCache.__init__r%cCs&d}|jD]}||j|jff7}q|S)z�305        Converts the `Cache` instance into the its equivalent in the legacy cache format. Used for306        backward compatibility.307        r)r�rr)r�legacy_cacher�rrr�to_legacy_cache�s308zDynamicCache.to_legacy_cache�past_key_valuescCsP|�}|durt�d�|dur&tt|��D]}||\}}|�|||�q|S)z�309        Converts a cache in the legacy cache format into an equivalent `Cache`. Used for310        backward compatibility.311        N�9past_key_values should not be None in from_legacy_cache())�logger�warning_oncer�r�r')�clsr��cacher�rr#rrr�from_legacy_cache�s312zDynamicCache.from_legacy_cache)NNFF)rr9r:r;rrrAr=r>rr�rr��classmethodr�rprrrbrr��s$,�����4313,r�c	s8eZdZdZ		d314dedededef�fdd	�
Z�ZS)�StaticCachea�315    Static Cache class to be used with `torch.compile(model)` and `torch.export()`. It will check the `config`316    for potential hybrid cache structure, and initialize each layer accordingly.317 318    See `Cache` for details on common methods that are implemented by all cache classes.319 320    Args:321        config (`PretrainedConfig`):322            The config of the model for which this Cache will be used. It will be used to check for sliding323            or hybrid layer structure, and initialize each layer accordingly.324        max_cache_len (`int`):325            The maximum number of tokens that this Cache should hold.326        offloading (`bool`, *optional*, defaults to `False`):327            Whether to perform offloading of the layers to `cpu`, to save GPU memory.328        offload_only_non_sliding (`bool`, *optional*, defaults to `True`):329            If `offloading` is `True`, this further decides if only the non-sliding layers will be offloaded (because330            usually the sliding layers are small in size, so there is no need to offload them, and skipping it is faster).331 332    Example:333 334    ```python335    >>> from transformers import AutoTokenizer, AutoModelForCausalLM, StaticCache336 337    >>> model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf")338    >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf")339 340    >>> inputs = tokenizer(text="My name is Llama", return_tensors="pt")341 342    >>> # Prepare a cache class and pass it to model's forward343    >>> # Leave empty space for 10 new tokens, which can be used when calling forward iteratively 10 times to generate344    >>> max_generated_length = inputs.input_ids.shape[1] + 10345    >>> past_key_values = StaticCache(config=model.config, max_cache_len=max_generated_length)346    >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)347    >>> outputs.past_key_values # access cache filled with key/values from generation348    StaticCache()349    ```350    FTr�rrr�r�c351s|jdd�}t|dd�}|dur@t|dd�dur#dd�t|j�D�}nt|dd�dur6dd�t|j�D�}n352d	d�t|j�D�}t|d353�rM|d|j�}g}|D]$}|dkr_t||jd�}	n|d
krkt||jd�}	nt	|d�}	|�354|	�qQt�j|||d�dS)NTr�r�r_cS�g|]}d�qS)r�rr�rrrr�<�z(StaticCache.__init__.<locals>.<listcomp>r�cSr�)r�rr�rrrr�>r�cSr�)r�rr�rrrr�@r�r�r�)rrr_r�r~r�)
r�r�r�r�r3r�r�r_r�rqr�rar)355rr�rrr�r��kwargsr�r�r�r�rbrrr/s*356�357zStaticCache.__init__)FT)	rr9r:r;rrBr�rrprrrbrr�s+�����r�csJeZdZdZ					ddededed	ed358ededef�fd
d�
Z�ZS)�QuantizedCachea�359    A quantizer cache similar to what is described in the360    [KIVI: A Tuning-Free Asymmetric 2bit Quantization for KV Cache paper](https://huggingface.co/papers/2402.02750).361    It allows the model to generate longer sequence length without allocating too much memory for keys and values362    by applying quantization.363    The cache has two types of storage, one for original precision and one for the364    quantized cache. A `residual length` is set as a maximum capacity for the original precision cache. When the365    length goes beyond maximum capacity, the original precision cache is discarded and moved into the quantized cache.366    The quantization is done per-channel with a set `q_group_size` for both keys and values, in contrast to what was367    described in the paper.368 369    See `Cache` for details on common methods that are implemented by all cache classes.370 371    Args:372        backend (`str`):373            The quantization backend to use. One of `("quanto", "hqq").374        config (`PretrainedConfig`):375            The config of the model for which this Cache will be used.376        nbits (`int`, *optional*, defaults to 4):377            The number of bits for quantization.378        axis_key (`int`, *optional*, defaults to 0):379            The axis on which to quantize the keys.380        axis_value (`int`, *optional*, defaults to 0):381            The axis on which to quantize the values.382        q_group_size (`int`, *optional*, defaults to 64):383            Quantization is done per-channel according to a set `q_group_size` for both keys and values.384        residual_length (`int`, *optional*, defaults to 128):385            Maximum capacity for the original precision cache386    r�rr�r��backendr�r�r�r�r�r�c	sl|dkrt�n|dkrt�ntd|�d���|jdd�}������fdd�t|j�D�}t�j|d	�dS)387N�quanto�hqqzUnknown quantization backend `�`Tr�csg|]388}��������qSrrr��r�r�Zlayer_classr�r�r�rrr��r�z+QuantizedCache.__init__.<locals>.<listcomp>r�)r�r�ror�r�r�rar)	rrr�r�r�r�r�r�r�rbrrrus389�zQuantizedCache.__init__r�)	rr9r:r;r@rrBrrprrrbrr�Vs,"��������r�c@sfeZdZdZd7dd�Zdefdd�Zdd	�Zd390ede	e391je392je393je394jffdd�Zd
d�Z
de	e	e395jfdd�Zedeee	e396jdfddfdd��Zd8d397edefdd�Zdd�Zde398jfdd�Zdefdd�Zd efd!d"�Zd#ed$edd%fd&d'�Zd(efd)d*�Zd+e399jfd,d-�Zdefd.d/�Zd0e400jd401ede	eeffd1d2�Zed3d4��Z ede!fd5d6��Z"dS)9�EncoderDecoderCachea�402    Base, abstract class for all encoder-decoder caches. Can be used to hold combinations of self-attention and403    cross-attention caches.404 405    See `Cache` for details on common methods that are implemented by all cache classes.406 407    Args:408        caches (`Iterable`):409            Usually an iterable of length 2, containing 2 `Cache` objects, the first one for self-attention, the410            second one for cross-attention. Can optionally also be an iterable of length 1, containing a411            `tuple[tuple[torch.Tensor]]` (usually used for compatibility with torch dp and ddp).412 413    Example:414 415    ```python416    >>> from transformers import AutoProcessor, AutoModelForCausalLM, DynamicCache, EncoderDecoderCache417 418    >>> model = AutoModelForCausalLM.from_pretrained("openai/whisper-small")419    >>> processor = AutoProcessor.from_pretrained("openai/whisper-small")420 421    >>> inputs = processor(audio=YOUR-AUDIO, return_tensors="pt")422 423    >>> # Prepare cache classes for encoder and decoder and pass it to model's forward424    >>> self_attention_cache = DynamicCache(config=self.config)425    >>> cross_attention_cache = DynamicCache(config=self.config)426    >>> past_key_values = EncoderDecoderCache(self_attention_cache, cross_attention_cache)427    >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)428    >>> outputs.past_key_values # access cache filled with key/values from generation429    EncoderDecoderCache()430    ```431    r%NcGs,t|�dkr@t�|_t�|_t|d�D]*\}}|dd�\}}|j�|||�t|�dkr>|dd�\}}|j�|||�qn:t|�dkrqt|dt�rTt|dt�sftdt	|d��dt	|d�����|d|_|d|_n	t432dt|�����i|_tt|j��D]}t
|j�|�dk�|j|<q�dS)Nrrryz;One of the two arguments is not a Cache: type(caches[0]) = z, type(caches[1]) = zExpected 1 or 2 arguments, got )r�r��self_attention_cache�cross_attention_cacher�r'�433isinstancer��	TypeErrorr�ro�434is_updatedr�r�r*)r�cachesr��key_value_statesrr#rrrr�s*��$435�zEncoderDecoderCache.__init__cCs|jj�d|j�d|j�d�S)Nz(self_attention_cache=z, cross_attention_cache=r�)rrrrrrrrr�s��zEncoderDecoderCache.__repr__ccsN�tt|��D]}|jj|j|jj|j|jj|j|jj|jfVqdSr�)r�r�rr�rrrr�rrrr��s���zEncoderDecoderCache.__iter__r�cCsX|t|�kr |jj|j|jj|j|jj|j|jj|jfStdt|��d|����r�)r�rr�rrrr�r�rrrr��s�zEncoderDecoderCache.__getitem__cCr�)z�436        Support for backwards-compatible `past_key_values` length, e.g. `len(past_key_values)`. This value corresponds437        to the number of layers in the model.438        )r�rrrrrr��s439zEncoderDecoderCache.__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)r�r�ziprr�)rr��	self_attn�440cross_attnrrrr��s�441�z#EncoderDecoderCache.to_legacy_cacher�.cCs�|t�t��}|durt�d�|St|�D]/\}}|dd�\}}|j�|||�t|�dkrE|dd�\}}|j�|||�d|j|<q|S)zUConverts a cache in the legacy cache format into an equivalent `EncoderDecoderCache`.Nr�ryT)	r�r�r�r�rr'r�rr442)r�r�r�r�rrr#rrrr��s443	�444�z%EncoderDecoderCache.from_legacy_cachercCs|j�|�S)zYReturns the sequence length of the cached states. A layer index can be optionally passed.)rr*r�rrrr*sz"EncoderDecoderCache.get_seq_lengthcCs.|j��|j��|jD]}d|j|<q
dSr)rr4rr445r�rrrr4s446447448449�zEncoderDecoderCache.resetr5cCs|j�|�|j�|�dS)zDReorders the cache for beam search, given the selected beam indices.N)rr7rr6rrrr7sz!EncoderDecoderCache.reorder_cache�methodcCsDt|jt�rt|jt�s td|�d|j���d|j���d���dS)Nrz)` is only defined for dynamic cache, got z" for the self attention cache and z for the cross attention cache.)rrr�rro�__str__)rrrrr�check_dynamic_caches450�451����z'EncoderDecoderCache.check_dynamic_cache�maximum_lengthcCs|�|jj�|j�|�dS)z�452        Crop the past key values up to a new `maximum_length` in terms of tokens. `maximum_length` can also be453        negative to remove `maximum_length` tokens. This is used in assisted decoding and contrastive search (on the Hub).454        N)rrVrr)rrrrrrV*szEncoderDecoderCache.crop�full_batch_size�455split_sizezlist[EncoderDecoderCache]cCsV|�|jj�|j�||�}|j�||�}g}t||�D]\}}|�t||��q|S)z�456        Split the current instance into a list of `DynamicCache` by the batch size. This will be used by457        `_split_model_inputs()` in `generation.utils`458        )r�batch_splitrrrr
r�r)rrrrr�outrrrrrr2szEncoderDecoderCache.batch_splitrWcC�*|�|jj�|j�|�|j�|�dS)zaRepeat the cache `repeats` times in the batch dimension. Used in contrastive search (on the Hub).N)rrYrrrrXrrrrY@�z+EncoderDecoderCache.batch_repeat_interleaverZcCr)zeOnly keep the `indices` in the batch dimension of the cache. Used in contrastive search (on the Hub).N)rr\rrrr[rrrr\Frz(EncoderDecoderCache.batch_select_indicescCs459|j��S)zKReturns the maximum sequence length (i.e. max capacity) of the cache object)rr+rrrrr+Ls460z'EncoderDecoderCache.get_max_cache_shaper(cCs|j�||�Sr)rr)r�rrrr)Psz"EncoderDecoderCache.get_mask_sizescC�|jjSr)rr]rrrrr]S�zEncoderDecoderCache.is_slidingcCrr)rr<rrrrr<Wrz"EncoderDecoderCache.is_compileabler8r�)#rr9r:r;rr@rr�rBrAr=r>r�r�r�r�rrZFloatTensorr�r*r4rCr7rrVrrYr\r+r)r�r]r�r<rrrrr�s8461 &
�� 462rc�&eZdZdedef�fdd�Z�ZS)�SlidingWindowLayerrrr_c�t�d�t��||�dS)Nz�`SlidingWindowLayer` is deprecated and will be removed in version v4.59 Use `StaticSlidingWindowLayer` instead, which is a better name for it.�r�r�rar�rrrr_rbrrr`��zSlidingWindowLayer.__init__�rr9r:rBrrprrrbrr_�rcr)�ChunkedSlidingLayerrrr_cr)Nz�`ChunkedSlidingLayer` is deprecated and will be removed in version v4.59 Use `StaticSlidingWindowLayer` instead, which has the exact same functionalities.rr rbrrrir!zChunkedSlidingLayer.__init__r"rrrbrr$hr#r$cseZdZd�fdd�Z�ZS)�OffloadedCacher%Ncst�d�t�jdd�dS)Nzo`OffloadedCache` is deprecated and will be removed in version v4.59 Use `DynamicCache(offloading=True)` insteadT)r�rrrbrrrrr!zOffloadedCache.__init__r8)rr9r:rrprrrbrr%qsr%c�&eZdZdedef�fdd�Z�ZS)�OffloadedStaticCacher�rrc� t�d�t�j||dd�dS)Nzy`OffloadedStaticCache` is deprecated and will be removed in version v4.59 Use `StaticCache(..., offloading=True)` insteadT�r�rrr�r�rr�rr�argsr�rbrrr{��zOffloadedStaticCache.__init__�rr9r:rrBrrprrrbrr'zr#r'cr&)�SlidingWindowCacher�rrc�t�d�t�j||d�dS)Nz�`SlidingWindowCache` is deprecated and will be removed in version v4.59 Use `StaticCache(...)` instead which will correctly infer the type of each layer.�r�rrrr*rbrrr���zSlidingWindowCache.__init__r-rrrbrr.�r#r.cr&)�HybridCacher�rrcr/)Nz�`HybridCache` is deprecated and will be removed in version v4.59 Use `StaticCache(...)` instead which will correctly infer the type of each layer.r0rr*rbrrr�r1zHybridCache.__init__r-rrrbrr2�r#r2cr&)�HybridChunkedCacher�rrcr/)Nz�`HybridChunkedCache` is deprecated and will be removed in version v4.59 Use `StaticCache(...)` instead which will correctly infer the type of each layer.r0rr*rbrrr�r1zHybridChunkedCache.__init__r-rrrbrr3�r#r3cr&)�OffloadedHybridCacher�rrcr()Nz�`OffloadedHybridCache` is deprecated and will be removed in version v4.59 Use `StaticCache(..., offload=True)` instead which will correctly infer the type of each layer.Tr)rr*rbrrr�r,zOffloadedHybridCache.__init__r-rrrbrr4�r#r4c
�BeZdZ					d
dedededed	ed463ef�fdd�
Z�ZS)�QuantoQuantizedCacher�rr�r�r�r�r�r�r�r�c	�&t�d�t��d||||||�dS)Nz~`QuantoQuantizedCache` is deprecated and will be removed in version v4.59 Use `QuantizedCache(backend='quanto', ...)` instead.rr�rr�r�r�r�r�r�rbrrr��	�zQuantoQuantizedCache.__init__r�r-rrrbrr6��&�������r6c
r5)�HQQQuantizedCacher�rr�r�r�r�r�r�r�r�c	r7)Nzx`HQQQuantizedCache` is deprecated and will be removed in version v4.59 Use `QuantizedCache(backend='hqq', ...)` instead.rrr8rbrrr�r9zHQQQuantizedCache.__init__r�r-rrrbrr;�r:r;c@seZdZdZddd�ZdS)�	SinkCachea
464    It is now a `custom_generate` repository on the Hub: https://huggingface.co/transformers-community/sink_cache.465    See [these docs](https://huggingface.co/docs/transformers/generation_strategies#custom-decoding-methods) for466    general `custom_generate`usage.467    r%NcKstd��)Nz�`SinkCache` has been moved as a `custom_generate` repository on the Hub: https://huggingface.co/transformers-community/sink_cache. See the repository for usage examples.)r})rr�rrrr�s�zSinkCache.__init__r8)rr9r:r;rrrrrr<�sr<)0�abcrr�collections.abcr�typingrrr=Zconfiguration_utilsr�utilsr	r468rrr
Zhqq.core.quantizerr�r�Z469get_loggerrr�rrDr^rqr�r�r�r�r�r�r�r�rrr$r%r'r.r2r3r4r6r;r<rrrr�<module>sH	470:SQm}P26uyO8R								
Aluode/PerceptionLabPortable · CoolFace