Buckets:

hf-doc-build/doc / transformers /main /fr /attention_interface.html
mishig's picture
download
raw
74.9 kB
<meta charset="utf-8" /><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Backends d'attention&quot;,&quot;local&quot;:&quot;attention-backends&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Définir un backend d'attention&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;Gestionnaire de contexte 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;Attention spécifique au backbone&quot;,&quot;local&quot;:&quot;backbone-specific-attention&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Créer une nouvelle fonction d'attention&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;Construire un masque d'attention&quot;,&quot;local&quot;:&quot;build-an-attention-mask&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Passer un masque d'attention 4D personnalisé&quot;,&quot;local&quot;:&quot;pass-a-custom-4d-attention-mask&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Attention bidirectionnelle&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><!---->Backends d'attention<!----></span></h1><!--]--><!----> <p>Toutes les implémentations d'attention effectuent le même calcul. Chaque jeton est comparé à tous les autres jetons. La différence réside dans <em>la manière</em> dont le calcul est effectué. L'attention de base échoue à l'échelle car elle matérialise la matrice d'attention complète en mémoire, créant des goulets d'étranglement qui ralentissent l'inférence. Les implémentations optimisées réorganisent les mathématiques pour réduire le trafic mémoire et permettre une inférence plus rapide et plus abordable.</p> <p><a href="/docs/transformers/main/fr/internal/modeling_utils#transformers.AttentionInterface">AttentionInterface</a> fournit des implémentations d'attention optimisées. Il découple l'implémentation de l'attention de l'implémentation du modèle afin de simplifier les expérimentations avec différentes fonctions. Ajoutez facilement de nouveaux backends grâce à cette interface cohérente.</p> <table><tbody><tr><th>Backend d'attention</th><th>Description</th></tr><tr><td><code>"flash_attention_3"</code></td><td>améliore FlashAttention-2 en superposant également les opérations et en fusionnant plus étroitement les passes avant et arrière</td></tr><tr><td><code>"flash_attention_2"</code></td><td>découpe les calculs en blocs plus petits et utilise la mémoire rapide sur puce</td></tr><tr><td><code>"flex_attention"</code></td><td>framework pour spécifier des motifs d'attention personnalisés (sparse, block-local, sliding window) sans écrire de kernels de bas niveau à la main</td></tr><tr><td><code>"sdpa"</code></td><td>implémentation intégrée de PyTorch de <a href="https://docs.pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html">scaled dot product attention</a></td></tr><tr><td><code>"paged|flash_attention_3"</code></td><td>Version paginée de FlashAttention-3</td></tr><tr><td><code>"paged|flash_attention_2"</code></td><td>Version paginée de FlashAttention-2</td></tr><tr><td><code>"paged|sdpa"</code></td><td>Version paginée de SDPA</td></tr><tr><td><code>"paged|eager"</code></td><td>Version paginée de 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><!---->Définir un backend d'attention<!----></span></h2><!--]--><!----> <p>Utilisez l'argument <code>attn_implementation</code> dans <a href="/docs/transformers/main/fr/main_classes/model#transformers.PreTrainedModel.from_pretrained">from_pretrained()</a> pour instancier un modèle avec une fonction d'attention spécifique.</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> Copié</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>Basculez entre les backends d'attention à l'exécution sans recharger le modèle en utilisant <a href="/docs/transformers/main/fr/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> Copié</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><!---->Kernels<!----></span></h3><!--]--><!----> <p>Téléchargez et chargez les noyaux de calcul compilés directement depuis le <a href="https://huggingface.co/models?other=kernels" rel="nofollow">Hub</a> à l'exécution avec la bibliothèque <a href="https://huggingface.co/docs/kernels/index" rel="nofollow">Kernels</a>. Cela évite les problèmes d'empaquetage liés à des versions de PyTorch ou de CUDA incompatibles.</p> <p>Les noyaux s’enregistrent automatiquement dans <a href="/docs/transformers/main/fr/internal/modeling_utils#transformers.AttentionInterface">AttentionInterface</a> lors de leur détection. Il n’est pas nécessaire d’installer explicitement le package FlashAttention. Demander FlashAttention par son nom bascule également sur le noyau du Hub, voir <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> Copié</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><!---->Gestionnaire de contexte SDPA<!----></span></h3><!--]--><!----> <p>La fonction d’attention à produit scalaire mis à l’échelle (SDPA) de PyTorch sélectionne automatiquement la fonction d’attention la plus rapide pour les backends CUDA. Pour les autres backends, elle utilise par défaut l’implémentation C++ de PyTorch.</p> <p>Forcer SDPA à utiliser une implémentation spécifique avec le gestionnaire de contexte <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> Copié</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><!---->Attention spécifique au backbone<!----></span></h2><!--]--><!----> <p>Les modèles multimodaux utilisent des backbones différents pour chaque modalité. Optimisez les performances en affectant des fonctions d'attention spécifiques à chaque backbone. Certains backbones de vision fonctionnent mieux en fp32, par exemple, ce que FlashAttention ne prend pas en charge.</p> <p>Associez les squelettes de vision à différentes fonctions d'attention à l'aide d'un dictionnaire, tandis que le squelette de texte continue d'utiliser FlashAttention. Les clés de l'implémentation de l'attention doivent correspondre aux noms des sous-configurations.</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> Copié</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>Omettez certains backbones du dictionnaire pour utiliser la fonction d'attention par défaut (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> Copié</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>Définissez la même fonction d’attention pour tous les backbones avec une seule chaîne de caractères.</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> Copié</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>Définissez la fonction d'attention globalement avec une clé vide.</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> Copié</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><!---->Créer une nouvelle fonction d'attention<!----></span></h2><!--]--><!----> <p>Personnalisez ou créez de nouvelles fonctions d'attention en les ajoutant au registre d'attention via <a href="/docs/transformers/main/fr/internal/modeling_utils#transformers.AttentionInterface.register">AttentionInterface.register()</a>. Les modèles utilisent ces fonctions à travers l'argument <code>attn_implementation</code>.</p> <blockquote class="warning"><p>Enregistrez une fonction de masque d'attention correspondante lorsque vous enregistrez une fonction d'attention personnalisée. Si le nom de <code>attn_implementation</code> personnalisé n'est pas enregistré dans <a href="/docs/transformers/main/fr/internal/modeling_utils#transformers.AttentionMaskInterface">AttentionMaskInterface</a>, Transformers ignore la création du masque et transmet <code>attention_mask=None</code> aux couches d'attention. Votre fonction d'attention doit gérer elle-même les contraintes causales, de bourrage, de regroupement ou de fenêtre glissante, sinon ces contraintes peuvent être silencieusement ignorées.</p></blockquote> <p>Cet exemple personnalise la fonction d'attention pour afficher un message pour chaque couche. Il conserve le masque de l'implémentation d'origine en enregistrant <code>masking_utils.sdpa_mask</code> en tant que fonction de masque d'attention.</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> Copié</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>Vous pouvez également ajouter de nouveaux arguments à la fonction d'attention. Les modèles prenant en charge <a href="/docs/transformers/main/fr/internal/modeling_utils#transformers.AttentionInterface">AttentionInterface</a> propagent les kwargs aux couches d'attention et à la fonction d'attention. Passez les arguments en tant que kwargs dans la fonction forward du modèle. Les fonctions d'attention personnalisées doivent respecter cette signature et ce format de retour.</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> Copié</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>Consultez le <a href="https://github.com/huggingface/transformers/tree/main/src/transformers/models" rel="nofollow">code de modélisation</a> d’un modèle pour vérifier les arguments et kwargs qu’il transmet à la fonction d’attention.</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/fr/internal/modeling_utils#transformers.AttentionMaskInterface">AttentionMaskInterface</a> est le registre que les fonctions <a href="#build-an-attention-mask"><code>create_*_mask</code></a> consultent pour convertir un masque dans le format attendu par le backend d'attention actif. FlexAttention a besoin d'un <a href="https://docs.pytorch.org/docs/stable/nn.attention.flex_attention.html#torch.nn.attention.flex_attention.BlockMask" rel="nofollow">BlockMask</a>, SDPA a besoin d'un tenseur 4D et FlashAttention a besoin du masque de padding de base 2D. Enregistrez un backend personnalisé, ou écrasez le formateur d'un backend existant, avec <a href="/docs/transformers/main/fr/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> Copié</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>En l’absence d’un formateur enregistré pour le <code>attn_implementation</code> actif, la création du masque est ignorée et <code>attention_mask=None</code> est transmis aux couches d’attention.</p> <p>Les fonctions enregistrées doivent correspondre à cette signature.</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> Copié</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>L'argument <code>mask_function</code> est un <code>Callable</code> qui imite les fonctions <a href="https://pytorch.org/blog/flexattention/" rel="nofollow">mask_mod</a> de PyTorch. Il prend 4 indices <code>(batch_idx, head_idx, q_idx, kv_idx)</code> et renvoie un booléen indiquant si cette position contribue au calcul de l'attention. C'est la même forme primitive utilisée par <code>or_mask_function</code> et <code>and_mask_function</code> dans <a href="#build-an-attention-mask">Construire un masque d'attention</a>.</p> <blockquote class="tip"><p>Utilisez ce <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/integrations/executorch.py" rel="nofollow">contournement</a> pour torch.export si <code>mask_function</code> échoue à créer un masque.</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><!---->Construire un masque d'attention<!----></span></h2><!--]--><!----> <p>Construisez les masques d’attention à l’aide des fonctions <code>create_*_mask</code> de <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/masking_utils.py#L894" rel="nofollow">transformers.masking_utils</a>. Chaque fonction lit le backend d’attention actif depuis la configuration du modèle, recherche le formateur de masque du backend dans <a href="/docs/transformers/main/fr/internal/modeling_utils#transformers.AttentionMaskInterface">AttentionMaskInterface</a> et renvoie le format attendu par ce backend. Vous n’avez pas besoin d’inverser, d’étendre ou de convertir le masque vous-même.</p> <p>Choisissez la fonction qui correspond au motif d'attention.</p> <table><thead><tr><th>function</th><th>cas d'usage</th></tr></thead><tbody><tr><td><code>create_causal_mask</code></td><td>les modèles uniquement décodeurs où chaque jeton porte attention sur lui-même et sur les jetons précédents</td></tr><tr><td><code>create_bidirectional_mask</code></td><td>les modèles encodeurs, ou l'attention croisée d'un décodeur vers les états de l'encodeur</td></tr><tr><td><code>create_sliding_window_causal_mask</code></td><td>modèles décodeurs avec un motif d'attention à fenêtre glissante</td></tr><tr><td><code>create_chunked_causal_mask</code></td><td>les modèles décodeurs qui découpent la séquence en blocs de taille fixe</td></tr><tr><td><code>create_bidirectional_sliding_window_mask</code></td><td>les modèles encodeurs avec un motif d'attention à fenêtre glissante</td></tr></tbody></table> <blockquote class="warning"><p>Les utilitaires de masque appelables hérités - <code>get_extended_attention_mask</code>, <code>create_extended_attention_mask_for_decoder</code>, <code>invert_attention_mask</code> - émettent un avertissement de non-recommandation et seront supprimés dans une future version. Utilisez à la place les fonctions <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">attention causale</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">auto-attention de l'encodeur</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>Appeler <code>create_causal_mask</code> dans le passage avant d'un décodeur. Transmettre la configuration, les embeddings d'entrée, le <code>attention_mask</code> 2D fourni par l'utilisateur et le cache. La fonction utilise les embeddings pour lire la taille du lot, la longueur des requêtes, le dtype et l'appareil, et utilise le cache pour calculer la longueur des clés.</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> Copié</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>Appeler <code>create_bidirectional_mask</code> pour l'auto-attention de l'encodeur. Supprimer <code>cache</code> car les encodeurs ne mettent pas en 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> Copié</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>Pour l'attention croisée, passez les états de l'encodeur en tant que <code>encoder_hidden_states</code> afin que le masque utilise la longueur des clés et des valeurs de l'encodeur plutôt que la longueur des requêtes du décodeur.</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> Copié</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>Ajoutez des contraintes supplémentaires au masque de base à l'aide des arguments <code>or_mask_function</code> et <code>and_mask_function</code>. Utilisez <code>or_mask_function</code> pour autoriser l'attention sur des positions supplémentaires, et <code>and_mask_function</code> pour restreindre davantage le motif de base. Les deux suivent la signature à 4 indices de <code>mask_function</code> décrite dans <a href="#attentionmaskinterface">AttentionMaskInterface</a>. Elles prennent <code>(batch_idx, head_idx, q_idx, kv_idx)</code> en entrée et renvoient un booléen.</p> <blockquote class="warning"><p><code>or_mask_function</code> et <code>and_mask_function</code> peuvent exprimer n’importe quel motif d’attention, mais ils sont plus lents que les motifs intégrés et ne sont pas compatibles avec ExecuTorch. Le surcoût est le plus notable sur les petits modèles (~200M paramètres), où la création du masque représente une part plus importante du temps de passe avant. N’y recourrez que lorsque les fonctions standard <code>create_*_mask</code> ne peuvent pas exprimer ce dont vous avez besoin.</p></blockquote> <p>Par exemple, superposez une fonction qui retourne <code>True</code> partout sur un masque causal pour le transformer en un masque entièrement bidirectionnel. L’union avec le motif causal permet à chaque jeton de prêter attention à tous les autres jetons.</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> Copié</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>Pendant la génération, <a href="/docs/transformers/main/fr/main_classes/text_generation#transformers.GenerationMixin.generate">generate()</a> construit les masques via <code>create_masks_for_generate</code>, qui achemine l'appel vers le bon <code>create_*_mask</code> en fonction de la configuration du modèle. Surchargez-le dans une classe de modèle pour intégrer une stratégie de masquage personnalisée pour la génération.</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><!---->Passer un masque d'attention 4D personnalisé<!----></span></h2><!--]--><!----> <p>Fournissez votre propre masque 4D lorsque vous avez besoin d’un motif d’attention que les fonctions <code>create_*_mask</code> ne peuvent pas exprimer. Un masque 4D a la forme <code>(batch_size, 1, query_length, kv_length)</code>, où <code>1</code> diffuse le même masque sur toutes les têtes d’attention. Transformers détecte et utilise le masque tel quel, en ignorant <code>create_*_mask</code>.</p> <p>Un masque 4D utilise l'une des deux conventions de valeurs.</p> <table><thead><tr><th>dtype</th><th>attend</th><th>masquer</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>La convention float ajoute le masque aux scores d’attention avant le softmax. Un score plus <code>0.0</code> reste inchangé, donc la position contribue. Un score plus <code>-inf</code> tombe à zéro après le softmax, donc la position est exclue.</p> <blockquote class="important"><p>La convention acceptée dépend du backend d’attention. <code>sdpa</code> accepte un masque booléen ou flottant. <code>eager</code> ajoute le masque aux scores, il n’accepte donc qu’un masque flottant. <code>flash_attention_2</code> et <code>flex_attention</code> consomment leurs propres formats (un masque de padding 2D et un <a href="https://docs.pytorch.org/docs/stable/nn.attention.flex_attention.html#torch.nn.attention.flex_attention.BlockMask" rel="nofollow">BlockMask</a>) et n’acceptent pas de masque 4D brut.</p></blockquote> <p>Une erreur courante consiste à réutiliser la convention <code>1</code>/<code>0</code> d'un masque de padding 2D dans un masque 4D en float. Comme le masque est ajouté aux scores, <code>0.0</code> conserve une position et <code>1.0</code> n'ajoute qu'un petit biais.</p> <p>L'exemple ci-dessous met en contraste un masque incorrect avec un masque correct. Les deux partent du même motif causal <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> Copié</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>Le mauvais masque conserve toutes les positions car <code>0.0</code> est la valeur qui masque, il n’exclut donc jamais quoi que ce soit.</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> Copié</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><!---->Attention bidirectionnelle<!----></span></h2><!--]--><!----> <p>Les modèles uniquement décodeurs utilisent par défaut une attention causale (unidirectionnelle), où chaque jeton ne porte attention qu’à lui-même et aux jetons précédents. Définissez <code>is_causal=False</code> pour passer à une attention bidirectionnelle, où chaque jeton porte attention à tous les autres jetons. Cela permet d’utiliser des modèles uniquement décodeurs comme encodeurs de texte, par exemple pour générer des plongements.</p> <blockquote class="note"><p>Cela ne fonctionne que pour les modèles causaux (décodeurs). Cela ne transforme pas les modèles encodeurs en modèles décodeurs.</p></blockquote> <p>Définissez <code>is_causal=False</code> dans la configuration du modèle pour que l'attention bidirectionnelle soit la valeur par défaut pour chaque passe avant.</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> Copié</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>Passez <code>is_causal</code> dans l'appel forward plutôt que dans la configuration du modèle pour basculer entre une attention causale et une attention bidirectionnelle sans charger le modèle deux fois. Ce paramètre mot-clé écrase temporairement la configuration et est restauré après l'appel.</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> Copié</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:
74.9 kB
·
Xet hash:
fc2a579a0e267779fc555df1224e5b5e6fe7aa1d1342e89230e904a56ae5628c

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