Buckets:
| <meta charset="utf-8" /><meta name="hf:doc:metadata" content="{"title":"Cache","local":"caching","sections":[{"title":"Escolha um método de cache","local":"choose-a-cache-method","sections":[],"depth":2},{"title":"Pyramid Attention Broadcast","local":"pyramid-attention-broadcast","sections":[],"depth":2},{"title":"FasterCache","local":"fastercache","sections":[],"depth":2},{"title":"SeaCache","local":"seacache","sections":[],"depth":2},{"title":"FirstBlockCache","local":"firstblockcache","sections":[],"depth":2},{"title":"Cache TaylorSeer","local":"taylorseer-cache","sections":[],"depth":2},{"title":"MagCache","local":"magcache","sections":[],"depth":2},{"title":"Cache de KV de Texto","local":"text-kv-cache","sections":[],"depth":2},{"title":"Adicionar cache a um novo modelo","local":"add-caching-to-a-new-model","sections":[],"depth":2}],"depth":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/8.DhsC3tNN.js" rel="modulepreload"> | |
| <link href="/docs/diffusers/main/en/_app/immutable/chunks/D2YP2_0L.js" rel="modulepreload"> | |
| <!--fs68f1--><meta name="hf:doc:metadata" content="{"title":"Caching","local":"caching","sections":[{"title":"Choose a cache method","local":"choose-a-cache-method","sections":[],"depth":2},{"title":"Pyramid Attention Broadcast","local":"pyramid-attention-broadcast","sections":[],"depth":2},{"title":"FasterCache","local":"fastercache","sections":[],"depth":2},{"title":"SeaCache","local":"seacache","sections":[],"depth":2},{"title":"FirstBlockCache","local":"firstblockcache","sections":[],"depth":2},{"title":"TaylorSeer Cache","local":"taylorseer-cache","sections":[],"depth":2},{"title":"MagCache","local":"magcache","sections":[],"depth":2},{"title":"Text KV Cache","local":"text-kv-cache","sections":[],"depth":2},{"title":"Add caching to a new model","local":"add-caching-to-a-new-model","sections":[],"depth":2}],"depth":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="caching" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#caching"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Cache<!----></span></h1><!--]--><!----> <p>O cache reutiliza as saídas das camadas intermediárias entre as etapas de remoção de ruído para acelerar a inferência. Ele usa mais memória e não requer treinamento. Ative um método com uma configuração em um transformer que suporte cache.</p> <!--[1--><h2 class="relative group"><a id="choose-a-cache-method" 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="#choose-a-cache-method"><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><!---->Escolha um método de cache<!----></span></h2><!--]--><!----> <p>Escolha um método com base na quantidade de configuração que você definirá e no ajuste necessário. Cada método equilibra velocidade, memória e o quão de perto as saídas correspondem à execução sem cache de maneira diferente. Compare as saídas com e sem o cache nos seus próprios prompts antes de confiar em um método.</p> <table><thead><tr><th>Método</th><th>Use quando</th><th>Observações</th></tr></thead><tbody><tr><td><a href="#text-kv-cache">Cache de KV de texto</a></td><td>Imagem do NucleusMoE, reutilização das projeções de texto K/V entre etapas</td><td>Atualmente, os hooks capturam os blocos de imagem do NucleusMoE</td></tr><tr><td><a href="#seacache">SeaCache</a></td><td>Geração de vídeo Cosmos 3</td><td>As configurações geralmente não são transferidas entre modelos</td></tr><tr><td><a href="#firstblockcache">FirstBlockCache</a></td><td>Quer um único controle principal de velocidade/qualidade em um transformer registrado</td><td>Um <code>threshold</code> controla a frequência com que as etapas são puladas</td></tr><tr><td><a href="#magcache">MagCache</a></td><td>Você tem as razões de magnitude para seu checkpoint e agendador, ou calibrará primeiro</td><td>As proporções são específicas do checkpoint e do agendador</td></tr><tr><td><a href="#taylorseer-cache">TaylorSeer</a></td><td>Deseja prever ativações posteriores a partir de etapas anteriores</td><td>Um <code>max_order</code> maior usa mais memória</td></tr><tr><td><a href="#pyramid-attention-broadcast">PAB</a></td><td>Vídeo, com possibilidade de ajustar a reutilização de atenção (intervalos de blocos e de saltos de passo de tempo por tipo de atenção)</td><td>Os intervalos de salto precisam de ajuste para cada modelo</td></tr><tr><td><a href="#fastercache">FasterCache</a></td><td>Como o PAB, além da possibilidade de ignorar o ramo do CFG</td><td>Experimental</td></tr></tbody></table> <!--[1--><h2 class="relative group"><a id="pyramid-attention-broadcast" 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="#pyramid-attention-broadcast"><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><!---->Pyramid Attention Broadcast<!----></span></h2><!--]--><!----> <p><a href="https://huggingface.co/papers/2408.12588" rel="nofollow">Pyramid Attention Broadcast (PAB)</a> aproxima a atenção entre as etapas de desruidamento reutilizando as saídas de atenção para alguns blocos e timesteps, em vez de recalcular a cada etapa. O Config separa os tipos de atenção (espacial, temporal, cruzada) quando o modelo os possui. Nem todo modelo de vídeo expõe os três tipos, e defina apenas os intervalos que correspondem aos blocos que você possui.</p> <p>Cada tipo usa um <code>*_attention_block_skip_range</code> (com que frequência recalcular versus reutilizar dentro da janela) e um <code>*_attention_timestep_skip_range</code> (quais timesteps de desruidamento podem ser pulados). Você deve passar <code>current_timestep_callback</code> para que o hook possa ler o timestep atual do pipeline. Pulos mais amplos ou agressivos geralmente significam mais velocidade e mais risco de qualidade.</p> <p>Passe um <a href="/docs/diffusers/main/pt/api/cache#diffusers.PyramidAttentionBroadcastConfig">PyramidAttentionBroadcastConfig</a> para ativá-lo.</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> Copiado</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">import</span> torch | |
| <span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> CogVideoXPipeline, PyramidAttentionBroadcastConfig | |
| pipe = CogVideoXPipeline.from_pretrained(<span class="hljs-string">"THUDM/CogVideoX-5b"</span>, dtype=torch.bfloat16) | |
| pipe.to(<span class="hljs-string">"cuda"</span>) <span class="hljs-comment"># or "mps", "xpu", "cpu"</span> | |
| config = PyramidAttentionBroadcastConfig( | |
| spatial_attention_block_skip_range=<span class="hljs-number">2</span>, | |
| spatial_attention_timestep_skip_range=(<span class="hljs-number">100</span>, <span class="hljs-number">800</span>), | |
| current_timestep_callback=<span class="hljs-keyword">lambda</span>: pipe.current_timestep, | |
| ) | |
| pipe.transformer.enable_cache(config)<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="fastercache" 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="#fastercache"><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><!---->FasterCache<!----></span></h2><!--]--><!----> <p><a href="https://huggingface.co/papers/2410.19355" rel="nofollow">FasterCache</a> faz o cache e reutiliza recursos de atenção semelhantes aos de <a href="#pyramid-attention-broadcast">PAB</a>. Ele também pode pular o ramo incondicional sob a orientação livre de classificador e estimá-lo a partir do ramo condicional quando os latentes sucessivos forem redundantes o suficiente.</p> <p>Passe um <a href="/docs/diffusers/main/pt/api/cache#diffusers.FasterCacheConfig">FasterCacheConfig</a> para ativá-lo. Assim como no PAB, defina <code>*_attention_block_skip_range</code> e <code>*_attention_timestep_skip_range</code> para os tipos de atenção que você possui, além das opções de skip do ramo CFG, quando desejá-las.</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> Copiado</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">import</span> torch | |
| <span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> CogVideoXPipeline, FasterCacheConfig | |
| pipe = CogVideoXPipeline.from_pretrained(<span class="hljs-string">"THUDM/CogVideoX-5b"</span>, dtype=torch.bfloat16) | |
| pipe.to(<span class="hljs-string">"cuda"</span>) <span class="hljs-comment"># or "mps", "xpu", "cpu"</span> | |
| config = FasterCacheConfig( | |
| spatial_attention_block_skip_range=<span class="hljs-number">2</span>, | |
| spatial_attention_timestep_skip_range=(-<span class="hljs-number">1</span>, <span class="hljs-number">681</span>), | |
| current_timestep_callback=<span class="hljs-keyword">lambda</span>: pipe.current_timestep, | |
| attention_weight_callback=<span class="hljs-keyword">lambda</span> _: <span class="hljs-number">0.3</span>, | |
| unconditional_batch_skip_range=<span class="hljs-number">5</span>, | |
| unconditional_batch_timestep_skip_range=(-<span class="hljs-number">1</span>, <span class="hljs-number">781</span>), | |
| tensor_format=<span class="hljs-string">"BFCHW"</span>, | |
| ) | |
| pipe.transformer.enable_cache(config)<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="seacache" 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="#seacache"><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><!---->SeaCache<!----></span></h2><!--]--><!----> <p><a href="https://huggingface.co/papers/2602.18993" rel="nofollow">SeaCache</a> compara os indicadores Spectral Evolution Aware (SEA) entre as etapas sucessivas de remoção de ruído. Quando a mudança acumulada permanece abaixo de um limite, ele ignora a pilha de blocos do transformer e prevê a saída a partir dos resíduos em cache. O método é aproximado e projetado para geração de vídeo.</p> <p>Os adaptadores integrados para SeaCache incluem:</p> <ul><li>Cosmos 3 é a integração principal otimizada e benchmarked.</li> <li>Wan T2V usa o caminho de bloco repetido genérico como demonstração de como fornecer os latentes de visão brutos ao SeaCache. Os mesmos parâmetros de cache podem não se transferir para o Wan ou outras variantes do Wan.</li></ul> <p>Ative o SeaCache no transformer. O loop de desruidamento do Cosmos 3 anexa o passo do agendador, o sigma e a contagem de passos a cada <code>cache_context</code>, portanto, nenhum parâmetro extra é necessário.</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> Copiado</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> Cosmos3OmniPipeline, SeaCacheConfig | |
| pipe = Cosmos3OmniPipeline.from_pretrained(<span class="hljs-string">"nvidia/Cosmos3-Nano"</span>) | |
| pipe.transformer.enable_cache(SeaCacheConfig(threshold=<span class="hljs-number">0.2</span>, max_consecutive_cached=<span class="hljs-number">2</span>))<!----></pre></div><!----> <p>SeaCache pode alterar as saídas. Chame <code>pipe.transformer.disable_cache()</code> quando precisar que cada etapa execute o transformador completo. A mesma chamada de habilitação funciona com <a href="/docs/diffusers/main/pt/api/pipelines/cosmos3#diffusers.Cosmos3OmniPipeline">Cosmos3OmniPipeline</a>, <a href="/docs/diffusers/main/pt/api/pipelines/cosmos3#diffusers.Cosmos3OmniModularPipeline">Cosmos3OmniModularPipeline</a> e <a href="/docs/diffusers/main/pt/api/pipelines/cosmos3#diffusers.Cosmos3DistilledModularPipeline">Cosmos3DistilledModularPipeline</a>.</p> <p>Para usar o SeaCache com outro video transformer, siga <a href="#add-caching-to-a-new-model">Adicionar cache a um novo modelo</a>. O SeaCache também precisa de <code>step_index</code>, <code>sigma</code> e <code>num_inference_steps</code> em cada <code>cache_context</code>, e de um <code>raw_vision_callback</code> quando não existe um adaptador embutido. Ajuste os parâmetros conforme o modelo e o agendador.</p> <!--[1--><h2 class="relative group"><a id="firstblockcache" 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="#firstblockcache"><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><!---->FirstBlockCache<!----></span></h2><!--]--><!----> <p><a href="/docs/diffusers/main/pt/api/cache#diffusers.FirstBlockCacheConfig">FirstBlockCacheConfig</a> verifica o quanto as camadas iniciais do denoiser mudam de um timestep para o próximo. Se a mudança for pequena, o modelo ignora as camadas posteriores, que são mais custosas, e reutiliza a saída anterior.</p> <p>Ative-o por meio de <code>enable_cache</code> para que <code>disable_cache</code> e <code>is_cache_enabled</code> permaneçam sincronizados. O valor padrão de <code>threshold</code> é <code>0.05</code>. Um valor maior, como <code>0.2</code>, ignora com mais frequência para ganhar velocidade, mas a qualidade da geração pode diminuir.</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> Copiado</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">import</span> torch | |
| <span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> DiffusionPipeline, FirstBlockCacheConfig | |
| pipe = DiffusionPipeline.from_pretrained( | |
| <span class="hljs-string">"Qwen/Qwen-Image"</span>, dtype=torch.bfloat16 | |
| ) | |
| pipe.transformer.enable_cache(FirstBlockCacheConfig(threshold=<span class="hljs-number">0.2</span>))<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="taylorseer-cache" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#taylorseer-cache"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Cache TaylorSeer<!----></span></h2><!--]--><!----> <p><a href="https://huggingface.co/papers/2503.06923" rel="nofollow">TaylorSeer Cache</a> acelera a inferência de difusão com expansões em série de Taylor ao longo das etapas de desruido. Ele prevê as ativações de etapas posteriores a partir das anteriores e reutiliza essas previsões por várias etapas, de modo que o transformer realize menos trabalho completo.</p> <ul><li><code>cache_interval</code>: Número de etapas para reutilizar saídas em cache antes de executar uma passagem completa</li> <li><code>disable_cache_before_step</code>: Etapas iniciais que usam computações completas para coletar dados para aproximações</li> <li><code>max_order</code>: Ordens de Taylor mais altas podem ser mais precisas, mas usam mais memória. Mantenha esse valor em <code>1</code>, a menos que você tenha um motivo para alterá-lo.</li></ul> <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> Copiado</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">import</span> torch | |
| <span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> FluxPipeline, TaylorSeerCacheConfig | |
| pipe = FluxPipeline.from_pretrained( | |
| <span class="hljs-string">"black-forest-labs/FLUX.1-dev"</span>, | |
| dtype=torch.bfloat16, | |
| ).to(<span class="hljs-string">"cuda"</span>) <span class="hljs-comment"># or "mps", "xpu", "cpu"</span> | |
| config = TaylorSeerCacheConfig( | |
| cache_interval=<span class="hljs-number">5</span>, | |
| max_order=<span class="hljs-number">1</span>, | |
| disable_cache_before_step=<span class="hljs-number">10</span>, | |
| taylor_factors_dtype=torch.bfloat16, | |
| ) | |
| pipe.transformer.enable_cache(config)<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="magcache" 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="#magcache"><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><!---->MagCache<!----></span></h2><!--]--><!----> <p><a href="https://github.com/Zehong-Ma/MagCache" rel="nofollow">MagCache</a> ignora blocos de transformador com base na magnitude da atualização residual. As magnitudes de atualização decaem de forma previsível ao longo do desruidamento, e o MagCache rastreia um orçamento de erro a partir de razões de magnitude pré-computadas (<code>mag_ratios</code>) para decidir quando a reutilização é segura. Essas razões são específicas do checkpoint e do agendador. Razões de um número alto de passos podem ser interpoladas para um número menor de passos.</p> <blockquote class="tip"><p>Os <code>FLUX_MAG_RATIOS</code> incluídos foram medidos no FLUX.1. Outros modelos, incluindo Flux2 e Flux2 Klein, precisam de sua própria execução de calibração.</p></blockquote> <p>O MagCache segue duas etapas:</p> <ol><li>Calibração: execute a inferência uma vez com <code>calibrate=True</code>. O hook mede as magnitudes residuais e imprime as proporções calculadas.</li> <li>Inferência: desative o cache de calibração e, em seguida, passe essas proporções para <code>MagCacheConfig</code> para aceleração.</li></ol> <p>A orientação sem classificador (classifier-free guidance) pode afetar a calibração. Pipelines que usam CFG verdadeiro com contextos sequenciais, como o Flux quando <code>true_cfg_scale > 1</code>, entram em <code>cache_context("cond")</code> e <code>cache_context("uncond")</code> separadamente. A calibração pode imprimir um array por contexto, mas você deve usar o array condicional na maioria dos casos. Pipelines que agrupam o CFG concatenando entradas condicionais e incondicionais (por exemplo, CogVideoX) produzem um array conjunto único que você pode usar diretamente.</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> Copiado</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">import</span> torch | |
| <span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> FluxPipeline, MagCacheConfig | |
| <span class="hljs-keyword">from</span> diffusers.hooks.mag_cache <span class="hljs-keyword">import</span> FLUX_MAG_RATIOS | |
| pipe = FluxPipeline.from_pretrained( | |
| <span class="hljs-string">"black-forest-labs/FLUX.1-schnell"</span>, | |
| dtype=torch.bfloat16 | |
| ).to(<span class="hljs-string">"cuda"</span>) <span class="hljs-comment"># or "mps", "xpu", "cpu"</span> | |
| <span class="hljs-comment"># 1. Calibration Step</span> | |
| <span class="hljs-comment"># Run full inference to measure model behavior.</span> | |
| calib_config = MagCacheConfig(calibrate=<span class="hljs-literal">True</span>, num_inference_steps=<span class="hljs-number">4</span>) | |
| pipe.transformer.enable_cache(calib_config) | |
| <span class="hljs-comment"># Run a prompt to trigger calibration</span> | |
| pipe(<span class="hljs-string">"A cat playing chess"</span>, num_inference_steps=<span class="hljs-number">4</span>) | |
| <span class="hljs-comment"># Prints: [MagCache] Calibration Complete. Copy these values to MagCacheConfig(mag_ratios=...):</span> | |
| <span class="hljs-comment"># 2. Inference Step</span> | |
| <span class="hljs-comment"># Disable calibration hooks before enabling MagCache for inference.</span> | |
| pipe.transformer.disable_cache() | |
| <span class="hljs-comment"># Apply ratios from calibration, or use the Flux defaults:</span> | |
| <span class="hljs-comment"># mag_ratios=FLUX_MAG_RATIOS</span> | |
| mag_config = MagCacheConfig( | |
| mag_ratios=[<span class="hljs-number">1.0</span>, <span class="hljs-number">1.37</span>, <span class="hljs-number">0.97</span>, <span class="hljs-number">0.87</span>], | |
| num_inference_steps=<span class="hljs-number">4</span> | |
| ) | |
| pipe.transformer.enable_cache(mag_config) | |
| image = pipe(<span class="hljs-string">"A cat playing chess"</span>, num_inference_steps=<span class="hljs-number">4</span>).images[<span class="hljs-number">0</span>]<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="text-kv-cache" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#text-kv-cache"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Cache de KV de Texto<!----></span></h2><!--]--><!----> <p><a href="/docs/diffusers/main/pt/api/cache#diffusers.TextKVCacheConfig">TextKVCacheConfig</a> calcula as projeções de chave e valor do texto uma única vez e as reutiliza em cada etapa de desruido, em vez de recalculá-las. <a href="/docs/diffusers/main/pt/api/cache#diffusers.apply_text_kv_cache">apply_text_kv_cache()</a> atualmente faz o hook apenas em <code>NucleusMoEImageTransformerBlock</code>. Ative-o com <code>enable_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> Copiado</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">import</span> torch | |
| <span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> NucleusMoEImagePipeline, TextKVCacheConfig | |
| pipe = NucleusMoEImagePipeline.from_pretrained( | |
| <span class="hljs-string">"NucleusAI/NucleusMoE-Image"</span>, dtype=torch.bfloat16 | |
| ) | |
| pipe.to(<span class="hljs-string">"cuda"</span>) <span class="hljs-comment"># or "mps", "xpu", "cpu"</span> | |
| pipe.transformer.enable_cache(TextKVCacheConfig()) | |
| image = pipe(<span class="hljs-string">"A cat holding a sign that says hello world"</span>, num_inference_steps=<span class="hljs-number">50</span>).images[<span class="hljs-number">0</span>]<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="add-caching-to-a-new-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="#add-caching-to-a-new-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><!---->Adicionar cache a um novo modelo<!----></span></h2><!--]--><!----> <p>Os métodos de cache são anexados a um modelo por meio de hooks, e esses hooks dependem da classe do modelo, dos seus blocos de transformer e do loop de desruidamento do pipeline. Configure os três antes de chamar <code>enable_cache</code> em um novo modelo.</p> <ol><li><p>Herde de <a href="/docs/diffusers/main/pt/api/cache#diffusers.CacheMixin">CacheMixin</a> na classe do transformer. Isso adiciona <code>enable_cache</code>, <code>disable_cache</code> e <code>cache_context</code>.</p></li> <li><p>Registre o layout de saída do bloco do transformer em <code>_register_transformer_blocks_metadata</code> em <code>hooks/_helpers.py</code>. Métodos que pulam ou reutilizam blocos inteiros, como FirstBlockCache, MagCache e SeaCache, usam esse registro para localizar os estados ocultos nas saídas do bloco.</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> Copiado</div><!----></button><!----></div> <pre class="language-py "><!---->TransformerBlockRegistry.register( | |
| model_class=MyTransformerBlock, | |
| metadata=TransformerBlockMetadata( | |
| return_hidden_states_index=<span class="hljs-number">0</span>, | |
| return_encoder_hidden_states_index=<span class="hljs-literal">None</span>, | |
| ), | |
| )<!----></pre></div><!----></li> <li><p>Envolva cada chamada do transformer no loop de desruidamento do pipeline com <code>cache_context</code>. Use nomes separados, como <code>"cond"</code> e <code>"uncond"</code>, quando a classifier-free guidance executa os ramos condicional e incondicional como chamadas separadas, para que cada ramo mantenha seu próprio estado de cache.</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> Copiado</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">with</span> <span class="hljs-variable language_">self</span>.transformer.cache_context(<span class="hljs-string">"cond"</span>): | |
| noise_pred = <span class="hljs-variable language_">self</span>.transformer(hidden_states=latents, timestep=timestep, ...)[<span class="hljs-number">0</span>]<!----></pre></div><!----></li></ol> <p>PAB e FasterCache também precisam de <code>current_timestep_callback</code> para que os hooks possam ler o timestep atual. Verifique a qualidade da saída no novo modelo, pois as configurações de cache ajustadas para um modelo geralmente não se transferem para outro.</p> <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/cache.md" target="_blank"><svg class="mr-1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M31,16l-7,7l-1.41-1.41L28.17,16l-5.58-5.59L24,9l7,7z"></path><path d="M1,16l7-7l1.41,1.41L3.83,16l5.58,5.59L8,23l-7-7z"></path><path d="M12.419,25.484L17.639,6.552l1.932,0.518L14.351,26.002z"></path></svg><!----> <span><span class="underline">Update</span> on GitHub</span></a><!----> <p></p><!--]--><!----><!--]--><!--]--><!--]--> <!--[-1--><!--]--><!--]--> | |
| <script> | |
| { | |
| __sveltekit_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, 8], | |
| data: [null,null], | |
| form: null, | |
| error: null | |
| }); | |
| }); | |
| } | |
| </script> | |
Xet Storage Details
- Size:
- 47.7 kB
- Xet hash:
- bac0dd2aacd4fd2372dade9c7c7fcb3c181541d9f5a2719d96bd8658c24c3a61
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.