Buckets:

hf-doc-build/doc / transformers /main /ru /attention_interface.html
mishig's picture
download
raw
81.9 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>Все реализации внимания выполняют одинаковые вычисления. Каждый токен сравнивается с каждым другим токеном. Разница заключается в <em>том, как</em> выполняются вычисления. Базовое внимание масштабируется плохо, поскольку оно материализует полную матрицу внимания в памяти, создавая узкие места, которые замедляют инференс. Оптимизированные реализации перестраивают математические операции, чтобы снизить нагрузку на память и обеспечить более быстрый и доступный инференс.</p> <p><a href="/docs/transformers/main/ru/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>framework for specifying custom attention patterns (sparse, block-local, sliding window) without writing low-level kernels by hand</td></tr><tr><td><code>"sdpa"</code></td><td>встроенная в PyTorch реализация <a href="https://docs.pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html">масштабированного внимания на основе скалярного произведения</a></td></tr><tr><td><code>"paged|flash_attention_3"</code></td><td>Paged-версия 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>Используйте аргумент <code>attn_implementation</code> в <a href="/docs/transformers/main/ru/main_classes/model#transformers.PreTrainedModel.from_pretrained">from_pretrained()</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;flash_attention_2&quot;</span>
)<!----></pre></div><!----> <p>Переключайте бэкенды внимания во время выполнения без перезагрузки модели с помощью <a href="/docs/transformers/main/ru/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/models?other=kernels" rel="nofollow">Hub</a> во время выполнения с помощью библиотеки <a href="https://huggingface.co/docs/kernels/index" rel="nofollow">Kernels</a>. Это позволяет избежать проблем с упаковкой, вызванных несовпадением версий PyTorch или CUDA.</p> <p>Ядра автоматически регистрируются в <a href="/docs/transformers/main/ru/internal/modeling_utils#transformers.AttentionInterface">AttentionInterface</a> при обнаружении. Вам не нужно явно устанавливать пакет FlashAttention. Запрос FlashAttention по имени также приводит к использованию ядра из Hub, см. <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>Масштабированное внимание на основе скалярного произведения (SDPA) в PyTorch автоматически выбирает наиболее быструю функцию внимания для бэкендов CUDA. Для остальных бэкендов по умолчанию используется реализация на C++ в PyTorch.</p> <p>Принудительно заставить SDPA использовать конкретную реализацию с помощью контекстного менеджера <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> Скопировано</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>Мультимодальные модели используют различные базовые архитектуры (backbones) для каждого модальности. Оптимизируйте производительность, назначая специфические функции внимания для каждой базовой архитектуры. Например, некоторые визуальные базовые архитектуры лучше работают в fp32, что не поддерживается FlashAttention.</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>Опустите определённые backbones из dict, чтобы использовать функцию внимания по умолчанию (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/ru/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/ru/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/ru/internal/modeling_utils#transformers.AttentionInterface">AttentionInterface</a>, передают kwargs в слои внимания и функцию внимания. Передавайте аргументы как kwargs в forward-функции модели. Пользовательские функции внимания должны соответствовать этой сигнатуре и формату возврата.</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">код моделирования</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/ru/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 — тензор размерности 4, а FlashAttention — базовую 2D-маску отсечения. Зарегистрируйте собственный бэкенд или переопределите форматтер для существующего с помощью <a href="/docs/transformers/main/ru/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>, имитирующий функции <a href="https://pytorch.org/blog/flexattention/" rel="nofollow">mask_mod</a> из PyTorch. Он принимает 4 индекса <code>(batch_idx, head_idx, q_idx, kv_idx)</code> и возвращает булево значение, указывающее, участвует ли данная позиция в вычислении внимания. Это тот же примитивный формат, который используется в <code>or_mask_function</code> и <code>and_mask_function</code> в разделе <a href="#build-an-attention-mask">Build an attention mask</a>.</p> <blockquote class="tip"><p>Используйте этот <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/integrations/executorch.py" rel="nofollow">обходной путь</a> для torch.export, если <code>mask_function</code> не может создать маску.</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>Создавайте маски внимания с помощью функций <code>create_*_mask</code> в модуле <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/masking_utils.py#L894" rel="nofollow">transformers.masking_utils</a>. Каждая функция считывает активный бэкенд внимания из конфигурации модели, находит форматтер маски для этого бэкенда в <a href="/docs/transformers/main/ru/internal/modeling_utils#transformers.AttentionMaskInterface">AttentionMaskInterface</a> и возвращает ожидаемый этим бэкендом формат. Вам не нужно самостоятельно инвертировать, расширять или приводить маску к нужному типу.</p> <p>Выберите функцию, соответствующую шаблону внимания.</p> <table><thead><tr><th>function</th><th>кейс использования</th></tr></thead><tbody><tr><td><code>create_causal_mask</code></td><td>модели только с декодером, в которых каждый токен обращается к себе и к предыдущим токенам</td></tr><tr><td><code>create_bidirectional_mask</code></td><td>модели-энкодеры, или кросс-внимание от декодера к состояниям энкодера</td></tr><tr><td><code>create_sliding_window_causal_mask</code></td><td>decoder-модели с паттерном внимания со скользящим окном</td></tr><tr><td><code>create_chunked_causal_mask</code></td><td>decoder-модели, которые разбивают последовательность на блоки фиксированного размера</td></tr><tr><td><code>create_bidirectional_sliding_window_mask</code></td><td>encoder-модели с паттерном внимания со скользящим окном</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">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 в энкодере</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>Вызывайте <code>create_causal_mask</code> внутри прямого прохода декодера. Передайте конфигурацию, входные эмбеддинги, пользовательскую 2D-маску <code>attention_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-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>, чтобы дополнительно ограничить базовый паттерн. Оба следуют сигнатуре <code>mask_function</code> с четырьмя индексами, описанной в <a href="#attentionmaskinterface">AttentionMaskInterface</a>. Они принимают <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> везде, чтобы превратить её в полностью двунаправленную. Объединение с каузальным паттерном позволяет каждому токену обращать внимание на любой другой токен.</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/ru/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>Передавайте собственную 4D-маску, когда вам нужен паттерн внимания, который не могут выразить функции <code>create_*_mask</code>. Форма 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> принимает булеву или float-маску. <code>eager</code> прибавляет маску к скорингу, поэтому принимает только float-маску. <code>flash_attention_2</code> и <code>flex_attention</code> используют собственные форматы (2D-маску padding и <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>Частая ошибка — использовать соглашение <code>1</code>/<code>0</code> из 2D-маски отсечки в float-маске 4D. Поскольку маска прибавляется к оценкам, <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>Модели только с декодером по умолчанию используют каузальное (однонаправленное) внимание, при котором каждый токен обращается только к себе и предыдущим токенам. Установите <code>is_causal=False</code>, чтобы переключиться на двунаправленное внимание, при котором каждый токен обращается ко всем остальным токенам. Это позволяет использовать модели только с декодером в качестве текстовых энкодеров, например, для генерации эмбеддингов.</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>Передавайте <code>is_causal</code> в вызове forward вместо конфигурации модели, чтобы переключаться между каузальным и двунаправленным вниманием без повторной загрузки модели. Этот аргумент временно переопределяет конфигурацию и восстанавливается после вызова.</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:
81.9 kB
·
Xet hash:
9b02cf48bdcc3557f44c147c8bc15d3db112d560545eec263f20c883dc8db5c6

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