Buckets:

hf-doc-build/doc / transformers /main /zh /attention_interface.html
mishig's picture
download
raw
72.4 kB
<meta charset="utf-8" /><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;注意力后端&quot;,&quot;local&quot;:&quot;attention-backends&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;设置注意力后端&quot;,&quot;local&quot;:&quot;set-an-attention-backend&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;内核&quot;,&quot;local&quot;:&quot;kernels&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;SDPA 上下文管理器&quot;,&quot;local&quot;:&quot;sdpa-context-manager&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3}],&quot;depth&quot;:2},{&quot;title&quot;:&quot;特定主干的注意力&quot;,&quot;local&quot;:&quot;backbone-specific-attention&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;创建新的注意力函数&quot;,&quot;local&quot;:&quot;create-a-new-attention-function&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;AttentionMaskInterface&quot;,&quot;local&quot;:&quot;attentionmaskinterface&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;构建注意力掩码&quot;,&quot;local&quot;:&quot;build-an-attention-mask&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;传入自定义的 4D 注意力掩码&quot;,&quot;local&quot;:&quot;pass-a-custom-4d-attention-mask&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;双向注意力&quot;,&quot;local&quot;:&quot;bidirectional-attention&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2}],&quot;depth&quot;:1}"/>
<link href="/docs/transformers/main/en/_app/immutable/entry/start.C2wSEYyY.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/B1XvRviU.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/DYxD-VOr.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/entry/app.DvYwi2oY.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/rBgV2CO2.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/Bqqc259Y.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/nodes/0.D0KV6BkP.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/CpYHmYpM.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/nodes/3.BWNxXzG1.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/BznRi4jy.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/De8_sD_o.js" rel="modulepreload">
<!--1jwvttd--><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Attention backends&quot;,&quot;local&quot;:&quot;attention-backends&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Set an attention backend&quot;,&quot;local&quot;:&quot;set-an-attention-backend&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Kernels&quot;,&quot;local&quot;:&quot;kernels&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;SDPA context manager&quot;,&quot;local&quot;:&quot;sdpa-context-manager&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3}],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Backbone-specific attention&quot;,&quot;local&quot;:&quot;backbone-specific-attention&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Create a new attention function&quot;,&quot;local&quot;:&quot;create-a-new-attention-function&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;AttentionMaskInterface&quot;,&quot;local&quot;:&quot;attentionmaskinterface&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Build an attention mask&quot;,&quot;local&quot;:&quot;build-an-attention-mask&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Pass a custom 4D attention mask&quot;,&quot;local&quot;:&quot;pass-a-custom-4d-attention-mask&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Bidirectional attention&quot;,&quot;local&quot;:&quot;bidirectional-attention&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="attention-backends" 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="#attention-backends"><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>所有注意力实现执行的都是相同的计算:每个 token 都会与其他所有 token 进行比较。区别在于<em>如何</em>执行该计算。基础注意力机制的扩展性较差,因为它会在内存中实例化完整的注意力矩阵,从而产生拖慢推理速度的瓶颈。经过优化的实现则通过重新组织数学运算来减少内存访问,从而实现更快、成本更低的推理。</p> <p><a href="/docs/transformers/main/zh/internal/modeling_utils#transformers.AttentionInterface">AttentionInterface</a> 提供了经过优化的注意力实现。它将注意力实现与模型实现解耦,从而简化了对不同函数的实验。借助这一一致的接口,您可以轻松添加新的后端。</p> <table><tbody><tr><th>注意力后端</th><th>描述</th></tr><tr><td><code>"flash_attention_3"</code></td><td>通过进一步重叠操作并更紧密地融合前向和反向传播,提升了 FlashAttention-2 的性能</td></tr><tr><td><code>"flash_attention_2"</code></td><td>将计算划分为更小的块,并使用快速的片上内存</td></tr><tr><td><code>"flex_attention"</code></td><td>一个用于指定自定义注意力模式(稀疏、块局部、滑动窗口)的框架,无需手动编写底层内核</td></tr><tr><td><code>"sdpa"</code></td><td>内置的 <a href="https://docs.pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html">缩放点积注意力</a> PyTorch 实现</td></tr><tr><td><code>"paged|flash_attention_3"</code></td><td>FlashAttention-3 的分页版本</td></tr><tr><td><code>"paged|flash_attention_2"</code></td><td>FlashAttention-2 的分页版本</td></tr><tr><td><code>"paged|sdpa"</code></td><td>SDPA 的分页版本</td></tr><tr><td><code>"paged|eager"</code></td><td>Eager 的分页版本</td></tr></tbody></table> <!--[1--><h2 class="relative group"><a id="set-an-attention-backend" 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="#set-an-attention-backend"><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/main_classes/model#transformers.PreTrainedModel.from_pretrained">from_pretrained()</a> 中的 <code>attn_implementation</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> AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained(
<span class="hljs-string">&quot;meta-llama/Llama-3.2-1B&quot;</span>, attn_implementation=<span class="hljs-string">&quot;flash_attention_2&quot;</span>
)<!----></pre></div><!----> <p>使用 <a href="/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.set_attn_implementation">set_attn_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 "><!---->model.set_attn_implementation(<span class="hljs-string">&quot;sdpa&quot;</span>)<!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="kernels" 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="#kernels"><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></h3><!--]--><!----> <p>在运行时,使用 <a href="https://huggingface.co/docs/kernels/index" rel="nofollow">Kernels</a> 库直接从 <a href="https://huggingface.co/models?other=kernels" rel="nofollow">Hub</a> 下载并加载已编译的计算内核。这可以避免因 PyTorch 或 CUDA 版本不匹配而导致的打包问题。</p> <p>Kernels 在检测到后会自动注册到 <a href="/docs/transformers/main/zh/internal/modeling_utils#transformers.AttentionInterface">AttentionInterface</a>。您无需显式安装 FlashAttention 包。按名称请求 FlashAttention 时,也会回退到 Hub kernel,参见 <a href="./kernel_doc/loading_kernels#flashattention-fallback">FlashAttention fallback</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> AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained(
<span class="hljs-string">&quot;meta-llama/Llama-3.2-1B&quot;</span>, attn_implementation=<span class="hljs-string">&quot;kernels-community/flash-attn2&quot;</span>
)<!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="sdpa-context-manager" 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="#sdpa-context-manager"><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><!---->SDPA 上下文管理器<!----></span></h3><!--]--><!----> <p>PyTorch 的缩放点积注意力(SDPA)会自动为 CUDA 后端选择最快的注意力函数。对于其他后端,它默认使用 PyTorch C++ 实现。</p> <p>使用 <a href="https://pytorch.org/docs/stable/generated/torch.nn.attention.sdpa_kernel.html" rel="nofollow">torch.nn.attention.sdpa_kernel</a> 上下文管理器强制 SDPA 使用特定的实现。</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> torch.nn.attention <span class="hljs-keyword">import</span> SDPBackend, sdpa_kernel
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained(
<span class="hljs-string">&quot;meta-llama/Llama-3.2-1B&quot;</span>, attn_implementation=<span class="hljs-string">&quot;sdpa&quot;</span>
)
<span class="hljs-keyword">with</span> sdpa_kernel(SDPBackend.FLASH_ATTENTION):
outputs = model.generate(**inputs)<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="backbone-specific-attention" 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="#backbone-specific-attention"><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>多模态模型为每种模态使用不同的骨干网络。通过为每个骨干网络分配特定的注意力函数来优化性能。例如,某些视觉骨干网络在 fp32 下表现更好,而 FlashAttention 并不支持 fp32。</p> <p>使用字典将视觉主干映射到不同的注意力函数,同时文本主干继续使用 FlashAttention。注意力实现中的键必须与子配置名称匹配。</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">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForImageTextToText
attention_implementation_per_backbone = {<span class="hljs-string">&quot;vision_config&quot;</span>: <span class="hljs-string">&quot;sdpa&quot;</span>, <span class="hljs-string">&quot;text_config&quot;</span>: <span class="hljs-string">&quot;flash_attention_2&quot;</span>}
<span class="hljs-keyword">for</span> key <span class="hljs-keyword">in</span> attention_implementation_per_backbone:
<span class="hljs-keyword">assert</span> key <span class="hljs-keyword">in</span> model.config.sub_configs, <span class="hljs-string">f&quot;Invalid key in `attention_implementation`&quot;</span>
model = AutoModelForImageTextToText.from_pretrained(
<span class="hljs-string">&quot;facebook/chameleon-7b&quot;</span>, attn_implementation=attention_implementation_per_backbone
)<!----></pre></div><!----> <p>从字典中省略某些骨干网络,即可使用默认的注意力函数(SDPA)。</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 "><!---->model = AutoModelForImageTextToText.from_pretrained(
<span class="hljs-string">&quot;facebook/chameleon-7b&quot;</span>, attn_implementation={<span class="hljs-string">&quot;text_config&quot;</span>: <span class="hljs-string">&quot;flash_attention_2&quot;</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 "><!---->model = AutoModelForImageTextToText.from_pretrained(
<span class="hljs-string">&quot;facebook/chameleon-7b&quot;</span>, attn_implementation=<span class="hljs-string">&quot;eager&quot;</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 "><!---->model = AutoModelForImageTextToText.from_pretrained(
<span class="hljs-string">&quot;facebook/chameleon-7b&quot;</span>, attn_implementation={<span class="hljs-string">&quot;&quot;</span>: <span class="hljs-string">&quot;eager&quot;</span>}
)<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="create-a-new-attention-function" 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="#create-a-new-attention-function"><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/modeling_utils#transformers.AttentionInterface.register">AttentionInterface.register()</a>。模型通过 <code>attn_implementation</code> 参数使用这些函数。</p> <blockquote class="warning"><p>在注册自定义注意力函数时,请同时注册一个匹配的注意力掩码函数。如果自定义的 <code>attn_implementation</code> 名称未在 <a href="/docs/transformers/main/zh/internal/modeling_utils#transformers.AttentionMaskInterface">AttentionMaskInterface</a> 中注册,Transformers 将跳过掩码创建,并向注意力层传递 <code>attention_mask=None</code>。此时,您的注意力函数必须自行处理因果、填充、打包或滑动窗口等约束,否则这些约束可能会被静默忽略。</p></blockquote> <p>本示例通过自定义注意力函数,为每一层打印一条语句。它通过注册 <code>masking_utils.sdpa_mask</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-python "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AttentionInterface, AttentionMaskInterface
<span class="hljs-keyword">from</span> transformers.integrations.sdpa_attention <span class="hljs-keyword">import</span> sdpa_attention_forward
<span class="hljs-keyword">from</span> transformers.masking_utils <span class="hljs-keyword">import</span> sdpa_mask
<span class="hljs-keyword">def</span> <span class="hljs-title function_">my_new_sdpa</span>(<span class="hljs-params">*args, **kwargs</span>):
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;I just entered the attention computation&quot;</span>)
<span class="hljs-keyword">return</span> sdpa_attention_forward(*args, **kwargs)
AttentionInterface.register(<span class="hljs-string">&quot;my_new_sdpa&quot;</span>, my_new_sdpa)
AttentionMaskInterface.register(<span class="hljs-string">&quot;my_new_sdpa&quot;</span>, sdpa_mask) <span class="hljs-comment"># must have the same name as the registered attention function</span>
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-3.2-1B&quot;</span>, attn_implementation=<span class="hljs-string">&quot;my_new_sdpa&quot;</span>)
model(torch.ones(<span class="hljs-number">1</span>, <span class="hljs-number">5</span>, dtype=<span class="hljs-built_in">int</span>))<!----></pre></div><!----> <p>您还可以向注意力函数添加新的参数。支持 <a href="/docs/transformers/main/zh/internal/modeling_utils#transformers.AttentionInterface">AttentionInterface</a> 的模型会将 kwargs 传递到注意力层和注意力函数中。请在模型的前向函数中通过 kwargs 传递参数。自定义注意力函数必须遵循此签名和返回格式。</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-python "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AttentionInterface, AttentionMaskInterface
<span class="hljs-keyword">from</span> transformers.integrations.sdpa_attention <span class="hljs-keyword">import</span> sdpa_attention_forward
<span class="hljs-keyword">from</span> transformers.masking_utils <span class="hljs-keyword">import</span> sdpa_mask
<span class="hljs-keyword">def</span> <span class="hljs-title function_">custom_attention</span>(<span class="hljs-params">
module: torch.nn.Module, <span class="hljs-comment"># required arg</span>
query: torch.Tensor, <span class="hljs-comment"># required arg</span>
key: torch.Tensor, <span class="hljs-comment"># required arg</span>
value: torch.Tensor, <span class="hljs-comment"># required arg</span>
attention_mask: <span class="hljs-type">Optional</span>[torch.Tensor], <span class="hljs-comment"># required arg</span>
a_new_kwargs = <span class="hljs-literal">None</span>, <span class="hljs-comment"># You can now add as many kwargs as you need</span>
another_new_kwargs = <span class="hljs-literal">None</span>, <span class="hljs-comment"># You can now add as many kwargs as you need</span>
**kwargs, <span class="hljs-comment"># You need to accept **kwargs as models will pass other args</span>
</span>) -&gt; <span class="hljs-built_in">tuple</span>[torch.Tensor, <span class="hljs-type">Optional</span>[torch.Tensor]]
... <span class="hljs-comment"># do your magic!</span>
<span class="hljs-keyword">return</span> attn_output, attn_weights <span class="hljs-comment"># attn_weights are optional here</span>
AttentionInterface.register(<span class="hljs-string">&quot;custom&quot;</span>, custom_attention)
AttentionMaskInterface.register(<span class="hljs-string">&quot;custom&quot;</span>, sdpa_mask) <span class="hljs-comment"># to leave the existing mask untouched</span>
model = AutoModelForCausalLM.from_pretrained(model_id, attn_implementation=<span class="hljs-string">&quot;custom&quot;</span>)
model(torch.ones(<span class="hljs-number">1</span>, <span class="hljs-number">5</span>, dtype=<span class="hljs-built_in">int</span>), a_new_kwargs=..., another_new_kwargs=...)<!----></pre></div><!----> <p>检查模型的 <a href="https://github.com/huggingface/transformers/tree/main/src/transformers/models" rel="nofollow">modeling code</a>,以确认它向注意力函数传递了哪些参数和 kwargs。</p> <!--[1--><h2 class="relative group"><a id="attentionmaskinterface" 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="#attentionmaskinterface"><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><!---->AttentionMaskInterface<!----></span></h2><!--]--><!----> <p><a href="/docs/transformers/main/zh/internal/modeling_utils#transformers.AttentionMaskInterface">AttentionMaskInterface</a> 是一个注册表,<a href="#build-an-attention-mask"><code>create_*_mask</code></a> 函数会查询该注册表,将掩码转换为当前激活的注意力后端所期望的格式。FlexAttention 需要 <a href="https://docs.pytorch.org/docs/stable/nn.attention.flex_attention.html#torch.nn.attention.flex_attention.BlockMask" rel="nofollow">BlockMask</a>,SDPA 需要 4D 张量,而 FlashAttention 需要基础的 2D padding 掩码。您可以使用 <a href="/docs/transformers/main/zh/internal/modeling_utils#transformers.AttentionInterface.register">AttentionMaskInterface.register()</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-python "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AttentionMaskInterface
<span class="hljs-keyword">from</span> transformers.masking_utils <span class="hljs-keyword">import</span> sdpa_mask
<span class="hljs-keyword">def</span> <span class="hljs-title function_">my_new_sdpa_mask</span>(<span class="hljs-params">*args, **kwargs</span>):
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;I just entered the attention mask computation&quot;</span>)
<span class="hljs-keyword">return</span> sdpa_mask(*args, **kwargs)
AttentionMaskInterface.register(<span class="hljs-string">&quot;my_new_sdpa_mask&quot;</span>, my_new_sdpa_mask)<!----></pre></div><!----> <p>如果当前 <code>attn_implementation</code> 没有注册对应的格式化器,则会跳过掩码创建,并将 <code>attention_mask=None</code> 传递给注意力层。</p> <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-python "><!----><span class="hljs-keyword">def</span> <span class="hljs-title function_">custom_attention_mask</span>(<span class="hljs-params">
batch_size: <span class="hljs-built_in">int</span>, <span class="hljs-comment"># required arg</span>
q_length: <span class="hljs-built_in">int</span>, <span class="hljs-comment"># required arg</span>
kv_length: <span class="hljs-built_in">int</span>, <span class="hljs-comment"># required arg</span>
q_offset: <span class="hljs-built_in">int</span> = <span class="hljs-number">0</span>, <span class="hljs-comment"># required arg</span>
kv_offset: <span class="hljs-built_in">int</span> = <span class="hljs-number">0</span>, <span class="hljs-comment"># required arg</span>
mask_function: <span class="hljs-type">Callable</span> = causal_mask_function, <span class="hljs-comment"># required arg</span>
attention_mask: <span class="hljs-type">Optional</span>[torch.Tensor] = <span class="hljs-literal">None</span>, <span class="hljs-comment"># required arg</span>
**kwargs, <span class="hljs-comment"># a few additional args may be passed as kwargs, especially the model&#x27;s config is always passed</span>
</span>) -&gt; <span class="hljs-type">Optional</span>[torch.Tensor]:<!----></pre></div><!----> <p><code>mask_function</code> 参数是一个 <code>Callable</code>,其作用类似于 PyTorch 的 <a href="https://pytorch.org/blog/flexattention/" rel="nofollow">mask_mod</a> 函数。它接收 4 个索引 <code>(batch_idx, head_idx, q_idx, kv_idx)</code>,并返回一个布尔值,指示该位置是否参与注意力计算。这与 <a href="#build-an-attention-mask">构建注意力掩码</a> 中 <code>or_mask_function</code> 和 <code>and_mask_function</code> 所使用的基本形式相同。</p> <blockquote class="tip"><p>如果 <code>mask_function</code> 无法创建掩码,请使用此 <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/integrations/executorch.py" rel="nofollow">变通方法</a> 来处理 torch.export。</p></blockquote> <!--[1--><h2 class="relative group"><a id="build-an-attention-mask" 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="#build-an-attention-mask"><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="https://github.com/huggingface/transformers/blob/main/src/transformers/masking_utils.py#L894" rel="nofollow">transformers.masking_utils</a> 中的 <code>create_*_mask</code> 函数来构建注意力掩码。每个函数都会从模型配置中读取当前生效的注意力后端,在 <a href="/docs/transformers/main/zh/internal/modeling_utils#transformers.AttentionMaskInterface">AttentionMaskInterface</a> 中查找该后端的掩码格式化器,并返回该后端所期望的格式。您无需自行对掩码进行取反、扩展或类型转换。</p> <p>选择与注意力模式相匹配的函数。</p> <table><thead><tr><th>函数</th><th>用例</th></tr></thead><tbody><tr><td><code>create_causal_mask</code></td><td>decoder-only 模型中,每个 token 仅关注自身及之前的 token</td></tr><tr><td><code>create_bidirectional_mask</code></td><td>编码器模型,或从解码器到编码器状态的交叉注意力</td></tr><tr><td><code>create_sliding_window_causal_mask</code></td><td>具有滑动窗口注意力模式的解码器模型</td></tr><tr><td><code>create_chunked_causal_mask</code></td><td>将序列分块为固定大小块的解码器模型</td></tr><tr><td><code>create_bidirectional_sliding_window_mask</code></td><td>采用滑动窗口注意力模式的编码器模型</td></tr></tbody></table> <blockquote class="warning"><p>旧版可调用掩码辅助函数 - <code>get_extended_attention_mask</code>、<code>create_extended_attention_mask_for_decoder</code>、<code>invert_attention_mask</code> - 会发出弃用警告,并将在未来版本中移除。请改用 <code>create_*_mask</code> 函数。</p></blockquote> <div class="flex space-x-2 items-center my-1.5 mr-8 h-7 !pl-0 -mx-3 md:mx-0"><!--[--><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd border-gray-800 bg-black dark:bg-gray-700 text-white">因果注意力</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">编码器自注意力</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">交叉注意力</div><!--]--></div> <div class="language-select"><div><p>在解码器的前向传播中调用 <code>create_causal_mask</code>。传入 config、输入嵌入、用户提供的 2D <code>attention_mask</code> 以及 cache。该函数利用嵌入来读取 batch size、query 长度、dtype 和 device,并利用 cache 来计算 key 长度。</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">from</span> transformers.masking_utils <span class="hljs-keyword">import</span> create_causal_mask
attention_mask = create_causal_mask(
config=<span class="hljs-variable language_">self</span>.config,
inputs_embeds=inputs_embeds,
attention_mask=attention_mask,
cache=cache,
)<!----></pre></div><!----><!----></div><!----> <div hidden=""><p>调用 <code>create_bidirectional_mask</code> 用于编码器的自注意力。由于编码器不使用缓存,因此省略 <code>cache</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">from</span> transformers.masking_utils <span class="hljs-keyword">import</span> create_bidirectional_mask
attention_mask = create_bidirectional_mask(
config=<span class="hljs-variable language_">self</span>.config,
inputs_embeds=embedding_output,
attention_mask=attention_mask,
)<!----></pre></div><!----><!----></div><!----> <div hidden=""><p>对于交叉注意力,请将编码器状态作为 <code>encoder_hidden_states</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 "><!---->encoder_attention_mask = create_bidirectional_mask(
config=<span class="hljs-variable language_">self</span>.config,
inputs_embeds=embedding_output,
attention_mask=encoder_attention_mask,
encoder_hidden_states=encoder_hidden_states,
)<!----></pre></div><!----><!----></div><!----><!----></div><!----> <p>使用 <code>or_mask_function</code> 和 <code>and_mask_function</code> 参数,可以在基础掩码之上添加额外的约束。使用 <code>or_mask_function</code> 允许额外的位置参与注意力计算,使用 <code>and_mask_function</code> 则进一步限制基础模式。两者均遵循 <a href="#attentionmaskinterface">AttentionMaskInterface</a> 中描述的 4 索引 <code>mask_function</code> 签名。它们接收 <code>(batch_idx, head_idx, q_idx, kv_idx)</code> 作为参数,并返回布尔值。</p> <blockquote class="warning"><p><code>or_mask_function</code> 和 <code>and_mask_function</code> 可以表达任意注意力模式,但它们的执行速度比内置模式慢,并且与 ExecuTorch 不兼容。在较小的模型(约 200M 参数)上,这种开销最为明显,因为掩码创建在正向传播时间中占据更大的比例。只有在标准的 <code>create_*_mask</code> 函数无法表达你的需求时,才应使用它们。</p></blockquote> <p>例如,可以在因果掩码上叠加一个在所有位置都返回 <code>True</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="language-py "><!---->mask_kwargs = {
<span class="hljs-string">&quot;config&quot;</span>: <span class="hljs-variable language_">self</span>.config,
<span class="hljs-string">&quot;inputs_embeds&quot;</span>: inputs_embeds,
<span class="hljs-string">&quot;attention_mask&quot;</span>: attention_mask,
<span class="hljs-string">&quot;cache&quot;</span>: cache,
<span class="hljs-string">&quot;position_ids&quot;</span>: position_ids,
<span class="hljs-string">&quot;or_mask_function&quot;</span>: <span class="hljs-keyword">lambda</span> *args: torch.tensor(<span class="hljs-literal">True</span>, dtype=torch.<span class="hljs-built_in">bool</span>),
}
attention_mask = create_causal_mask(**mask_kwargs)<!----></pre></div><!----> <p>在生成过程中,<a href="/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationMixin.generate">generate()</a> 会通过 <code>create_masks_for_generate</code> 构建掩码,该函数会根据模型配置分发到相应的 <code>create_*_mask</code>。在模型类中重写此方法,即可为生成过程接入自定义的掩码策略。</p> <!--[1--><h2 class="relative group"><a id="pass-a-custom-4d-attention-mask" 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="#pass-a-custom-4d-attention-mask"><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><!---->传入自定义的 4D 注意力掩码<!----></span></h2><!--]--><!----> <p>当 <code>create_*_mask</code> 函数无法表达所需的注意力模式时,请传入自定义的 4D 掩码。4D 掩码的形状为 <code>(batch_size, 1, query_length, kv_length)</code>,其中 <code>1</code> 表示将相同的掩码广播到所有注意力头。Transformers 会检测并直接使用该掩码,跳过 <code>create_*_mask</code>。</p> <p>4D 掩码使用两种取值约定之一。</p> <table><thead><tr><th>dtype</th><th>attend</th><th>屏蔽</th></tr></thead><tbody><tr><td>boolean</td><td><code>True</code></td><td><code>False</code></td></tr><tr><td>float</td><td><code>0.0</code></td><td><code>-inf</code></td></tr></tbody></table> <p>float 约定在 softmax 之前将掩码加到注意力分数上。分数加上 <code>0.0</code> 保持不变,因此该位置会被计入。分数加上 <code>-inf</code> 在 softmax 之后变为零,因此该位置会被排除。</p> <blockquote class="important"><p>所接受的约定取决于注意力后端。<code>sdpa</code> 接受布尔型或浮点型掩码。<code>eager</code> 会将掩码加到分数上,因此仅接受浮点型掩码。<code>flash_attention_2</code> 和 <code>flex_attention</code> 使用各自的格式(一个 2D 填充掩码和一个 <a href="https://docs.pytorch.org/docs/stable/nn.attention.flex_attention.html#torch.nn.attention.flex_attention.BlockMask" rel="nofollow">BlockMask</a>),不接受原始的 4D 掩码。</p></blockquote> <p>一个常见的错误是在浮点 4D 掩码中复用 2D 填充掩码的 <code>1</code>/<code>0</code> 约定。由于掩码会被加到分数上,<code>0.0</code> 会保留该位置,而 <code>1.0</code> 只会引入一个微小的偏差。</p> <p>下面的示例对比了一个错误的掩码和一个正确的掩码。两者都从相同的 <code>1</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> AutoModelForCausalLM, AutoTokenizer
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;TinyLlama/TinyLlama-1.1B-Chat-v1.0&quot;</span>, attn_implementation=<span class="hljs-string">&quot;sdpa&quot;</span>)
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;TinyLlama/TinyLlama-1.1B-Chat-v1.0&quot;</span>)
input_ids = tokenizer(<span class="hljs-string">&quot;my favorite condiment on a&quot;</span>, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).input_ids
seq_len = input_ids.shape[<span class="hljs-number">1</span>]
<span class="hljs-comment"># 1 attends, 0 masks</span>
causal = torch.tril(torch.ones(seq_len, seq_len))
<span class="hljs-comment"># wrong: 1.0/0.0 floats are added to the scores, so 0.0 keeps a token and 1.0 barely changes it</span>
wrong_mask = causal[<span class="hljs-literal">None</span>, <span class="hljs-literal">None</span>]
<span class="hljs-comment"># correct: 0.0 attends, -inf masks</span>
correct_mask = torch.where(causal.<span class="hljs-built_in">bool</span>(), <span class="hljs-number">0.0</span>, <span class="hljs-built_in">float</span>(<span class="hljs-string">&quot;-inf&quot;</span>))[<span class="hljs-literal">None</span>, <span class="hljs-literal">None</span>]<!----></pre></div><!----> <p>错误的掩码会保留所有位置,因为 <code>0.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-text "><!----> wrong_mask correct_mask
(1 attends, 0 masks) (0 attends, -inf masks)
k0 k1 k2 k3 k4 k0 k1 k2 k3 k4
q0 1 0 0 0 0 q0 0 -inf -inf -inf -inf
q1 1 1 0 0 0 q1 0 0 -inf -inf -inf
q2 1 1 1 0 0 q2 0 0 0 -inf -inf
q3 1 1 1 1 0 q3 0 0 0 0 -inf
q4 1 1 1 1 1 q4 0 0 0 0 0<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="bidirectional-attention" 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="#bidirectional-attention"><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>Decoder-only 模型默认使用因果(单向)注意力,即每个 token 仅关注自身及其之前的 token。将 <code>is_causal=False</code> 设置为 False 可切换为双向注意力,使每个 token 都能关注所有其他 token。这允许您将 decoder-only 模型用作文本编码器,例如用于生成嵌入。</p> <blockquote class="note"><p>此功能仅适用于因果(解码器)模型。它不会将编码器模型转换为解码器模型。</p></blockquote> <p>在模型配置中设置 <code>is_causal=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">from</span> transformers <span class="hljs-keyword">import</span> AutoModel, AutoConfig
config = AutoConfig.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-3.2-1B&quot;</span>)
config.is_causal = <span class="hljs-literal">False</span>
model = AutoModel.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-3.2-1B&quot;</span>, config=config)
<span class="hljs-comment"># all forward passes now use bidirectional attention</span>
outputs = model(**inputs)<!----></pre></div><!----> <p>在 forward 调用中传入 <code>is_causal</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">from</span> transformers <span class="hljs-keyword">import</span> AutoModel
model = AutoModel.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-3.2-1B&quot;</span>)
<span class="hljs-comment"># run with bidirectional attention</span>
outputs = model(**inputs, is_causal=<span class="hljs-literal">False</span>)
<span class="hljs-comment"># run with default causal attention</span>
outputs = model(**inputs)<!----></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/attention_interface.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_mcl5gy = {
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.C2wSEYyY.js"),
import("/docs/transformers/main/en/_app/immutable/entry/app.DvYwi2oY.js")
]).then(([kit, app]) => {
kit.start(app, element, {
node_ids: [0, 3],
data: [null,null],
form: null,
error: null
});
});
}
</script>

Xet Storage Details

Size:
72.4 kB
·
Xet hash:
8bec9bab2c1d3e4857bc4f2def573ed1f43c25ae40dc1444137aaf7c5015d6a0

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