Buckets:

hf-doc-build/doc / diffusers /main /ru /optimization /attention_backends.html
mishig's picture
download
raw
41.4 kB
<meta charset="utf-8" /><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Бэкенды внимания&quot;,&quot;local&quot;:&quot;attention-backends&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Установите бэкенд для модели&quot;,&quot;local&quot;:&quot;set-a-backend-on-the-model&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Попробуйте бэкенд временно&quot;,&quot;local&quot;:&quot;try-a-backend-temporarily&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Доверие к удалённым ядрам&quot;,&quot;local&quot;:&quot;trusting-remote-kernels&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Проверки&quot;,&quot;local&quot;:&quot;checks&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Доступные бэкенды&quot;,&quot;local&quot;:&quot;available-backends&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2}],&quot;depth&quot;:1}"/>
<link href="/docs/diffusers/main/en/_app/immutable/entry/start.B6roO9Zr.js" rel="modulepreload">
<link href="/docs/diffusers/main/en/_app/immutable/chunks/CjYFLaCl.js" rel="modulepreload">
<link href="/docs/diffusers/main/en/_app/immutable/chunks/Cc4T7sti.js" rel="modulepreload">
<link href="/docs/diffusers/main/en/_app/immutable/entry/app.CxxEVG8A.js" rel="modulepreload">
<link href="/docs/diffusers/main/en/_app/immutable/chunks/C8F28shN.js" rel="modulepreload">
<link href="/docs/diffusers/main/en/_app/immutable/chunks/BTnLXsn-.js" rel="modulepreload">
<link href="/docs/diffusers/main/en/_app/immutable/chunks/DnVIJfC5.js" rel="modulepreload">
<link href="/docs/diffusers/main/en/_app/immutable/chunks/DsnmJJEf.js" rel="modulepreload">
<link href="/docs/diffusers/main/en/_app/immutable/nodes/0.CmHT0Edy.js" rel="modulepreload">
<link href="/docs/diffusers/main/en/_app/immutable/chunks/C7Ky3Ped.js" rel="modulepreload">
<link href="/docs/diffusers/main/en/_app/immutable/nodes/7.CnCvnb8O.js" rel="modulepreload">
<link href="/docs/diffusers/main/en/_app/immutable/chunks/D2YP2_0L.js" rel="modulepreload">
<!--gxcprv--><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 a backend on the model&quot;,&quot;local&quot;:&quot;set-a-backend-on-the-model&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Try a backend temporarily&quot;,&quot;local&quot;:&quot;try-a-backend-temporarily&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Trusting remote kernels&quot;,&quot;local&quot;:&quot;trusting-remote-kernels&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Checks&quot;,&quot;local&quot;:&quot;checks&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Available backends&quot;,&quot;local&quot;:&quot;available-backends&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2}],&quot;depth&quot;:1}"/><!---->
<link href="/docs/diffusers/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><!--]--><!----> <blockquote class="note"><p>Диспетчер внимания — это экспериментальная функция. Пожалуйста, создайте issue, если у вас есть отзывы или вы столкнулись с какими-либо проблемами.</p></blockquote> <p>Большинство трансформерных моделей Diffusers маршрутизируют внимание через <em>диспетчер внимания</em>, что позволяет переключать оптимизированные бэкенды за единым API. Диспетчер управляет зарегистрированными реализациями и предоставляет для них единый путь вызова. Некоторые модели, например многие автоэнкодеры, не используют диспетчер из-за своей внутренней структуры, и переключение бэкенда не влияет на их слои внимания.</p> <p>См. таблицу ниже для обзора доступных семейств внимания и раздел <a href="#available-backends">Доступные бэкенды</a> для более полного списка. Самый быстрый бэкенд зависит от модели, GPU, dtype и формы входных данных.</p> <table><thead><tr><th>семейство attention</th><th>основная функция</th></tr></thead><tbody><tr><td>FlashAttention</td><td>минимизирует чтение/запись памяти с помощью тайлинга и пересчета</td></tr><tr><td>AI Tensor Engine для ROCm</td><td>Реализация FlashAttention, оптимизированная для ускорителей AMD ROCm</td></tr><tr><td>SageAttention</td><td>квантует внимание до int8</td></tr><tr><td>FlexAttention</td><td>PyTorch FlexAttention</td></tr><tr><td>Нативный PyTorch</td><td>встроенная реализация PyTorch с использованием <a href="./fp16#scaled-dot-product-attention">scaled_dot_product_attention</a></td></tr><tr><td>xFormers</td><td>memory-efficient attention с поддержкой различных attention-ядер</td></tr></tbody></table> <p>Бэкенды Hub (имена <code>*_hub</code>) требуют библиотеку <a href="https://github.com/huggingface/kernels" rel="nofollow">Kernels</a> и загружают ядро при первом использовании. Бэкенды Hub для SageAttention также требуют <code>DIFFUSERS_TRUST_REMOTE_KERNELS=true</code> (см. <a href="#trusting-remote-kernels">Доверие удалённым ядрам</a>). Остальные бэкенды требуют свои пакеты, например <code>flash-attn</code> или <code>sageattention</code>. В таблице <a href="#available-backends">Доступные бэкенды</a> перечислены требования, которые Diffusers проверяет при включении бэкенда.</p> <!--[1--><h2 class="relative group"><a id="set-a-backend-on-the-model" 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-a-backend-on-the-model"><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/diffusers/main/ru/api/models/overview#diffusers.ModelMixin.set_attention_backend">set_attention_backend()</a> проходит по слоям внимания модели и применяет выбранный бэкенд к каждому из них. Он также устанавливает активный бэкенд диспетчера для всего процесса в то же значение.</p> <p><a href="/docs/diffusers/main/ru/api/models/overview#diffusers.ModelMixin.reset_attention_backend">reset_attention_backend()</a> очищает бэкенд только на слоях внимания. Он не очищает активный бэкенд для всего процесса. Для временного переключения, которое восстанавливает предыдущий активный бэкенд при выходе, используйте контекстный менеджер <a href="#try-a-backend-temporarily">attention_backend</a>.</p> <p>Пример ниже включает <code>_flash_3_hub</code> (FlashAttention-3 из Hub) с <code>device_map="cuda"</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> diffusers <span class="hljs-keyword">import</span> QwenImagePipeline
pipeline = QwenImagePipeline.from_pretrained(
<span class="hljs-string">&quot;Qwen/Qwen-Image&quot;</span>, dtype=torch.bfloat16, device_map=<span class="hljs-string">&quot;cuda&quot;</span>
)
pipeline.transformer.set_attention_backend(<span class="hljs-string">&quot;_flash_3_hub&quot;</span>)
prompt = <span class="hljs-string">&quot;&quot;&quot;
cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
&quot;&quot;&quot;</span>
pipeline(prompt).images[<span class="hljs-number">0</span>]<!----></pre></div><!----> <blockquote class="note"><p>Бэкенды FlashAttention-3, не использующие Hub (<code>_flash_3</code>, <code>_flash_varlen_3</code>), требуют сборки FlashAttention-3 из исходного кода и скоро будут сняты с поддержки. Вместо них используйте <code>_flash_3_hub</code> или <code>_flash_3_varlen_hub</code>.</p></blockquote> <!--[1--><h2 class="relative group"><a id="try-a-backend-temporarily" 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="#try-a-backend-temporarily"><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>attention_backend()</code> устанавливает активный бэкенд для всего процесса на время выполнения блока и восстанавливает предыдущий бэкенд при выходе из блока. Используйте его, чтобы протестировать бэкенд для одного вызова, не оставляя постоянный бэкенд, установленный через <a href="/docs/diffusers/main/ru/api/models/overview#diffusers.ModelMixin.set_attention_backend">set_attention_backend()</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> diffusers <span class="hljs-keyword">import</span> QwenImagePipeline, attention_backend
pipeline = QwenImagePipeline.from_pretrained(
<span class="hljs-string">&quot;Qwen/Qwen-Image&quot;</span>, dtype=torch.bfloat16, device_map=<span class="hljs-string">&quot;cuda&quot;</span>
)
prompt = <span class="hljs-string">&quot;&quot;&quot;
cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
&quot;&quot;&quot;</span>
<span class="hljs-keyword">with</span> attention_backend(<span class="hljs-string">&quot;_flash_3_hub&quot;</span>):
image = pipeline(prompt).images[<span class="hljs-number">0</span>]<!----></pre></div><!----> <blockquote class="tip"><p>Большинство бэкендов внимания работают с <code>torch.compile</code>. Ускорит ли это ваш пайплайн, зависит от модели и бэкенда. См. <a href="./fp16#torchcompile">Точность и компиляция</a>.</p></blockquote> <!--[1--><h2 class="relative group"><a id="trusting-remote-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="#trusting-remote-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></h2><!--]--><!----> <p>Бэкендам Hub сначала требуется библиотека <a href="https://github.com/huggingface/kernels" rel="nofollow">Kernels</a>, после чего Diffusers загружает ядро Hub при первом использовании.</p> <p>Бэкенды внимания Hub загружают вычислительные ядра с помощью библиотеки <a href="https://github.com/huggingface/kernels" rel="nofollow">Kernels</a> и запускают их локально. Большинство имён внимания Hub (<code>_flash_3_hub</code>, <code>flash_hub</code> и другие бэкенды <code>*_hub</code>) указывают на организацию <a href="https://huggingface.co/kernels-community" rel="nofollow">kernels-community</a>. Эта организация является доверенным издателем в Kernels, поэтому Diffusers загружает эти ядра внимания без установки переменной <code>DIFFUSERS_TRUST_REMOTE_KERNELS</code>.</p> <blockquote class="note"><p>Бэкенды SageAttention Hub (<code>sage_hub</code> и <code>sage_blackwell_hub</code>) загружаются из организации <a href="https://huggingface.co/SageAttention" rel="nofollow">SageAttention</a>. Для их использования установите <code>DIFFUSERS_TRUST_REMOTE_KERNELS=true</code>.</p></blockquote> <p>Другие функции, использующие ядра, такие как <a href="../quantization/gguf">GGUF</a> и <a href="../quantization/nunchaku">Nunchaku Lite</a>, могут загружать ядра от издателей, не входящих в kernels-community. Эти пути остаются заблокированными, если вы не разрешите их явно с помощью <code>DIFFUSERS_TRUST_REMOTE_KERNELS</code>. При установке этой переменной Diffusers передаёт <code>trust_remote_code=True</code> в Kernels, что позволяет загружать ядра и от ненадёжных издателей.</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-bash "><!----><span class="hljs-built_in">export</span> DIFFUSERS_TRUST_REMOTE_KERNELS=<span class="hljs-literal">true</span><!----></pre></div><!----> <p>Включайте этот параметр только после проверки репозитория ядра. Без него загрузка ядра от ненадёжного издателя приводит к ошибке. Diffusers выполняет эту проверку самостоятельно, поэтому она также распространяется на <code>kernels&lt;0.14.0</code>, которые предшествуют аргументу <code>trust_remote_code</code>. Установка <code>DIFFUSERS_DISABLE_REMOTE_CODE=true</code> глобально отключает удалённый код и имеет приоритет над <code>DIFFUSERS_TRUST_REMOTE_KERNELS</code>.</p> <!--[1--><h2 class="relative group"><a id="checks" 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="#checks"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Проверки<!----></span></h2><!--]--><!----> <p>Диспетчер внимания может выполнять отладочные проверки перед каждым вызовом диспетчеризованного внимания. Какие проверки выполняются, зависит от ограничений, зарегистрированных для активного бэкенда.</p> <ol><li>Проверки устройства подтверждают, что тензоры запроса, ключа и значения находятся на одном и том же устройстве.</li> <li>Проверки типов данных, если они зарегистрированы, подтверждают совпадение dtypes и часто требуют <code>bfloat16</code> или <code>float16</code>.</li> <li>Проверки формы валидируют размеры тензоров и предотвращают смешивание масок внимания с каузальными флагами.</li></ol> <p>Включите проверки с помощью переменной окружения <code>DIFFUSERS_ATTN_CHECKS</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-bash "><!----><span class="hljs-built_in">export</span> DIFFUSERS_ATTN_CHECKS=<span class="hljs-built_in">yes</span><!----></pre></div><!----> <p>При включённых проверках Diffusers выполняет эти ограничения перед каждым вызовом диспетчеризованного внимания. В приведённом ниже низкоуровневом примере <code>dispatch_attention_fn</code> вызывается напрямую. Для инференса пайплайна этот импорт не требуется. Достаточно установить бэкенд с помощью <a href="/docs/diffusers/main/ru/api/models/overview#diffusers.ModelMixin.set_attention_backend">set_attention_backend()</a> или <code>attention_backend()</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> diffusers.models.attention_dispatch <span class="hljs-keyword">import</span> attention_backend, dispatch_attention_fn
query = torch.randn(<span class="hljs-number">1</span>, <span class="hljs-number">10</span>, <span class="hljs-number">8</span>, <span class="hljs-number">64</span>, dtype=torch.bfloat16, device=<span class="hljs-string">&quot;cuda&quot;</span>)
key = torch.randn(<span class="hljs-number">1</span>, <span class="hljs-number">10</span>, <span class="hljs-number">8</span>, <span class="hljs-number">64</span>, dtype=torch.bfloat16, device=<span class="hljs-string">&quot;cuda&quot;</span>)
value = torch.randn(<span class="hljs-number">1</span>, <span class="hljs-number">10</span>, <span class="hljs-number">8</span>, <span class="hljs-number">64</span>, dtype=torch.bfloat16, device=<span class="hljs-string">&quot;cuda&quot;</span>)
<span class="hljs-keyword">try</span>:
<span class="hljs-keyword">with</span> attention_backend(<span class="hljs-string">&quot;flash&quot;</span>):
output = dispatch_attention_fn(query, key, value)
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;✓ Flash Attention works with checks enabled&quot;</span>)
<span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
<span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;✗ Flash Attention failed: <span class="hljs-subst">{e}</span>&quot;</span>)<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="available-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="#available-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></h2><!--]--><!----> <p>Список доступных бэкендов внимания и их вариантов приведён в таблице ниже. При включении бэкенда Diffusers проверяет наличие пакета и закреплённые версии.</p> <table><thead><tr><th>Имя бэкенда</th><th>Семейство</th><th>Описание</th><th>Предварительные требования</th></tr></thead><tbody><tr><td><code>native</code></td><td><a href="https://docs.pytorch.org/docs/stable/generated/torch.nn.attention.SDPBackend.html#torch.nn.attention.SDPBackend" rel="nofollow">нативный PyTorch</a></td><td>Бэкенд по умолчанию, использующий scaled_dot_product_attention из PyTorch</td><td>None</td></tr><tr><td><code>flex</code></td><td><a href="https://docs.pytorch.org/docs/stable/nn.attention.flex_attention.html#module-torch.nn.attention.flex_attention" rel="nofollow">FlexAttention</a></td><td>PyTorch FlexAttention</td><td><code>torch>=2.5.0</code></td></tr><tr><td><code>_native_cudnn</code></td><td><a href="https://docs.pytorch.org/docs/stable/generated/torch.nn.attention.SDPBackend.html#torch.nn.attention.SDPBackend" rel="nofollow">нативный PyTorch</a></td><td>Внимание с оптимизацией CuDNN</td><td>CUDA + CuDNN</td></tr><tr><td><code>_native_efficient</code></td><td><a href="https://docs.pytorch.org/docs/stable/generated/torch.nn.attention.SDPBackend.html#torch.nn.attention.SDPBackend" rel="nofollow">нативный PyTorch</a></td><td>Внимание с эффективной работой с памятью</td><td>Ничего, кроме PyTorch</td></tr><tr><td><code>_native_flash</code></td><td><a href="https://docs.pytorch.org/docs/stable/generated/torch.nn.attention.SDPBackend.html#torch.nn.attention.SDPBackend" rel="nofollow">нативный PyTorch</a></td><td>FlashAttention в PyTorch</td><td>CUDA</td></tr><tr><td><code>_native_math</code></td><td><a href="https://docs.pytorch.org/docs/stable/generated/torch.nn.attention.SDPBackend.html#torch.nn.attention.SDPBackend" rel="nofollow">нативный PyTorch</a></td><td>Внимание на основе математики (резервный вариант)</td><td>None</td></tr><tr><td><code>_native_npu</code></td><td><a href="https://docs.pytorch.org/docs/stable/generated/torch.nn.attention.SDPBackend.html#torch.nn.attention.SDPBackend" rel="nofollow">нативный PyTorch</a></td><td>Внимание, оптимизированное для NPU</td><td><code>torch_npu</code></td></tr><tr><td><code>_native_xla</code></td><td><a href="https://docs.pytorch.org/docs/stable/generated/torch.nn.attention.SDPBackend.html#torch.nn.attention.SDPBackend" rel="nofollow">нативный PyTorch</a></td><td>Внимание, оптимизированное XLA</td><td><code>torch_xla>=2.2</code></td></tr><tr><td><code>flash</code></td><td><a href="https://github.com/Dao-AILab/flash-attention" rel="nofollow">FlashAttention</a></td><td>FlashAttention-2</td><td><code>flash-attn>=2.6.3</code></td></tr><tr><td><code>flash_hub</code></td><td><a href="https://github.com/Dao-AILab/flash-attention" rel="nofollow">FlashAttention</a></td><td>FlashAttention-2 из Hub kernels</td><td><code>kernels>=0.12</code></td></tr><tr><td><code>flash_varlen</code></td><td><a href="https://github.com/Dao-AILab/flash-attention" rel="nofollow">FlashAttention</a></td><td>FlashAttention с переменной длиной</td><td><code>flash-attn>=2.6.3</code></td></tr><tr><td><code>flash_varlen_hub</code></td><td><a href="https://github.com/Dao-AILab/flash-attention" rel="nofollow">FlashAttention</a></td><td>FlashAttention переменной длины из ядра Hub</td><td><code>kernels>=0.12</code></td></tr><tr><td><code>aiter_fa2_hub</code></td><td><a href="https://github.com/ROCm/aiter" rel="nofollow">AI Tensor Engine для ROCm</a></td><td>FlashAttention-2 для AMD ROCm из Hub kernels (<code>bfloat16</code>)</td><td><code>kernels>=0.12</code>, ROCm</td></tr><tr><td><code>flash_4_hub</code></td><td><a href="https://github.com/Dao-AILab/flash-attention" rel="nofollow">FlashAttention</a></td><td>FlashAttention-4 из ядра Hub</td><td><code>kernels>=0.12.3</code></td></tr><tr><td><code>_flash_3</code></td><td><a href="https://github.com/Dao-AILab/flash-attention" rel="nofollow">FlashAttention</a></td><td>FlashAttention-3 (локальный; скоро будет снят с поддержки)</td><td>Сборка FA3 из исходного кода</td></tr><tr><td><code>_flash_varlen_3</code></td><td><a href="https://github.com/Dao-AILab/flash-attention" rel="nofollow">FlashAttention</a></td><td>FlashAttention-3 переменной длины (локальный; скоро будет снят с поддержки)</td><td>Сборка FA3 из исходного кода</td></tr><tr><td><code>_flash_3_hub</code></td><td><a href="https://github.com/Dao-AILab/flash-attention" rel="nofollow">FlashAttention</a></td><td>FlashAttention-3 из Hub kernels</td><td><code>kernels>=0.12</code></td></tr><tr><td><code>_flash_3_varlen_hub</code></td><td><a href="https://github.com/Dao-AILab/flash-attention" rel="nofollow">FlashAttention</a></td><td>FlashAttention-3 переменной длины из ядра Hub</td><td><code>kernels>=0.12</code></td></tr><tr><td><code>sage</code></td><td><a href="https://github.com/thu-ml/SageAttention" rel="nofollow">SageAttention</a></td><td>Квантованное внимание (INT8 QK)</td><td><code>sageattention>=2.1.1</code></td></tr><tr><td><code>sage_hub</code></td><td><a href="https://github.com/thu-ml/SageAttention" rel="nofollow">SageAttention</a></td><td>Квантованное внимание (INT8 QK) из ядра Hub</td><td><code>kernels>=0.12</code>, <code>DIFFUSERS_TRUST_REMOTE_KERNELS=true</code></td></tr><tr><td><code>sage_blackwell_hub</code></td><td><a href="https://github.com/thu-ml/SageAttention" rel="nofollow">SageAttention</a></td><td>Внимание SageAttention3 FP4 для GPU SM120 Blackwell из ядра Hub</td><td><code>kernels>=0.12</code>, <code>DIFFUSERS_TRUST_REMOTE_KERNELS=true</code></td></tr><tr><td><code>sage_varlen</code></td><td><a href="https://github.com/thu-ml/SageAttention" rel="nofollow">SageAttention</a></td><td>SageAttention переменной длины</td><td><code>sageattention>=2.1.1</code></td></tr><tr><td><code>_sage_qk_int8_pv_fp8_cuda</code></td><td><a href="https://github.com/thu-ml/SageAttention" rel="nofollow">SageAttention</a></td><td>INT8 QK + FP8 PV (CUDA)</td><td><code>sageattention>=2.1.1</code></td></tr><tr><td><code>_sage_qk_int8_pv_fp8_cuda_sm90</code></td><td><a href="https://github.com/thu-ml/SageAttention" rel="nofollow">SageAttention</a></td><td>INT8 QK + FP8 PV (SM90)</td><td><code>sageattention>=2.1.1</code>; SM90</td></tr><tr><td><code>_sage_qk_int8_pv_fp16_cuda</code></td><td><a href="https://github.com/thu-ml/SageAttention" rel="nofollow">SageAttention</a></td><td>INT8 QK + FP16 PV (CUDA)</td><td><code>sageattention>=2.1.1</code></td></tr><tr><td><code>_sage_qk_int8_pv_fp16_triton</code></td><td><a href="https://github.com/thu-ml/SageAttention" rel="nofollow">SageAttention</a></td><td>INT8 QK + FP16 PV (Triton)</td><td><code>sageattention>=2.1.1</code></td></tr><tr><td><code>xformers</code></td><td><a href="https://github.com/facebookresearch/xformers" rel="nofollow">xFormers</a></td><td>Внимание с эффективной работой с памятью</td><td><code>xformers>=0.0.29</code></td></tr></tbody></table> <a class="!text-gray-400 !no-underline text-sm flex items-center not-prose mt-4" href="https://github.com/huggingface/diffusers/blob/main/docs/source/en/optimization/attention_backends.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_kft2r9 = {
base: "/docs/diffusers/main/en",
assets: "/docs/diffusers/main/en"
};
const element = document.currentScript.parentElement;
Promise.all([
import("/docs/diffusers/main/en/_app/immutable/entry/start.B6roO9Zr.js"),
import("/docs/diffusers/main/en/_app/immutable/entry/app.CxxEVG8A.js")
]).then(([kit, app]) => {
kit.start(app, element, {
node_ids: [0, 7],
data: [null,null],
form: null,
error: null
});
});
}
</script>

Xet Storage Details

Size:
41.4 kB
·
Xet hash:
a7d730f6ce573814fdecb548916ed64f38214212c179ff2b2b7b2c7855a0afd6

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