Buckets:
| <meta charset="utf-8" /><meta name="hf:doc:metadata" content="{"title":"Backend perhatian","local":"attention-backends","sections":[{"title":"Atur backend perhatian","local":"set-an-attention-backend","sections":[{"title":"Kernels","local":"kernels","sections":[],"depth":3},{"title":"Manajer konteks SDPA","local":"sdpa-context-manager","sections":[],"depth":3}],"depth":2},{"title":"Perhatian spesifik backbone","local":"backbone-specific-attention","sections":[],"depth":2},{"title":"Buat fungsi perhatian baru","local":"create-a-new-attention-function","sections":[],"depth":2},{"title":"AttentionMaskInterface","local":"attentionmaskinterface","sections":[],"depth":2},{"title":"Membangun attention mask","local":"build-an-attention-mask","sections":[],"depth":2},{"title":"Lewati mask perhatian 4D kustom","local":"pass-a-custom-4d-attention-mask","sections":[],"depth":2},{"title":"Perhatian bidireksional","local":"bidirectional-attention","sections":[],"depth":2}],"depth":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="{"title":"Attention backends","local":"attention-backends","sections":[{"title":"Set an attention backend","local":"set-an-attention-backend","sections":[{"title":"Kernels","local":"kernels","sections":[],"depth":3},{"title":"SDPA context manager","local":"sdpa-context-manager","sections":[],"depth":3}],"depth":2},{"title":"Backbone-specific attention","local":"backbone-specific-attention","sections":[],"depth":2},{"title":"Create a new attention function","local":"create-a-new-attention-function","sections":[],"depth":2},{"title":"AttentionMaskInterface","local":"attentionmaskinterface","sections":[],"depth":2},{"title":"Build an attention mask","local":"build-an-attention-mask","sections":[],"depth":2},{"title":"Pass a custom 4D attention mask","local":"pass-a-custom-4d-attention-mask","sections":[],"depth":2},{"title":"Bidirectional attention","local":"bidirectional-attention","sections":[],"depth":2}],"depth":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><!---->Backend perhatian<!----></span></h1><!--]--><!----> <p>Semua implementasi perhatian melakukan komputasi yang sama. Setiap token dibandingkan dengan setiap token lainnya. Perbedaannya terletak pada <em>bagaimana</em> komputasi tersebut dilakukan. Perhatian dasar memiliki skalabilitas yang buruk karena mematerialisasi matriks perhatian penuh di memori, menciptakan hambatan yang memperlambat inferensi. Implementasi yang dioptimalkan menyusun ulang matematisnya untuk mengurangi lalu lintas memori demi inferensi yang lebih cepat dan lebih terjangkau.</p> <p><a href="/docs/transformers/main/id/internal/modeling_utils#transformers.AttentionInterface">AttentionInterface</a> menyediakan implementasi perhatian yang dioptimalkan. Antarmuka ini memisahkan implementasi perhatian dari implementasi model untuk menyederhanakan eksperimen dengan fungsi yang berbeda. Tambahkan backend baru dengan mudah melalui antarmuka yang konsisten ini.</p> <table><tbody><tr><th>Backend perhatian</th><th>Deskripsi</th></tr><tr><td><code>"flash_attention_3"</code></td><td>meningkatkan FlashAttention-2 dengan juga menumpuk operasi dan menggabungkan jalur maju dan mundur secara lebih ketat</td></tr><tr><td><code>"flash_attention_2"</code></td><td>tiles komputasi menjadi blok-blok yang lebih kecil dan menggunakan memori on-chip yang cepat</td></tr><tr><td><code>"flex_attention"</code></td><td>framework untuk menentukan pola perhatian kustom (sparse, block-local, sliding window) tanpa menulis kernel tingkat rendah secara manual</td></tr><tr><td><code>"sdpa"</code></td><td>implementasi PyTorch bawaan untuk <a href="https://docs.pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html">scaled dot product attention</a></td></tr><tr><td><code>"paged|flash_attention_3"</code></td><td>Versi berhalaman dari FlashAttention-3</td></tr><tr><td><code>"paged|flash_attention_2"</code></td><td>Versi berhalaman dari FlashAttention-2</td></tr><tr><td><code>"paged|sdpa"</code></td><td>Versi berhalaman dari SDPA</td></tr><tr><td><code>"paged|eager"</code></td><td>Versi paged dari 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><!---->Atur backend perhatian<!----></span></h2><!--]--><!----> <p>Gunakan argumen <code>attn_implementation</code> di <a href="/docs/transformers/main/id/main_classes/model#transformers.PreTrainedModel.from_pretrained">from_pretrained()</a> untuk membuat model dengan fungsi perhatian tertentu.</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> Disalin</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">"meta-llama/Llama-3.2-1B"</span>, attn_implementation=<span class="hljs-string">"flash_attention_2"</span> | |
| )<!----></pre></div><!----> <p>Beralih antara backend perhatian pada waktu runtime tanpa memuat ulang model menggunakan <a href="/docs/transformers/main/id/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> Disalin</div><!----></button><!----></div> <pre class="language-py "><!---->model.set_attn_implementation(<span class="hljs-string">"sdpa"</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><!---->Kernels<!----></span></h3><!--]--><!----> <p>Unduh dan muat kernel komputasi yang telah dikompilasi langsung dari <a href="https://huggingface.co/models?other=kernels" rel="nofollow">Hub</a> saat runtime dengan pustaka <a href="https://huggingface.co/docs/kernels/index" rel="nofollow">Kernels</a>. Hal ini menghindari masalah pengemasan akibat ketidakcocokan versi PyTorch atau CUDA.</p> <p>Kernels secara otomatis terdaftar ke <a href="/docs/transformers/main/id/internal/modeling_utils#transformers.AttentionInterface">AttentionInterface</a> saat terdeteksi. Anda tidak perlu menginstal paket FlashAttention secara eksplisit. Meminta FlashAttention berdasarkan nama juga akan kembali ke kernel Hub, lihat <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> Disalin</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">"meta-llama/Llama-3.2-1B"</span>, attn_implementation=<span class="hljs-string">"kernels-community/flash-attn2"</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><!---->Manajer konteks SDPA<!----></span></h3><!--]--><!----> <p>Scaled dot product attention (SDPA) dari PyTorch secara otomatis memilih fungsi attention tercepat untuk backend CUDA. Untuk backend lainnya, default-nya adalah implementasi C++ PyTorch.</p> <p>Paksa SDPA untuk menggunakan implementasi tertentu dengan context manager <a href="https://pytorch.org/docs/stable/generated/torch.nn.attention.sdpa_kernel.html" rel="nofollow">torch.nn.attention.sdpa_kernel</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> Disalin</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">"meta-llama/Llama-3.2-1B"</span>, attn_implementation=<span class="hljs-string">"sdpa"</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><!---->Perhatian spesifik backbone<!----></span></h2><!--]--><!----> <p>Model multimodal menggunakan backbone yang berbeda untuk setiap modalitas. Optimalkan kinerja dengan menugaskan fungsi perhatian tertentu ke setiap backbone. Beberapa backbone visi, misalnya, memberikan kinerja yang lebih baik dalam fp32, yang tidak didukung oleh FlashAttention.</p> <p>Petakan tulang punggung visi ke fungsi perhatian yang berbeda menggunakan dict, sementara tulang punggung teks tetap menggunakan FlashAttention. Kunci dalam implementasi perhatian harus cocok dengan nama sub-konfigurasi.</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> Disalin</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">"vision_config"</span>: <span class="hljs-string">"sdpa"</span>, <span class="hljs-string">"text_config"</span>: <span class="hljs-string">"flash_attention_2"</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"Invalid key in `attention_implementation`"</span> | |
| model = AutoModelForImageTextToText.from_pretrained( | |
| <span class="hljs-string">"facebook/chameleon-7b"</span>, attn_implementation=attention_implementation_per_backbone | |
| )<!----></pre></div><!----> <p>Hapus beberapa backbone dari dict untuk menggunakan fungsi perhatian default (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> Disalin</div><!----></button><!----></div> <pre class="language-py "><!---->model = AutoModelForImageTextToText.from_pretrained( | |
| <span class="hljs-string">"facebook/chameleon-7b"</span>, attn_implementation={<span class="hljs-string">"text_config"</span>: <span class="hljs-string">"flash_attention_2"</span>} | |
| )<!----></pre></div><!----> <p>Atur fungsi perhatian yang sama untuk semua backbone dengan satu string.</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> Disalin</div><!----></button><!----></div> <pre class="language-py "><!---->model = AutoModelForImageTextToText.from_pretrained( | |
| <span class="hljs-string">"facebook/chameleon-7b"</span>, attn_implementation=<span class="hljs-string">"eager"</span> | |
| )<!----></pre></div><!----> <p>Atur fungsi perhatian secara global dengan kunci kosong.</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> Disalin</div><!----></button><!----></div> <pre class="language-py "><!---->model = AutoModelForImageTextToText.from_pretrained( | |
| <span class="hljs-string">"facebook/chameleon-7b"</span>, attn_implementation={<span class="hljs-string">""</span>: <span class="hljs-string">"eager"</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><!---->Buat fungsi perhatian baru<!----></span></h2><!--]--><!----> <p>Sesuaikan atau buat fungsi perhatian baru dengan menambahkannya ke registri perhatian menggunakan <a href="/docs/transformers/main/id/internal/modeling_utils#transformers.AttentionInterface.register">AttentionInterface.register()</a>. Model menggunakan fungsi-fungsi ini melalui argumen <code>attn_implementation</code>.</p> <blockquote class="warning"><p>Daftarkan fungsi mask perhatian yang sesuai saat Anda mendaftarkan fungsi perhatian kustom. Jika nama <code>attn_implementation</code> kustom tidak terdaftar di <a href="/docs/transformers/main/id/internal/modeling_utils#transformers.AttentionMaskInterface">AttentionMaskInterface</a>, Transformers akan melewati pembuatan mask dan meneruskan <code>attention_mask=None</code> ke lapisan perhatian. Fungsi perhatian Anda harus menangani kendala kausal, padding, packing, atau sliding-window sendiri, atau kendala tersebut dapat diabaikan secara diam-diam.</p></blockquote> <p>Contoh ini menyesuaikan fungsi perhatian untuk mencetak pernyataan untuk setiap lapisan. Mask dipertahankan dalam implementasi asli dengan mendaftarkan <code>masking_utils.sdpa_mask</code> sebagai fungsi mask perhatian.</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> Disalin</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">"I just entered the attention computation"</span>) | |
| <span class="hljs-keyword">return</span> sdpa_attention_forward(*args, **kwargs) | |
| AttentionInterface.register(<span class="hljs-string">"my_new_sdpa"</span>, my_new_sdpa) | |
| AttentionMaskInterface.register(<span class="hljs-string">"my_new_sdpa"</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">"meta-llama/Llama-3.2-1B"</span>, attn_implementation=<span class="hljs-string">"my_new_sdpa"</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>Anda juga dapat menambahkan argumen baru ke fungsi perhatian. Model yang mendukung <a href="/docs/transformers/main/id/internal/modeling_utils#transformers.AttentionInterface">AttentionInterface</a> meneruskan kwargs ke lapisan perhatian dan fungsi perhatian. Lewatkan argumen sebagai kwargs dalam fungsi forward model. Fungsi perhatian kustom harus mengikuti tanda tangan dan format pengembalian ini.</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> Disalin</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>) -> <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">"custom"</span>, custom_attention) | |
| AttentionMaskInterface.register(<span class="hljs-string">"custom"</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">"custom"</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>Periksa <a href="https://github.com/huggingface/transformers/tree/main/src/transformers/models" rel="nofollow">kode pemodelan</a> model untuk mengonfirmasi argumen dan kwargs apa yang dikirimkannya ke fungsi perhatian.</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/id/internal/modeling_utils#transformers.AttentionMaskInterface">AttentionMaskInterface</a> adalah registry yang dirujuk oleh fungsi <a href="#build-an-attention-mask"><code>create_*_mask</code></a> untuk mengonversi mask menjadi format yang diharapkan oleh backend attention yang aktif. FlexAttention membutuhkan <a href="https://docs.pytorch.org/docs/stable/nn.attention.flex_attention.html#torch.nn.attention.flex_attention.BlockMask" rel="nofollow">BlockMask</a>, SDPA membutuhkan tensor 4D, dan FlashAttention membutuhkan mask padding dasar 2D. Daftarkan backend kustom, atau timpa formatter untuk backend yang sudah ada, dengan <a href="/docs/transformers/main/id/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> Disalin</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">"I just entered the attention mask computation"</span>) | |
| <span class="hljs-keyword">return</span> sdpa_mask(*args, **kwargs) | |
| AttentionMaskInterface.register(<span class="hljs-string">"my_new_sdpa_mask"</span>, my_new_sdpa_mask)<!----></pre></div><!----> <p>Tanpa formatter yang terdaftar untuk <code>attn_implementation</code> yang aktif, pembuatan mask dilewati dan <code>attention_mask=None</code> diteruskan ke lapisan attention.</p> <p>Fungsi yang terdaftar harus cocok dengan tanda tangan ini.</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> Disalin</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's config is always passed</span> | |
| </span>) -> <span class="hljs-type">Optional</span>[torch.Tensor]:<!----></pre></div><!----> <p>Argumen <code>mask_function</code> adalah <code>Callable</code> yang meniru fungsi <a href="https://pytorch.org/blog/flexattention/" rel="nofollow">mask_mod</a> PyTorch. Argumen ini menerima 4 indeks <code>(batch_idx, head_idx, q_idx, kv_idx)</code> dan mengembalikan nilai boolean yang menunjukkan apakah posisi tersebut berkontribusi pada komputasi perhatian. Ini adalah bentuk primitif yang sama yang digunakan oleh <code>or_mask_function</code> dan <code>and_mask_function</code> di <a href="#build-an-attention-mask">Membangun mask perhatian</a>.</p> <blockquote class="tip"><p>Gunakan <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/integrations/executorch.py" rel="nofollow">workaround</a> ini untuk torch.export jika <code>mask_function</code> gagal membuat mask.</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><!---->Membangun attention mask<!----></span></h2><!--]--><!----> <p>Bangun attention mask dengan fungsi <code>create_*_mask</code> di <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/masking_utils.py#L894" rel="nofollow">transformers.masking_utils</a>. Setiap fungsi membaca backend attention aktif dari konfigurasi model, mencari formatter mask backend di <a href="/docs/transformers/main/id/internal/modeling_utils#transformers.AttentionMaskInterface">AttentionMaskInterface</a>, dan mengembalikan format yang diharapkan oleh backend tersebut. Anda tidak perlu membalik, memperluas, atau meng-cast mask secara manual.</p> <p>Pilih fungsi yang sesuai dengan pola perhatian.</p> <table><thead><tr><th>function</th><th>kasus penggunaan</th></tr></thead><tbody><tr><td><code>create_causal_mask</code></td><td>model decoder-only di mana setiap token memperhatikan dirinya sendiri dan token-token sebelumnya</td></tr><tr><td><code>create_bidirectional_mask</code></td><td>model encoder, atau cross-attention dari decoder ke state encoder</td></tr><tr><td><code>create_sliding_window_causal_mask</code></td><td>model decoder dengan pola perhatian jendela geser</td></tr><tr><td><code>create_chunked_causal_mask</code></td><td>model decoder yang memecah urutan menjadi blok berukuran tetap</td></tr><tr><td><code>create_bidirectional_sliding_window_mask</code></td><td>model encoder dengan pola perhatian jendela geser</td></tr></tbody></table> <blockquote class="warning"><p>Helper mask callable lama - <code>get_extended_attention_mask</code>, <code>create_extended_attention_mask_for_decoder</code>, <code>invert_attention_mask</code> - mengeluarkan peringatan deprekasi dan akan dihapus pada rilis mendatang. Gunakan fungsi <code>create_*_mask</code> sebagai gantinya.</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">causal attention</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">self-attention encoder</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">cross-attention</div><!--]--></div> <div class="language-select"><div><p>Panggil <code>create_causal_mask</code> di dalam jalur forward decoder. Sampaikan config, input embeddings, <code>attention_mask</code> 2D yang disediakan pengguna, dan cache. Fungsi ini menggunakan embeddings untuk membaca batch size, panjang query, dtype, dan device, serta menggunakan cache untuk menghitung panjang 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> Disalin</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>Panggil <code>create_bidirectional_mask</code> untuk self-attention encoder. Buang <code>cache</code> karena encoder tidak melakukan caching.</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> Disalin</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>Untuk cross-attention, berikan state encoder sebagai <code>encoder_hidden_states</code> agar mask menggunakan panjang key dan value encoder, bukan panjang query decoder.</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> Disalin</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>Tambahkan kendala tambahan di atas mask dasar dengan argumen <code>or_mask_function</code> dan <code>and_mask_function</code>. Gunakan <code>or_mask_function</code> untuk memungkinkan posisi tambahan melakukan attend, dan <code>and_mask_function</code> untuk membatasi pola dasar lebih lanjut. Keduanya mengikuti tanda tangan <code>mask_function</code> 4-indeks yang dijelaskan dalam <a href="#attentionmaskinterface">AttentionMaskInterface</a>. Mereka menerima <code>(batch_idx, head_idx, q_idx, kv_idx)</code> dan mengembalikan nilai boolean.</p> <blockquote class="warning"><p><code>or_mask_function</code> dan <code>and_mask_function</code> dapat mengekspresikan pola perhatian apa pun, tetapi lebih lambat daripada pola bawaan dan tidak kompatibel dengan ExecuTorch. Overhead paling terasa pada model yang lebih kecil (~200M parameter), di mana pembuatan mask mengambil porsi yang lebih besar dari waktu forward-pass. Gunakan fungsi-fungsi ini hanya ketika fungsi <code>create_*_mask</code> standar tidak dapat mengekspresikan apa yang Anda butuhkan.</p></blockquote> <p>Sebagai contoh, tambahkan fungsi yang mengembalikan <code>True</code> di mana saja pada mask kausal untuk mengubahnya menjadi mask bidireksional penuh. Gabungan dengan pola kausal memungkinkan setiap token memperhatikan setiap token lainnya.</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> Disalin</div><!----></button><!----></div> <pre class="language-py "><!---->mask_kwargs = { | |
| <span class="hljs-string">"config"</span>: <span class="hljs-variable language_">self</span>.config, | |
| <span class="hljs-string">"inputs_embeds"</span>: inputs_embeds, | |
| <span class="hljs-string">"attention_mask"</span>: attention_mask, | |
| <span class="hljs-string">"cache"</span>: cache, | |
| <span class="hljs-string">"position_ids"</span>: position_ids, | |
| <span class="hljs-string">"or_mask_function"</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>Saat generasi, <a href="/docs/transformers/main/id/main_classes/text_generation#transformers.GenerationMixin.generate">generate()</a> membangun mask melalui <code>create_masks_for_generate</code>, yang meneruskan ke <code>create_*_mask</code> yang tepat berdasarkan konfigurasi model. Timpa metode ini pada kelas model untuk menerapkan strategi masking kustom untuk generasi.</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><!---->Lewati mask perhatian 4D kustom<!----></span></h2><!--]--><!----> <p>Lewati mask 4D Anda sendiri ketika Anda membutuhkan pola perhatian yang tidak dapat diekspresikan oleh fungsi <code>create_*_mask</code>. Mask 4D memiliki bentuk <code>(batch_size, 1, query_length, kv_length)</code>, di mana <code>1</code> melakukan broadcast mask yang sama di setiap kepala perhatian. Transformers mendeteksi dan menggunakan mask apa adanya, melewati <code>create_*_mask</code>.</p> <p>Mask 4D menggunakan salah satu dari dua konvensi nilai.</p> <table><thead><tr><th>dtype</th><th>hadiri</th><th>mask out</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>Konvensi float menambahkan mask ke skor perhatian sebelum softmax. Skor ditambah <code>0.0</code> tetap tidak berubah, sehingga posisi tersebut berkontribusi. Skor ditambah <code>-inf</code> menjadi nol setelah softmax, sehingga posisi tersebut dikecualikan.</p> <blockquote class="important"><p>Konvensi yang diterima bergantung pada backend perhatian. <code>sdpa</code> menerima mask boolean atau float. <code>eager</code> menambahkan mask ke skor, sehingga hanya menerima mask float. <code>flash_attention_2</code> dan <code>flex_attention</code> menggunakan format mereka sendiri (mask padding 2D dan <a href="https://docs.pytorch.org/docs/stable/nn.attention.flex_attention.html#torch.nn.attention.flex_attention.BlockMask" rel="nofollow">BlockMask</a>) dan tidak menerima mask 4D mentah.</p></blockquote> <p>Kesalahan umum adalah menggunakan kembali konvensi <code>1</code>/<code>0</code> dari mask padding 2D pada mask 4D float. Karena mask ditambahkan ke skor, <code>0.0</code> mempertahankan posisi dan <code>1.0</code> hanya menambahkan bias kecil.</p> <p>Contoh di bawah ini membandingkan mask yang salah dengan yang benar. Keduanya dimulai dari pola kausal <code>1</code>/<code>0</code> yang sama.</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> Disalin</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">"TinyLlama/TinyLlama-1.1B-Chat-v1.0"</span>, attn_implementation=<span class="hljs-string">"sdpa"</span>) | |
| tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">"TinyLlama/TinyLlama-1.1B-Chat-v1.0"</span>) | |
| input_ids = tokenizer(<span class="hljs-string">"my favorite condiment on a"</span>, return_tensors=<span class="hljs-string">"pt"</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">"-inf"</span>))[<span class="hljs-literal">None</span>, <span class="hljs-literal">None</span>]<!----></pre></div><!----> <p>Mask yang salah mempertahankan semua posisi karena <code>0.0</code> adalah nilai yang digunakan untuk masking, sehingga tidak pernah mengecualikan apa pun.</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> Disalin</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><!---->Perhatian bidireksional<!----></span></h2><!--]--><!----> <p>Model decoder-only menggunakan perhatian kausal (unidireksional) secara default, di mana setiap token hanya memperhatikan dirinya sendiri dan token-token sebelumnya. Atur <code>is_causal=False</code> untuk beralih ke perhatian bidireksional, di mana setiap token memperhatikan semua token lainnya. Hal ini memungkinkan Anda menggunakan model decoder-only sebagai encoder teks, misalnya untuk menghasilkan embedding.</p> <blockquote class="note"><p>Ini hanya berfungsi untuk model kausal (decoder). Hal ini tidak mengubah model encoder menjadi model decoder.</p></blockquote> <p>Setel <code>is_causal=False</code> dalam konfigurasi model untuk menjadikan perhatian bidireksional sebagai default untuk setiap forward pass.</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> Disalin</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">"meta-llama/Llama-3.2-1B"</span>) | |
| config.is_causal = <span class="hljs-literal">False</span> | |
| model = AutoModel.from_pretrained(<span class="hljs-string">"meta-llama/Llama-3.2-1B"</span>, config=config) | |
| <span class="hljs-comment"># all forward passes now use bidirectional attention</span> | |
| outputs = model(**inputs)<!----></pre></div><!----> <p>Lewati <code>is_causal</code> dalam panggilan forward alih-alih melalui konfigurasi model untuk beralih antara perhatian kausal dan bidireksional tanpa memuat model dua kali. Argumen kwarg ini secara sementara menimpa konfigurasi dan dipulihkan setelah panggilan selesai.</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> Disalin</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">"meta-llama/Llama-3.2-1B"</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:
- 73.5 kB
- Xet hash:
- 94f188e48f90a1f62b64a2df6c76b6005eb24788ba39e4f9d25e3ba1141c7bdc
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.