Buckets:

hf-doc-build/doc / transformers /main /zh /kv_cache.html
mishig's picture
download
raw
71.3 kB
<meta charset="utf-8" /><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;缓存策略&quot;,&quot;local&quot;:&quot;cache-strategies&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;默认缓存&quot;,&quot;local&quot;:&quot;default-cache&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;固定大小缓存&quot;,&quot;local&quot;:&quot;fixed-size-cache&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;将生成张量保留在 CPU 上&quot;,&quot;local&quot;:&quot;keep-generation-tensors-on-cpu&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;缓存卸载&quot;,&quot;local&quot;:&quot;cache-offloading&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;量化缓存&quot;,&quot;local&quot;:&quot;quantized-cache&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;编码器-解码器缓存&quot;,&quot;local&quot;:&quot;encoder-decoder-cache&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;特定模型的缓存&quot;,&quot;local&quot;:&quot;model-specific-caches&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;迭代生成&quot;,&quot;local&quot;:&quot;iterative-generation&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;裁剪缓存&quot;,&quot;local&quot;:&quot;crop-a-cache&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;预填充缓存(前缀缓存)&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><!---->缓存策略<!----></span></h1><!--]--><!----> <p>键值(KV)向量用于计算注意力分数。对于自回归模型,由于模型每次只预测一个 token,因此 KV 分数是<em>每次</em>都计算的。每个预测都依赖于之前的 token,这意味着模型每次都会执行相同的计算。</p> <p>KV <em>缓存</em>会存储这些计算结果,以便在不重新计算的情况下重复使用。高效的缓存对于优化模型性能至关重要,因为它能减少计算时间并提高响应速度。有关缓存工作原理的详细说明,请参阅<a href="./cache_explanation">缓存</a>文档。</p> <p>Transformers 提供了多个 <a href="/docs/transformers/main/zh/internal/generation_utils#transformers.Cache">Cache</a> 类,它们实现了不同的缓存机制。其中一些 <a href="/docs/transformers/main/zh/internal/generation_utils#transformers.Cache">Cache</a> 类针对节省内存进行了优化,而另一些则旨在最大化生成速度。请参阅下表以比较不同的缓存类型,并据此为您的使用场景选择最合适的缓存。</p> <table><thead><tr><th>缓存类型</th><th>支持滑动层</th><th>支持卸载</th><th>支持 torch.compile()</th><th>预期内存使用量</th></tr></thead><tbody><tr><td>动态缓存</td><td>是的</td><td>是的</td><td>No</td><td>中等</td></tr><tr><td>静态缓存</td><td>是的</td><td>是的</td><td>是的</td><td>高</td></tr><tr><td>量化缓存</td><td>No</td><td>否</td><td>No</td><td>低</td></tr></tbody></table> <p>本指南将为您介绍不同的 <a href="/docs/transformers/main/zh/internal/generation_utils#transformers.Cache">Cache</a> 类,并展示如何在生成过程中使用它们。</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><!---->默认缓存<!----></span></h2><!--]--><!----> <p><a href="/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache">DynamicCache</a> 是所有模型的默认缓存类。它允许缓存大小动态增长,以便随着生成过程的推进,存储越来越多的键和值。</p> <p>请注意,对于使用滑动窗口注意力(Mistral、Gemma2 等)或分块注意力(Llama4)的模型,当使用这些注意力类型的层达到其最大尺寸(即滑动窗口或分块大小)时,缓存将停止增长。</p> <p>通过在 <a href="/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationMixin.generate">generate()</a> 中设置 <code>use_cache=False</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> 已复制</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>Cache 类也可以先进行初始化,然后再调用并将其传递给模型的 <a href="/docs/transformers/main/zh/internal/generation_utils#transformers.generation.GenerateDecoderOnlyOutput.cache">cache</a> 参数。这在需要更细粒度的控制或更高级的用法(例如上下文缓存)时非常有用。</p> <p>在大多数情况下,在 <a href="/docs/transformers/main/zh/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> 已复制</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><!---->固定大小缓存<!----></span></h2><!--]--><!----> <p>默认的 <a href="/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache">DynamicCache</a> 会阻止你利用大多数即时(JIT)优化,因为缓存大小不是固定的。JIT 优化允许你以内存占用为代价来最小化延迟。以下所有缓存类型均兼容 <a href="./perf_torch_compile">torch.compile</a> 等 JIT 优化,以加速生成过程。</p> <p>固定大小的缓存(<a href="/docs/transformers/main/zh/internal/generation_utils#transformers.StaticCache">StaticCache</a>)会为 kv 对预先分配一个特定的最大缓存大小。你可以生成多达最大缓存大小的 token,而无需对其进行修改。然而,由于 key/value 状态具有固定(通常较大)的大小,在生成过程中,许多 token 实际上会被屏蔽,因为它们不应参与注意力计算。因此,这种技巧可以轻松地 <code>compile</code> 解码阶段,但会在注意力计算中造成 token 的浪费。凡事皆有取舍:如果你生成的多个序列长度大致相同,这种方案效果会非常好;但如果你有一个非常大的序列,随后只有较短的序列(因为固定缓存大小会很大,短序列会浪费大量空间),则可能不是最优选择。如果你打算使用它,请务必了解其影响!</p> <p>对于 <a href="/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache">DynamicCache</a>,请注意,对于使用滑动窗口注意力(Mistral、Gemma2 等)或分块注意力(Llama4)的模型,即使指定的最大长度更大,在使用这些类型注意力的层上,缓存的大小也永远不会超过滑动窗口/分块大小。</p> <p>您可以通过在 <a href="/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationMixin.generate">generate()</a> 中配置 <code>cache_implementation="static"</code> 来启用 <a href="/docs/transformers/main/zh/internal/generation_utils#transformers.StaticCache">StaticCache</a>。这还将自动开启贪心、采样和 <a href="./assisted_decoding">assisted</a> 解码策略的解码阶段 <code>compilation</code>。</p> <p>对于辅助解码,静态缓存的支持仅限于少数几种层类型,因为被拒绝的草稿 token 必须就地回滚,而这只有在缓存中没有状态被驱逐的情况下才可行。例如,滑动窗口层仅在已处理的 token 数量小于窗口大小时可用,否则较早的 token 会开始从缓存中被驱逐,并且由于其大小必须是静态的,我们无法像对带有滑动窗口层的 <a href="/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache">DynamicCache</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> 已复制</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><!---->将生成张量保留在 CPU 上<!----></span></h2><!--]--><!----> <p>像 Neuron 和 TPU 这样的编译器后端会将模型追踪为固定的计算图。生成循环会维护一些张量(输出序列、<code>attention_mask</code>、<code>position_ids</code>),这些张量在每一步都会增加一个 token。每当这些张量在加速器上的形状发生变化时,编译器就会重新追踪计算图,从而拖慢生成速度。</p> <p><a href="/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationMixin.generate">generate()</a> 仅在每次 <code>forward</code> 调用前,将 <code>forward</code> 所消费的张量移动到模型所在的设备上。输出会被移回,以匹配输入所在的设备。请将输入保持在 CPU 上,以避免循环中不断增长的张量管理开销落在加速器上。编译后的图保持稳定,并且由于输出跟随输入的设备,生成的输出也会保留在 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> 已复制</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><!---->缓存卸载<!----></span></h2><!--]--><!----> <p>KV 缓存可能会占用大量内存,并成为长上下文生成的<a href="https://hf.co/blog/llama31#inference-memory-requirements" rel="nofollow">瓶颈</a>。内存高效的缓存方案旨在以速度为代价来降低内存占用。对于大型语言模型(LLM)以及硬件内存受限的场景,这一点尤为重要。</p> <p>通过将缓存卸载来节省 GPU 显存:除一个模型层外,其余层的 KV 缓存会被移至 CPU。在模型对各个层执行 <code>forward</code> 迭代期间,GPU 上仅保留当前层的缓存。系统会异步预取下一层的缓存,并在注意力计算完成后,将当前层的缓存送回 CPU。</p> <p>如果您的 GPU 较小且遇到内存不足(OOM)错误,可以考虑使用 offloading。</p> <blockquote class="warning"><p>与完全在设备端使用缓存相比,你可能会注意到生成吞吐量略有下降,具体取决于你的模型和生成配置(上下文大小、生成的 token 数量、beam 数量等)。这是因为在设备间来回移动 key/value 状态需要额外的计算开销。</p></blockquote> <p>Offloading 功能同时支持 <a href="/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache">DynamicCache</a> 和 <a href="/docs/transformers/main/zh/internal/generation_utils#transformers.StaticCache">StaticCache</a>。您可以通过在 <a href="/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationConfig">GenerationConfig</a> 或 <a href="/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationMixin.generate">generate()</a> 中配置 <code>cache_implementation="offloaded"</code>(动态版本)或 <code>cache_implementation="offloaded_static"</code>(静态版本)来启用该功能。
此外,您也可以使用 <code>offloading=True</code> 选项自行实例化 <a href="/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache">DynamicCache</a> 或 <a href="/docs/transformers/main/zh/internal/generation_utils#transformers.StaticCache">StaticCache</a>,并将该缓存传入 <code>generate</code> 或模型的 <code>forward</code>(例如,对于动态缓存,使用 <code>cache=DynamicCache(config=model.config, offloading=True)</code>)。</p> <p>请注意,上述提到的两个 <a href="/docs/transformers/main/zh/internal/generation_utils#transformers.Cache">Cache</a> 类在直接实例化时还有一个额外选项 <code>offload_only_non_sliding</code>。
该额外参数用于决定使用滑动窗口/分块注意力(如果存在)的层是否也会被卸载。由于这些层通常本身就很短,为避免卸载带来的速度损失,最好不卸载它们。默认情况下,<a href="/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache">DynamicCache</a> 的该选项为 <code>False</code>,而 <a href="/docs/transformers/main/zh/internal/generation_utils#transformers.StaticCache">StaticCache</a> 的该选项为 <code>True</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> 已复制</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>下面的示例展示了当内存不足时,如何回退到已卸载的缓存:</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> 已复制</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><!---->量化缓存<!----></span></h2><!--]--><!----> <p><a href="/docs/transformers/main/zh/internal/generation_utils#transformers.QuantizedCache">QuantizedCache</a> 通过将 KV 值量化为较低精度来降低内存需求。<a href="/docs/transformers/main/zh/internal/generation_utils#transformers.QuantizedCache">QuantizedCache</a> 目前支持三种量化后端:</p> <ul><li><code>hqq</code> 支持 int1、int2、int3、int4 和 int8 数据类型。</li> <li><code>quanto</code> 支持 int2 和 int4 数据类型。这是默认的量化后端。</li> <li><code>fp8</code> 以 8 位浮点格式(<code>float8_e4m3fn</code>)存储 KV 值。它无需额外依赖,并且采用按张量(per-tensor)而非按组(per-group)的量化方式,因此会拒绝 <code>nbits</code>、<code>axis_key</code>、<code>axis_value</code>、<code>q_group_size</code> 和 <code>residual_length</code>。</li></ul> <blockquote class="warning"><p>在上下文长度较短且 GPU 内存足以在不启用缓存量化的情况下进行生成的情况下,对缓存进行量化可能会损害延迟。请尝试在内存效率和延迟之间找到平衡。</p></blockquote> <p>通过配置 <a href="/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationConfig">GenerationConfig</a> 中的 <code>cache_implementation="quantized"</code> 来启用 <a href="/docs/transformers/main/zh/internal/generation_utils#transformers.QuantizedCache">QuantizedCache</a>。量化后端以及任何额外的量化参数都在传递给 <a href="/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationMixin.generate">generate()</a> 的 <code>cache_config</code> 字典中指定。除非遇到内存不足的情况,否则这些额外参数应使用默认值。如果出现内存不足,请考虑减小残差长度。</p> <p>对于 <code>hqq</code> 后端,我们建议将 <code>axis_key</code> 和 <code>axis_value</code> 参数设置为 <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> 已复制</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>对于 <code>quanto</code> 后端,我们建议将 <code>axis_key</code> 和 <code>axis_value</code> 参数设置为 <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> 已复制</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><code>fp8</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> 已复制</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><!---->编码器-解码器缓存<!----></span></h2><!--]--><!----> <p><a href="/docs/transformers/main/zh/internal/generation_utils#transformers.EncoderDecoderCache">EncoderDecoderCache</a> 专为编码器-解码器模型设计。它同时管理自注意力(self-attention)和交叉注意力(cross-attention)缓存,以确保之前 kv 对的存储与检索。可以分别为编码器和解码器设置不同的缓存类型。</p> <p>此缓存类型无需任何配置。它是对上述两个 <a href="/docs/transformers/main/zh/internal/generation_utils#transformers.Cache">Cache</a> 的简单封装,将由模型直接独立使用。</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><!---->特定模型的缓存<!----></span></h2><!--]--><!----> <p>某些模型具有独特的过去 kv 对或状态的存储方式,与其他任何缓存类都不兼容。</p> <p>像 <a href="./model_doc/mamba">Mamba</a> 这样的 Mamba 模型需要特定的缓存,因为该模型没有注意力机制或 kv 状态。因此,它们与上述 <a href="/docs/transformers/main/zh/internal/generation_utils#transformers.Cache">Cache</a> 类不兼容。</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><!---->迭代生成<!----></span></h2><!--]--><!----> <p>缓存同样适用于存在与模型来回交互的迭代生成场景(例如聊天机器人)。与常规生成类似,使用缓存的迭代生成使模型能够高效地处理持续进行的对话,而无需在每一步都重新计算整个上下文。</p> <p>对于使用缓存的迭代生成,首先初始化一个空的缓存类,然后即可输入新的提示词。使用 <a href="./chat_templating">chat template</a> 来跟踪对话历史。</p> <p>以下示例演示了 <a href="https://huggingface.co/meta-llama/Llama-2-7b-chat-hf" rel="nofollow">Llama-2-7b-chat-hf</a>。如果您使用的是其他聊天式模型,<a href="/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template">apply_chat_template()</a> 可能会以不同的方式处理消息。具体取决于 Jinja 模板的编写方式,它可能会截断重要的 token。对于多模态聊天模型,请参阅 <a href="./tasks/image_text_to_text#iterative-chatting-with-cache">iterative chatting with cache</a> 指南,了解如何处理图像或音频。</p> <p>例如,某些模型在推理过程中会使用特殊的 <code>&lt;think> ... &lt;/think></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> 已复制</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><!---->裁剪缓存<!----></span></h2><!--]--><!----> <p>使用 <a href="/docs/transformers/main/zh/internal/generation_utils#transformers.Cache.crop">crop()</a> 从缓存中回滚 token,例如在迭代生成过程中候选续写被拒绝时。将需要移除的 token 数量作为负整数传入。</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> 已复制</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>滑动窗口和线性注意力层在计算过程中会丢弃过去的状态,因此默认情况下没有可供回滚的状态。请在前向传播之前调用 <code>activate_past_recording()</code>,使这些层保留这些状态。否则,一旦滑动窗口层填满其窗口,<code>crop</code> 就会抛出 <code>RuntimeError</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> 已复制</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> 不会清除缓存。它不会从缓存序列中移除任何 token,对于全注意力层而言是一个空操作。对于滑动窗口和线性注意力层,它可以丢弃下一次模型调用不会使用的缓存信息。这在不回滚 token 的情况下降低了内存占用。</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> 已复制</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>现在,这两个层都报告序列长度为 3,生成从位置 3 恢复。</p> <p>传入 <code>0</code> 不会从序列中移除任何 token。对于全注意力层,这是一个无操作;但对于滑动窗口和线性注意力层,它仍会丢弃下一次前向传播不会读取的已记录状态,从而在不回滚任何内容的情况下释放内存。</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><!---->预填充缓存(前缀缓存)<!----></span></h2><!--]--><!----> <p>在某些情况下,您可能希望使用特定前缀提示的 kv 对来填充 <a href="/docs/transformers/main/zh/internal/generation_utils#transformers.Cache">Cache</a>,并复用它来生成不同的序列。</p> <p>下面的示例初始化了一个 <a href="/docs/transformers/main/zh/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> 已复制</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:
71.3 kB
·
Xet hash:
4dcb4e4beb761f24d94df8c2bcf704fa7f47c16c63860cc83141a403bf76e398

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