Buckets:

hf-doc-build/doc / transformers /main /fr /kv_cache.html
mishig's picture
download
raw
75 kB
<meta charset="utf-8" /><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Stratégies de cache&quot;,&quot;local&quot;:&quot;cache-strategies&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Cache par défaut&quot;,&quot;local&quot;:&quot;default-cache&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Cache de taille fixe&quot;,&quot;local&quot;:&quot;fixed-size-cache&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Garder les tenseurs de génération sur le CPU&quot;,&quot;local&quot;:&quot;keep-generation-tensors-on-cpu&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Déchargement du cache&quot;,&quot;local&quot;:&quot;cache-offloading&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Cache quantifié&quot;,&quot;local&quot;:&quot;quantized-cache&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Cache encodeur-décodeur&quot;,&quot;local&quot;:&quot;encoder-decoder-cache&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Caches spécifiques aux modèles&quot;,&quot;local&quot;:&quot;model-specific-caches&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Génération itérative&quot;,&quot;local&quot;:&quot;iterative-generation&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Recadrer un cache&quot;,&quot;local&quot;:&quot;crop-a-cache&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Préremplir un cache (cache de préfixe)&quot;,&quot;local&quot;:&quot;prefill-a-cache-prefix-caching&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2}],&quot;depth&quot;:1}"/>
<link href="/docs/transformers/main/en/_app/immutable/entry/start.COK5KGrS.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/CpX-fPQX.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/Bvu3qeNQ.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/entry/app.CjTXVmse.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/DDEoM7Dh.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/DOLBYqcr.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/DsnmJJEf.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/DR_h0zy8.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/nodes/0.DPJVnUkl.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/CsYDzxHY.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/nodes/4.BLeaAS-x.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/DuAZEI1R.js" rel="modulepreload">
<!--u3e3bh--><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Cache strategies&quot;,&quot;local&quot;:&quot;cache-strategies&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Default cache&quot;,&quot;local&quot;:&quot;default-cache&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Fixed-size cache&quot;,&quot;local&quot;:&quot;fixed-size-cache&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Keep generation tensors on CPU&quot;,&quot;local&quot;:&quot;keep-generation-tensors-on-cpu&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Cache offloading&quot;,&quot;local&quot;:&quot;cache-offloading&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Quantized cache&quot;,&quot;local&quot;:&quot;quantized-cache&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Encoder-decoder cache&quot;,&quot;local&quot;:&quot;encoder-decoder-cache&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Model-specific caches&quot;,&quot;local&quot;:&quot;model-specific-caches&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Iterative generation&quot;,&quot;local&quot;:&quot;iterative-generation&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Crop a cache&quot;,&quot;local&quot;:&quot;crop-a-cache&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Prefill a cache (prefix caching)&quot;,&quot;local&quot;:&quot;prefill-a-cache-prefix-caching&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2}],&quot;depth&quot;:1}"/><!---->
<link href="/docs/transformers/main/en/_app/immutable/assets/0.tn0RQdqM.css" rel="modulepreload"> <!--[--><!--[0--><!--[--><!--[0--><!--[--><p></p> <div class="items-center shrink-0 min-w-[100px] max-sm:min-w-[50px] justify-end ml-auto flex" style="float: inline-end; margin-inline-start: 10px; display: inline-flex; position: relative; z-index: 10;"><div dir="ltr" class="inline-flex rounded-md max-sm:rounded-sm"><button class="inline-flex items-center gap-1 h-7 max-sm:h-7 px-2 max-sm:px-1.5 text-sm font-medium text-gray-800 border border-r-0 rounded-l-md max-sm:rounded-l-sm border-gray-200 bg-white hover:shadow-inner dark:border-gray-850 dark:bg-gray-950 dark:text-gray-200 dark:hover:bg-gray-800" aria-live="polite"><span class="inline-flex items-center justify-center rounded-md p-0.5 max-sm:p-0 hover:text-gray-800 dark:hover:text-gray-200"><svg class="sm:size-3.5 size-3" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----></span> <span dir="auto">Copy page</span></button> <button class="inline-flex items-center justify-center w-6 max-sm:w-5 h-7 max-sm:h-7 disabled:pointer-events-none text-sm text-gray-500 hover:text-gray-700 dark:hover:text-white rounded-r-md max-sm:rounded-r-sm border border-l transition border-gray-200 bg-white hover:shadow-inner dark:border-gray-850 dark:bg-gray-950 dark:text-gray-200 dark:hover:bg-gray-800" aria-haspopup="menu" aria-expanded="false" aria-label="Open copy menu"><svg class="transition-transform text-gray-400 overflow-visible sm:size-3.5 size-3 rotate-0" width="1em" height="1em" viewBox="0 0 12 7" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 1L6 6L11 1" stroke="currentColor"></path></svg><!----></button></div> <!--[-1--><!--]--></div><!----> <!--[0--><h1 class="relative group"><a id="cache-strategies" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#cache-strategies"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Stratégies de cache<!----></span></h1><!--]--><!----> <p>Les vecteurs clé-valeur (KV) sont utilisés pour calculer les scores d'attention. Pour les modèles autorégressifs, les scores KV sont calculés <em>à chaque</em> itération, car le modèle prédit un jeton à la fois. Chaque prédiction dépend des jetons précédents, ce qui signifie que le modèle effectue les mêmes calculs à chaque fois.</p> <p>Un <em>cache</em> KV stocke ces calculs afin qu'ils puissent être réutilisés sans avoir à les recalculer. Un cache efficace est crucial pour optimiser les performances du modèle, car il réduit le temps de calcul et améliore les taux de réponse. Consultez la documentation <a href="./cache_explanation">Caching</a> pour une explication plus détaillée du fonctionnement d'un cache.</p> <p>Transformers propose plusieurs classes <a href="/docs/transformers/main/fr/internal/generation_utils#transformers.Cache">Cache</a> qui implémentent différents mécanismes de mise en cache. Certaines de ces classes <a href="/docs/transformers/main/fr/internal/generation_utils#transformers.Cache">Cache</a> sont optimisées pour économiser la mémoire, tandis que d'autres sont conçues pour maximiser la vitesse de génération. Reportez-vous au tableau ci-dessous pour comparer les types de cache et l'utiliser afin de sélectionner le cache le plus adapté à votre cas d'usage.</p> <table><thead><tr><th>Type de cache</th><th>Prend en charge les couches glissantes</th><th>Prend en charge le déchargement</th><th>Prend en charge torch.compile()</th><th>Mémoire attendue</th></tr></thead><tbody><tr><td>Cache dynamique</td><td>Oui</td><td>Oui</td><td>Non</td><td>Moyen</td></tr><tr><td>Cache statique</td><td>Oui</td><td>Oui</td><td>Oui</td><td>Élevé</td></tr><tr><td>Cache quantifié</td><td>Non</td><td>Non</td><td>Non</td><td>Faible</td></tr></tbody></table> <p>Ce guide vous présente les différentes classes <a href="/docs/transformers/main/fr/internal/generation_utils#transformers.Cache">Cache</a> et vous montre comment les utiliser pour la génération.</p> <!--[1--><h2 class="relative group"><a id="default-cache" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#default-cache"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Cache par défaut<!----></span></h2><!--]--><!----> <p>Le <a href="/docs/transformers/main/fr/internal/generation_utils#transformers.DynamicCache">DynamicCache</a> est la classe de cache par défaut pour tous les modèles. Il permet à la taille du cache de croître dynamiquement afin de stocker un nombre croissant de clés et de valeurs au fur et à mesure que la génération progresse.</p> <p>Notez que pour les modèles utilisant l’attention à fenêtre glissante (Mistral, Gemma2,…) ou l’attention par morceaux (Llama4), le cache cessera de croître lorsque les couches utilisant ces types d’attention auront atteint leur taille maximale (la taille de la fenêtre glissante ou du morceau).</p> <p>Désactivez le cache en configurant <code>use_cache=False</code> dans <a href="/docs/transformers/main/fr/main_classes/text_generation#transformers.GenerationMixin.generate">generate()</a>.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copié</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-2-7b-chat-hf&quot;</span>)
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-2-7b-chat-hf&quot;</span>, dtype=torch.float16, device_map=<span class="hljs-string">&quot;auto&quot;</span>)
inputs = tokenizer(<span class="hljs-string">&quot;I like rock music because&quot;</span>, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(model.device)
model.generate(**inputs, do_sample=<span class="hljs-literal">False</span>, max_new_tokens=<span class="hljs-number">20</span>, use_cache=<span class="hljs-literal">False</span>)<!----></pre></div><!----> <p>Les classes de cache peuvent également être initialisées avant d’être appelées et passées au paramètre <a href="/docs/transformers/main/fr/internal/generation_utils#transformers.generation.GenerateDecoderOnlyOutput.cache">cache</a> des modèles. Cela peut être utile pour un contrôle plus fin ou pour des usages plus avancés, tels que la mise en cache du contexte.</p> <p>Dans la plupart des cas, il est plus simple de définir la stratégie de cache dans le paramètre <a href="/docs/transformers/main/fr/main_classes/text_generation#transformers.GenerationConfig.cache_implementation">cache_implementation</a>.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copié</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoTokenizer, AutoModelForCausalLM, DynamicCache
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-2-7b-chat-hf&quot;</span>)
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-2-7b-chat-hf&quot;</span>, dtype=torch.float16, device_map=<span class="hljs-string">&quot;auto&quot;</span>)
inputs = tokenizer(<span class="hljs-string">&quot;I like rock music because&quot;</span>, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(model.device)
cache = DynamicCache(config=model.config)
out = model.generate(**inputs, do_sample=<span class="hljs-literal">False</span>, max_new_tokens=<span class="hljs-number">20</span>, cache=cache)<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="fixed-size-cache" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#fixed-size-cache"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Cache de taille fixe<!----></span></h2><!--]--><!----> <p>Le <a href="/docs/transformers/main/fr/internal/generation_utils#transformers.DynamicCache">DynamicCache</a> par défaut vous empêche de tirer parti de la plupart des optimisations just-in-time (JIT), car la taille du cache n’est pas fixe. Les optimisations JIT vous permettent de minimiser la latence au détriment de l’utilisation de la mémoire. Tous les types de cache suivants sont compatibles avec des optimisations JIT telles que <a href="./perf_torch_compile">torch.compile</a> pour accélérer la génération.</p> <p>Un cache de taille fixe (<a href="/docs/transformers/main/fr/internal/generation_utils#transformers.StaticCache">StaticCache</a>) pré-alloue une taille de cache maximale spécifique pour les paires kv. Vous pouvez générer jusqu’à la taille de cache maximale sans avoir besoin de la modifier. Cependant, le fait d’avoir une taille fixe (généralement grande) pour les états clé/valeur signifie qu’au cours de la génération, de nombreux jetons seront en réalité masqués car ils ne devraient pas participer à l’attention. Cette astuce permet donc de <code>compile</code> facilement l’étape de décodage, mais elle entraîne un gaspillage de jetons dans le calcul de l’attention. Comme pour tout, il s’agit d’un compromis qui sera très avantageux si vous générez avec plusieurs séquences de longueurs plus ou moins similaires, mais qui peut s’avérer sous-optimal si vous avez par exemple une très grande séquence, suivie uniquement de séquences courtes (la taille fixe du cache étant grande, beaucoup serait gaspillé pour les séquences courtes). Assurez-vous de bien comprendre l’impact si vous l’utilisez !</p> <p>En ce qui concerne <a href="/docs/transformers/main/fr/internal/generation_utils#transformers.DynamicCache">DynamicCache</a>, notez que pour les modèles utilisant l'attention à fenêtre glissante (Mistral, Gemma2,…) ou l'attention par morceaux (Llama4), le cache ne dépassera jamais la taille de la fenêtre glissante/des morceaux sur les couches utilisant ces types d'attention, même si la longueur maximale spécifiée est supérieure.</p> <p>Vous pouvez activer <a href="/docs/transformers/main/fr/internal/generation_utils#transformers.StaticCache">StaticCache</a> en configurant <code>cache_implementation="static"</code> dans <a href="/docs/transformers/main/fr/main_classes/text_generation#transformers.GenerationMixin.generate">generate()</a>. Cela activera également la <code>compilation</code> automatique de l’étape de décodage pour les stratégies de décodage glouton, par échantillonnage et <a href="./assisted_decoding">assisted</a>.</p> <p>Pour le décodage assisté, la prise en charge des caches statiques est limitée à quelques classes de types de couches, car les jetons de brouillon rejetés doivent être annulés sur place, ce qui ne fonctionne que tant qu’aucun état n’a été évacué du cache. Par exemple, une couche à fenêtre glissante n’est utilisable que tant que le nombre de jetons traités est inférieur à la fenêtre, sinon les jetons plus anciens commencent à être évacués du cache, et comme sa taille doit être statique, nous ne pouvons pas conserver temporairement les états supplémentaires en mémoire de la même manière que nous le faisons pour un <a href="/docs/transformers/main/fr/internal/generation_utils#transformers.DynamicCache">DynamicCache</a> avec une couche à fenêtre glissante.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copié</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-2-7b-chat-hf&quot;</span>)
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-2-7b-chat-hf&quot;</span>, dtype=torch.float16, device_map=<span class="hljs-string">&quot;auto&quot;</span>)
inputs = tokenizer(<span class="hljs-string">&quot;Hello, my name is&quot;</span>, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(model.device)
out = model.generate(**inputs, do_sample=<span class="hljs-literal">False</span>, max_new_tokens=<span class="hljs-number">20</span>, cache_implementation=<span class="hljs-string">&quot;static&quot;</span>)
tokenizer.batch_decode(out, skip_special_tokens=<span class="hljs-literal">True</span>)[<span class="hljs-number">0</span>]
<span class="hljs-string">&quot;Hello, my name is [Your Name], and I am a [Your Profession] with [Number of Years] of&quot;</span><!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="keep-generation-tensors-on-cpu" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#keep-generation-tensors-on-cpu"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Garder les tenseurs de génération sur le CPU<!----></span></h2><!--]--><!----> <p>Les backends de compilation tels que Neuron et TPU tracent votre modèle en un graphe de calcul fixe. La boucle de génération maintient des tenseurs (séquence de sortie, <code>attention_mask</code>, <code>position_ids</code>) qui augmentent d’un jeton à chaque étape. Le compilateur retrace le graphe chaque fois que la forme de ces tenseurs change sur l’accélérateur, ce qui ralentit la génération.</p> <p><a href="/docs/transformers/main/fr/main_classes/text_generation#transformers.GenerationMixin.generate">generate()</a> ne déplace que les tenseurs consommés par <code>forward</code> vers le périphérique du modèle, juste avant chaque appel à <code>forward</code>. La sortie est ensuite déplacée pour correspondre au périphérique de l’entrée. Passez vos entrées sur CPU afin de maintenir la gestion des tenseurs croissants de la boucle hors de l’accélérateur. Le graphe compilé reste stable, et comme la sortie suit le périphérique de l’entrée, la sortie générée reste sur CPU.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copié</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;Qwen/Qwen3-0.6B&quot;</span>)
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;Qwen/Qwen3-0.6B&quot;</span>, device_map=<span class="hljs-string">&quot;auto&quot;</span>)
<span class="hljs-comment"># leave the inputs on CPU instead of calling .to(model.device).</span>
inputs = tokenizer(<span class="hljs-string">&quot;The French Bread Law states&quot;</span>, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>)
<span class="hljs-comment"># generate runs forward on the model device but returns the output on the input_ids device.</span>
output = model.generate(**inputs, do_sample=<span class="hljs-literal">False</span>, max_new_tokens=<span class="hljs-number">20</span>)
<span class="hljs-built_in">print</span>(output.device)
cpu<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="cache-offloading" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#cache-offloading"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Déchargement du cache<!----></span></h2><!--]--><!----> <p>Le cache KV peut occuper une part importante de la mémoire et devenir un <a href="https://hf.co/blog/llama31#inference-memory-requirements" rel="nofollow">goulot d'étranglement</a> pour la génération de contexte long. Les caches optimisés pour la mémoire privilégient une réduction de l'empreinte mémoire au détriment de la vitesse. C'est particulièrement important pour les grands modèles de langage (LLM) et si votre matériel est limité en mémoire.</p> <p>Le déchargement du cache permet d’économiser de la mémoire GPU en déplaçant le cache KV des couches du modèle, à l’exception d’une seule, vers le CPU. Seule la couche courante est maintenue sur le GPU pendant l’itération <code>forward</code> du modèle sur les couches. Le cache de la couche suivante est préchargé de manière asynchrone, et le cache de la couche courante est renvoyé vers le CPU après le calcul d’attention.</p> <p>Vous pouvez envisager l’offloading si vous disposez d’un GPU de petite taille et que vous rencontrez des erreurs de mémoire insuffisante (OOM).</p> <blockquote class="warning"><p>Vous remarquerez peut-être une légère dégradation du débit de génération par rapport à un cache entièrement sur l’appareil, en fonction de votre modèle et de vos choix de génération (taille du contexte, nombre de jetons générés, nombre de faisceaux, etc.). Cela est dû au fait que le déplacement des états clé/valeur de part et d’autre nécessite un certain travail.</p></blockquote> <p>Le déchargement (offloading) est disponible pour <a href="/docs/transformers/main/fr/internal/generation_utils#transformers.DynamicCache">DynamicCache</a> et <a href="/docs/transformers/main/fr/internal/generation_utils#transformers.StaticCache">StaticCache</a>. Vous pouvez l’activer en configurant <code>cache_implementation="offloaded"</code> pour la version dynamique, ou <code>cache_implementation="offloaded_static"</code> pour la version statique, dans <a href="/docs/transformers/main/fr/main_classes/text_generation#transformers.GenerationConfig">GenerationConfig</a> ou <a href="/docs/transformers/main/fr/main_classes/text_generation#transformers.GenerationMixin.generate">generate()</a>.
De plus, vous pouvez également instancier votre propre <a href="/docs/transformers/main/fr/internal/generation_utils#transformers.DynamicCache">DynamicCache</a> ou <a href="/docs/transformers/main/fr/internal/generation_utils#transformers.StaticCache">StaticCache</a> avec l’option <code>offloading=True</code>, et passer ce cache dans <code>generate</code> ou dans la méthode <code>forward</code> de votre modèle (par exemple, <code>cache=DynamicCache(config=model.config, offloading=True)</code> pour un cache dynamique).</p> <p>Notez que les deux classes <a href="/docs/transformers/main/fr/internal/generation_utils#transformers.Cache">Cache</a> mentionnées ci-dessus disposent d’une option supplémentaire lors de leur instanciation directe, <code>offload_only_non_sliding</code>.
Cet argument supplémentaire détermine si les couches utilisant l’attention à fenêtre glissante ou par morceaux (le cas échéant) seront également déchargées. Étant donné que ces couches sont généralement courtes de toute façon, il peut être préférable d’éviter de les décharger, car le déchargement peut entraîner une pénalité en termes de vitesse. Par défaut, cette option est <code>False</code> pour <a href="/docs/transformers/main/fr/internal/generation_utils#transformers.DynamicCache">DynamicCache</a>, et <code>True</code> pour <a href="/docs/transformers/main/fr/internal/generation_utils#transformers.StaticCache">StaticCache</a>.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copié</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoTokenizer, AutoModelForCausalLM
ckpt = <span class="hljs-string">&quot;microsoft/Phi-3-mini-4k-instruct&quot;</span>
tokenizer = AutoTokenizer.from_pretrained(ckpt)
model = AutoModelForCausalLM.from_pretrained(ckpt, dtype=torch.float16, device_map=<span class="hljs-string">&quot;auto&quot;</span>)
inputs = tokenizer(<span class="hljs-string">&quot;Fun fact: The shortest&quot;</span>, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(model.device)
out = model.generate(**inputs, do_sample=<span class="hljs-literal">False</span>, max_new_tokens=<span class="hljs-number">23</span>, cache_implementation=<span class="hljs-string">&quot;offloaded&quot;</span>)
<span class="hljs-built_in">print</span>(tokenizer.batch_decode(out, skip_special_tokens=<span class="hljs-literal">True</span>)[<span class="hljs-number">0</span>])
Fun fact: The shortest war <span class="hljs-keyword">in</span> history was between Britain <span class="hljs-keyword">and</span> Zanzibar on August <span class="hljs-number">27</span>, <span class="hljs-number">1896.</span><!----></pre></div><!----> <p>L'exemple ci-dessous montre comment vous pouvez basculer sur un cache déchargé si vous épuisez la mémoire :</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copié</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoTokenizer, AutoModelForCausalLM
<span class="hljs-keyword">from</span> accelerate <span class="hljs-keyword">import</span> Accelerator
<span class="hljs-keyword">def</span> <span class="hljs-title function_">resilient_generate</span>(<span class="hljs-params">model, *args, **kwargs</span>):
oom = <span class="hljs-literal">False</span>
device = Accelerator().device
torch_device_module = <span class="hljs-built_in">getattr</span>(torch, device, torch.cuda)
<span class="hljs-keyword">try</span>:
<span class="hljs-keyword">return</span> model.generate(*args, **kwargs)
<span class="hljs-keyword">except</span> torch.OutOfMemoryError <span class="hljs-keyword">as</span> e:
<span class="hljs-built_in">print</span>(e)
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;retrying with cache_implementation=&#x27;offloaded&#x27;&quot;</span>)
oom = <span class="hljs-literal">True</span>
<span class="hljs-keyword">if</span> oom:
torch_device_module.empty_cache()
kwargs[<span class="hljs-string">&quot;cache_implementation&quot;</span>] = <span class="hljs-string">&quot;offloaded&quot;</span>
<span class="hljs-keyword">return</span> model.generate(*args, **kwargs)
ckpt = <span class="hljs-string">&quot;microsoft/Phi-3-mini-4k-instruct&quot;</span>
tokenizer = AutoTokenizer.from_pretrained(ckpt)
model = AutoModelForCausalLM.from_pretrained(ckpt, dtype=torch.float16, device_map=<span class="hljs-string">&quot;auto&quot;</span>)
prompt = [<span class="hljs-string">&quot;okay &quot;</span>*<span class="hljs-number">1000</span> + <span class="hljs-string">&quot;Fun fact: The most&quot;</span>]
inputs = tokenizer(prompt, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(model.device)
beams = { <span class="hljs-string">&quot;num_beams&quot;</span>: <span class="hljs-number">40</span>, <span class="hljs-string">&quot;num_return_sequences&quot;</span>: <span class="hljs-number">20</span>, <span class="hljs-string">&quot;max_new_tokens&quot;</span>: <span class="hljs-number">23</span>, <span class="hljs-string">&quot;early_stopping&quot;</span>: <span class="hljs-literal">True</span>, }
out = resilient_generate(model, **inputs, **beams)
responses = tokenizer.batch_decode(out[:,-<span class="hljs-number">28</span>:], skip_special_tokens=<span class="hljs-literal">True</span>)<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="quantized-cache" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#quantized-cache"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Cache quantifié<!----></span></h2><!--]--><!----> <p><a href="/docs/transformers/main/fr/internal/generation_utils#transformers.QuantizedCache">QuantizedCache</a> réduit les besoins en mémoire en quantifiant les valeurs KV à une précision inférieure. <a href="/docs/transformers/main/fr/internal/generation_utils#transformers.QuantizedCache">QuantizedCache</a> prend actuellement en charge trois backends de quantification :</p> <ul><li><code>hqq</code> prend en charge les types de données int1, int2, int3, int4 et int8.</li> <li><code>quanto</code> prend en charge les types de données int2 et int4. C'est le backend de quantification par défaut.</li> <li><code>fp8</code> stocke les valeurs KV en virgule flottante sur 8 bits (<code>float8_e4m3fn</code>). Il n’exige aucune dépendance supplémentaire et quantise par tenseur plutôt que par groupe, ce qui le rend incompatible avec <code>nbits</code>, <code>axis_key</code>, <code>axis_value</code>, <code>q_group_size</code> et <code>residual_length</code>.</li></ul> <blockquote class="warning"><p>La quantification du cache peut nuire à la latence si la longueur du contexte est courte et qu’il y a suffisamment de mémoire GPU disponible pour la génération sans activer la quantification du cache. Essayez de trouver un équilibre entre l’efficacité mémoire et la latence.</p></blockquote> <p>Activez <a href="/docs/transformers/main/fr/internal/generation_utils#transformers.QuantizedCache">QuantizedCache</a> en configurant <code>cache_implementation="quantized"</code> dans <a href="/docs/transformers/main/fr/main_classes/text_generation#transformers.GenerationConfig">GenerationConfig</a>. Le backend de quantification, ainsi que les paramètres de quantification supplémentaires, sont spécifiés dans le dictionnaire <code>cache_config</code> passé à <a href="/docs/transformers/main/fr/main_classes/text_generation#transformers.GenerationMixin.generate">generate()</a>. Vous devriez utiliser les valeurs par défaut pour ces paramètres supplémentaires, sauf si vous rencontrez des erreurs de mémoire insuffisante. Dans ce cas, envisagez de réduire la longueur des résidus.</p> <p>Pour le backend <code>hqq</code>, nous recommandons de définir les paramètres <code>axis_key</code> et <code>axis_value</code> sur <code>1</code>.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copié</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-2-7b-chat-hf&quot;</span>)
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-2-7b-chat-hf&quot;</span>, dtype=torch.float16, device_map=<span class="hljs-string">&quot;auto&quot;</span>)
inputs = tokenizer(<span class="hljs-string">&quot;I like rock music because&quot;</span>, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(model.device)
out = model.generate(
**inputs,
do_sample=<span class="hljs-literal">False</span>,
max_new_tokens=<span class="hljs-number">20</span>,
cache_implementation=<span class="hljs-string">&quot;quantized&quot;</span>,
cache_config={
<span class="hljs-string">&quot;nbits&quot;</span>: <span class="hljs-number">4</span>,
<span class="hljs-string">&quot;backend&quot;</span>: <span class="hljs-string">&quot;hqq&quot;</span>,
<span class="hljs-string">&quot;axis_key&quot;</span>: <span class="hljs-number">1</span>,
<span class="hljs-string">&quot;axis_value&quot;</span>: <span class="hljs-number">1</span>
}
)
<span class="hljs-built_in">print</span>(tokenizer.batch_decode(out, skip_special_tokens=<span class="hljs-literal">True</span>)[<span class="hljs-number">0</span>])
I like rock music because it<span class="hljs-string">&#x27;s loud and energetic. It&#x27;</span>s a great way to express myself <span class="hljs-keyword">and</span> rel<!----></pre></div><!----> <p>Pour le backend <code>quanto</code>, nous recommandons de définir les paramètres <code>axis_key</code> et <code>axis_value</code> sur <code>0</code>.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copié</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-2-7b-chat-hf&quot;</span>)
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-2-7b-chat-hf&quot;</span>, dtype=torch.float16, device_map=<span class="hljs-string">&quot;auto&quot;</span>)
inputs = tokenizer(<span class="hljs-string">&quot;I like rock music because&quot;</span>, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(model.device)
out = model.generate(
**inputs,
do_sample=<span class="hljs-literal">False</span>,
max_new_tokens=<span class="hljs-number">20</span>,
cache_implementation=<span class="hljs-string">&quot;quantized&quot;</span>,
cache_config={
<span class="hljs-string">&quot;nbits&quot;</span>: <span class="hljs-number">4</span>,
<span class="hljs-string">&quot;backend&quot;</span>: <span class="hljs-string">&quot;quanto&quot;</span>,
<span class="hljs-string">&quot;axis_key&quot;</span>: <span class="hljs-number">0</span>,
<span class="hljs-string">&quot;axis_value&quot;</span>: <span class="hljs-number">0</span>
}
)
<span class="hljs-built_in">print</span>(tokenizer.batch_decode(out, skip_special_tokens=<span class="hljs-literal">True</span>)[<span class="hljs-number">0</span>])
I like rock music because it<span class="hljs-string">&#x27;s loud and energetic. It&#x27;</span>s a great way to express myself <span class="hljs-keyword">and</span> rel<!----></pre></div><!----> <p>Le backend <code>fp8</code> n’accepte aucun paramètre supplémentaire et lève une erreur si l’un des paramètres group-wise lui est fourni.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copié</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;Qwen/Qwen3-4B-Instruct-2507&quot;</span>)
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;Qwen/Qwen3-4B-Instruct-2507&quot;</span>, dtype=torch.float16, device_map=<span class="hljs-string">&quot;auto&quot;</span>)
inputs = tokenizer(<span class="hljs-string">&quot;I like rock music because&quot;</span>, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(model.device)
out = model.generate(**inputs, do_sample=<span class="hljs-literal">False</span>, max_new_tokens=<span class="hljs-number">20</span>, cache_implementation=<span class="hljs-string">&quot;quantized&quot;</span>, cache_config={<span class="hljs-string">&quot;backend&quot;</span>: <span class="hljs-string">&quot;fp8&quot;</span>})
<span class="hljs-built_in">print</span>(tokenizer.batch_decode(out, skip_special_tokens=<span class="hljs-literal">True</span>)[<span class="hljs-number">0</span>])
I like rock music because it <span class="hljs-keyword">is</span> powerful <span class="hljs-keyword">and</span> emotional. I also like classical music because it <span class="hljs-keyword">is</span> elegant <span class="hljs-keyword">and</span> sophisticated. I enjoy<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="encoder-decoder-cache" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#encoder-decoder-cache"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Cache encodeur-décodeur<!----></span></h2><!--]--><!----> <p><a href="/docs/transformers/main/fr/internal/generation_utils#transformers.EncoderDecoderCache">EncoderDecoderCache</a> est conçu pour les modèles encodeur-décodeur. Il gère à la fois les caches d'auto-attention et d'attention croisée afin d'assurer le stockage et la récupération des paires kv précédentes. Il est possible de définir un type de cache différent pour l'encodeur et le décodeur.</p> <p>Ce type de cache ne nécessite aucune configuration. Il s’agit d’un simple wrapper autour de 2 <a href="/docs/transformers/main/fr/internal/generation_utils#transformers.Cache">Cache</a> tels que décrits ci-dessus, qui seront utilisés indépendamment et directement par le modèle.</p> <!--[1--><h2 class="relative group"><a id="model-specific-caches" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#model-specific-caches"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Caches spécifiques aux modèles<!----></span></h2><!--]--><!----> <p>Certains modèles disposent d'une méthode de stockage des paires kv passées ou des états qui n'est compatible avec aucune autre classe de cache.</p> <p>Les modèles Mamba, tels que <a href="./model_doc/mamba">Mamba</a>, nécessitent un cache spécifique car le modèle ne dispose ni d’un mécanisme d’attention ni d’états kv. Ils ne sont donc pas compatibles avec les classes <a href="/docs/transformers/main/fr/internal/generation_utils#transformers.Cache">Cache</a> ci-dessus.</p> <!--[1--><h2 class="relative group"><a id="iterative-generation" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#iterative-generation"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Génération itérative<!----></span></h2><!--]--><!----> <p>Un cache peut également fonctionner dans des configurations de génération itérative impliquant une interaction aller-retour avec un modèle (chatbots). Tout comme pour la génération standard, la génération itérative avec un cache permet à un modèle de gérer efficacement des conversations en cours sans recalculer l'intégralité du contexte à chaque étape.</p> <p>Pour une génération itérative avec un cache, commencez par initialiser une classe de cache vide, puis vous pouvez y injecter vos nouveaux prompts. Suivez l’historique de la conversation à l’aide d’un <a href="./chat_templating">chat template</a>.</p> <p>L’exemple suivant illustre <a href="https://huggingface.co/meta-llama/Llama-2-7b-chat-hf" rel="nofollow">Llama-2-7b-chat-hf</a>. Si vous utilisez un autre modèle de type chat, <a href="/docs/transformers/main/fr/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template">apply_chat_template()</a> peut traiter les messages différemment. Il peut supprimer des jetons importants selon la façon dont le modèle Jinja est rédigé. Pour les modèles de chat multimodaux, consultez le guide <a href="./tasks/image_text_to_text#iterative-chatting-with-cache">iterative chatting with cache</a> pour savoir comment traiter les images ou l’audio.</p> <p>Par exemple, certains modèles utilisent des jetons spéciaux <code>&lt;think> ... &lt;/think></code> pendant le raisonnement. Ils pourraient être perdus lors de la ré-encodage, provoquant des problèmes d’indexation. Il peut être nécessaire de supprimer ou d’ajuster manuellement les jetons supplémentaires des complétions pour maintenir la stabilité.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copié</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoTokenizer,AutoModelForCausalLM, DynamicCache, StaticCache
model_id = <span class="hljs-string">&quot;meta-llama/Llama-2-7b-chat-hf&quot;</span>
model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.bfloat16, device_map=<span class="hljs-string">&#x27;auto&#x27;</span>)
tokenizer = AutoTokenizer.from_pretrained(model_id)
user_prompts = [<span class="hljs-string">&quot;Hello, what&#x27;s your name?&quot;</span>, <span class="hljs-string">&quot;Btw, yesterday I was on a rock concert.&quot;</span>]
cache = DynamicCache(config=model.config)
messages = []
<span class="hljs-keyword">for</span> prompt <span class="hljs-keyword">in</span> user_prompts:
messages.append({<span class="hljs-string">&quot;role&quot;</span>: <span class="hljs-string">&quot;user&quot;</span>, <span class="hljs-string">&quot;content&quot;</span>: prompt})
inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=<span class="hljs-literal">True</span>, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>, return_dict=<span class="hljs-literal">True</span>).to(model.device)
input_length = inputs[<span class="hljs-string">&quot;input_ids&quot;</span>].shape[<span class="hljs-number">1</span>]
outputs = model.generate(**inputs, do_sample=<span class="hljs-literal">False</span>, max_new_tokens=<span class="hljs-number">256</span>, cache=cache)
completion = tokenizer.decode(outputs[<span class="hljs-number">0</span>, input_length: ], skip_special_tokens=<span class="hljs-literal">True</span>)
messages.append({<span class="hljs-string">&quot;role&quot;</span>: <span class="hljs-string">&quot;assistant&quot;</span>, <span class="hljs-string">&quot;content&quot;</span>: completion})<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="crop-a-cache" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#crop-a-cache"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Recadrer un cache<!----></span></h2><!--]--><!----> <p>Utilisez <a href="/docs/transformers/main/fr/internal/generation_utils#transformers.Cache.crop">crop()</a> pour annuler des jetons depuis un cache, par exemple lorsqu’une continuation candidate est rejetée lors d’une génération itérative. Passez le nombre de jetons à supprimer en tant qu’entier négatif.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copié</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-comment"># Remove the last three tokens from the cache.</span>
cache.crop(-<span class="hljs-number">3</span>)<!----></pre></div><!----> <p>Les couches d’attention à fenêtre glissante et d’attention linéaire abandonnent les états passés au fil de l’exécution, il n’y a donc par défaut aucun état auquel revenir. Appelez <code>activate_past_recording()</code> avant le passage avant pour qu’elles conservent ces états. Sans cela, <code>crop</code> lève une <code>RuntimeError</code> dès qu’une couche à fenêtre glissante remplit sa fenêtre, et immédiatement pour les couches d’attention linéaire.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copié</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-comment"># Enable this before the forward pass if you need to roll back tokens.</span>
cache.activate_past_recording()<!----></pre></div><!----> <p><code>crop(0)</code> ne vide pas le cache. Il ne supprime aucun jeton de la séquence mise en cache et constitue une opération nulle pour les couches d’attention complète. Pour les couches à fenêtre glissante et à attention linéaire, il peut éliminer des informations mises en cache que l’appel suivant du modèle n’utilisera pas. Cela réduit l’utilisation de la mémoire sans annuler les jetons.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copié</div><!----></button><!----></div> <pre class=" "><!----> cached positions
┌───┬───┬───┬───┬───┬───┐
before crop(-3) │<span class="hljs-number"> 0 </span>│<span class="hljs-number"> 1 </span>│<span class="hljs-number"> 2 </span>│<span class="hljs-number"> 3 </span>│<span class="hljs-number"> 4 </span>│<span class="hljs-number"> 5 </span>│
└───┴───┴───┴───┴───┴───┘
╰─────┬─────╯
rolled back
after crop(-3)
┌───┬───┬───┐
full attention │<span class="hljs-number"> 0 </span>│<span class="hljs-number"> 1 </span>│<span class="hljs-number"> 2 </span>│ keeps the whole prefix
└───┴───┴───┘
┌───┐
sliding_window=2 │<span class="hljs-number"> 2 </span>│ keeps sliding_window - 1
└───┘<!----></pre></div><!----> <p>Les deux couches signalent désormais une longueur de séquence de 3, et la génération reprend à partir de la position 3.</p> <p>Passer <code>0</code> ne supprime aucun jeton de la séquence. C’est une opération sans effet pour les couches d’attention complète, mais pour les couches à fenêtre glissante et à attention linéaire, elle supprime toujours les états enregistrés que le prochain passage en avant ne lira pas, ce qui libère de la mémoire sans annuler quoi que ce soit.</p> <!--[1--><h2 class="relative group"><a id="prefill-a-cache-prefix-caching" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#prefill-a-cache-prefix-caching"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Préremplir un cache (cache de préfixe)<!----></span></h2><!--]--><!----> <p>Dans certaines situations, vous pouvez vouloir remplir un <a href="/docs/transformers/main/fr/internal/generation_utils#transformers.Cache">Cache</a> avec des paires kv pour un certain préfixe de prompt et le réutiliser pour générer différentes séquences.</p> <p>L'exemple ci-dessous initialise un <a href="/docs/transformers/main/fr/internal/generation_utils#transformers.StaticCache">StaticCache</a>, puis met en cache un prompt initial. Vous pouvez maintenant générer plusieurs séquences à partir du prompt pré-rempli.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copié</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> copy
<span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AutoTokenizer, DynamicCache, StaticCache
model_id = <span class="hljs-string">&quot;meta-llama/Llama-2-7b-chat-hf&quot;</span>
model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.bfloat16, device_map={<span class="hljs-string">&quot;&quot;</span>: <span class="hljs-number">0</span>})
tokenizer = AutoTokenizer.from_pretrained(model_id)
<span class="hljs-comment"># Init StaticCache with big enough max-length (1024 tokens for the below example)</span>
<span class="hljs-comment"># You can also init a DynamicCache, if that suits you better</span>
prompt_cache = StaticCache(config=model.config, max_cache_len=<span class="hljs-number">1024</span>)
INITIAL_PROMPT = <span class="hljs-string">&quot;You are a helpful assistant. &quot;</span>
inputs_initial_prompt = tokenizer(INITIAL_PROMPT, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(model.device.<span class="hljs-built_in">type</span>)
<span class="hljs-comment"># This is the common prompt cached, we need to run forward without grad to be able to copy</span>
<span class="hljs-keyword">with</span> torch.no_grad():
prompt_cache = model(**inputs_initial_prompt, cache = prompt_cache).cache
prompts = [<span class="hljs-string">&quot;Help me to write a blogpost about travelling.&quot;</span>, <span class="hljs-string">&quot;What is the capital of France?&quot;</span>]
responses = []
<span class="hljs-keyword">for</span> prompt <span class="hljs-keyword">in</span> prompts:
new_inputs = tokenizer(INITIAL_PROMPT + prompt, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(model.device.<span class="hljs-built_in">type</span>)
cache = copy.deepcopy(prompt_cache)
outputs = model.generate(**new_inputs, cache=cache,max_new_tokens=<span class="hljs-number">20</span>)
response = tokenizer.batch_decode(outputs)[<span class="hljs-number">0</span>]
responses.append(response)
<span class="hljs-built_in">print</span>(responses)<!----></pre></div><!----> <a class="!text-gray-400 !no-underline text-sm flex items-center not-prose mt-4" href="https://github.com/huggingface/transformers/blob/main/docs/source/en/kv_cache.md" target="_blank"><svg class="mr-1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M31,16l-7,7l-1.41-1.41L28.17,16l-5.58-5.59L24,9l7,7z"></path><path d="M1,16l7-7l1.41,1.41L3.83,16l5.58,5.59L8,23l-7-7z"></path><path d="M12.419,25.484L17.639,6.552l1.932,0.518L14.351,26.002z"></path></svg><!----> <span><span class="underline">Update</span> on GitHub</span></a><!----> <p></p><!--]--><!----><!--]--><!--]--><!--]--> <!--[-1--><!--]--><!--]-->
<script>
{
__sveltekit_h4kf7b = {
base: "/docs/transformers/main/en",
assets: "/docs/transformers/main/en"
};
const element = document.currentScript.parentElement;
Promise.all([
import("/docs/transformers/main/en/_app/immutable/entry/start.COK5KGrS.js"),
import("/docs/transformers/main/en/_app/immutable/entry/app.CjTXVmse.js")
]).then(([kit, app]) => {
kit.start(app, element, {
node_ids: [0, 4],
data: [null,null],
form: null,
error: null
});
});
}
</script>

Xet Storage Details

Size:
75 kB
·
Xet hash:
50940b232b23e03b9cbac3da66af368d46202d159bf0f8f731f1905cea4b45f5

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.