Buckets:
| <meta charset="utf-8" /><meta name="hf:doc:metadata" content="{"title":"Ajouter un modèle avec des transformers modulaires","local":"add-a-model-with-modular-transformers","sections":[{"title":"Mise en œuvre d'un fichier modulaire","local":"implementing-a-modular-file","sections":[{"title":"Configuration","local":"config","sections":[],"depth":3},{"title":"Norme","local":"norm","sections":[],"depth":3},{"title":"Attention","local":"attention","sections":[],"depth":3},{"title":"DecoderLayer","local":"decoderlayer","sections":[],"depth":3},{"title":"Modèle","local":"model","sections":[],"depth":3},{"title":"Tête de modèle","local":"model-head","sections":[],"depth":3},{"title":"Autres classes","local":"other-classes","sections":[],"depth":3},{"title":"Finaliser le fichier","local":"finishing-the-file","sections":[],"depth":3}],"depth":2},{"title":"Générer les fichiers de modélisation","local":"generate-the-modeling-files","sections":[],"depth":2},{"title":"Modèles pour les fichiers modulaires","local":"patterns-for-modular-files","sections":[{"title":"Suppression des attributs","local":"removing-attributes","sections":[],"depth":3},{"title":"Travailler avec super()","local":"working-with-super","sections":[{"title":"Appeler directement une classe grand-mère","local":"call-a-grandparent-class-directly","sections":[],"depth":4},{"title":"super_kwargs","local":"superkwargs","sections":[],"depth":4}],"depth":3},{"title":"Suppression des méthodes inutilisées","local":"deleting-unused-methods","sections":[],"depth":3},{"title":"Écraser des méthodes décorées","local":"overriding-decorated-methods","sections":[],"depth":3},{"title":"Nommage spécial","local":"special-naming","sections":[],"depth":3},{"title":"Docstrings de configuration","local":"config-docstrings","sections":[],"depth":3}],"depth":2},{"title":"Conversion de points de contrôle","local":"checkpoint-conversion","sections":[{"title":"Écrire un script de conversion","local":"write-a-conversion-script","sections":[],"depth":3},{"title":"Cartographie de conversion au moment de l'exécution","local":"runtime-conversion-mapping","sections":[],"depth":3}],"depth":2},{"title":"Étapes suivantes","local":"next-steps","sections":[],"depth":2}],"depth":1}"/> | |
| <link href="/docs/transformers/main/en/_app/immutable/entry/start.DYIO-UII.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/DSYYoqAA.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/BovLmb3z.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/entry/app.D2_KizbC.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/WyYpyc-L.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/DYBfcveH.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.ByO_lNbj.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/ZtBhN-Ei.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/nodes/675.C9W3viMf.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/D-dvW--N.js" rel="modulepreload"> | |
| <!--1rp9gg8--><meta name="hf:doc:metadata" content="{"title":"Add a model with modular transformers","local":"add-a-model-with-modular-transformers","sections":[{"title":"Implementing a modular file","local":"implementing-a-modular-file","sections":[{"title":"Config","local":"config","sections":[],"depth":3},{"title":"Norm","local":"norm","sections":[],"depth":3},{"title":"Attention","local":"attention","sections":[],"depth":3},{"title":"DecoderLayer","local":"decoderlayer","sections":[],"depth":3},{"title":"Model","local":"model","sections":[],"depth":3},{"title":"Model head","local":"model-head","sections":[],"depth":3},{"title":"Other classes","local":"other-classes","sections":[],"depth":3},{"title":"Finishing the file","local":"finishing-the-file","sections":[],"depth":3}],"depth":2},{"title":"Generate the modeling files","local":"generate-the-modeling-files","sections":[],"depth":2},{"title":"Patterns for modular files","local":"patterns-for-modular-files","sections":[{"title":"Removing attributes","local":"removing-attributes","sections":[],"depth":3},{"title":"Working with super()","local":"working-with-super","sections":[{"title":"Call a grandparent class directly","local":"call-a-grandparent-class-directly","sections":[],"depth":4},{"title":"super_kwargs","local":"superkwargs","sections":[],"depth":4}],"depth":3},{"title":"Deleting unused methods","local":"deleting-unused-methods","sections":[],"depth":3},{"title":"Overriding decorated methods","local":"overriding-decorated-methods","sections":[],"depth":3},{"title":"Special naming","local":"special-naming","sections":[],"depth":3},{"title":"Config docstrings","local":"config-docstrings","sections":[],"depth":3}],"depth":2},{"title":"Checkpoint conversion","local":"checkpoint-conversion","sections":[{"title":"Write a conversion script","local":"write-a-conversion-script","sections":[],"depth":3},{"title":"Runtime conversion mapping","local":"runtime-conversion-mapping","sections":[],"depth":3}],"depth":2},{"title":"Next steps","local":"next-steps","sections":[],"depth":2}],"depth":1}"/><!----> | |
| <link href="/docs/transformers/main/en/_app/immutable/assets/0.tn0RQdqM.css" rel="modulepreload"> <!--[--><!--[0--><!--[--><!--[0--><!--[--><p></p> <div class="items-center shrink-0 min-w-[100px] max-sm:min-w-[50px] justify-end ml-auto flex" style="float: inline-end; margin-inline-start: 10px; display: inline-flex; position: relative; z-index: 10;"><div dir="ltr" class="inline-flex rounded-md max-sm:rounded-sm"><button class="inline-flex items-center gap-1 h-7 max-sm:h-7 px-2 max-sm:px-1.5 text-sm font-medium text-gray-800 border border-r-0 rounded-l-md max-sm:rounded-l-sm border-gray-200 bg-white hover:shadow-inner dark:border-gray-850 dark:bg-gray-950 dark:text-gray-200 dark:hover:bg-gray-800" aria-live="polite"><span class="inline-flex items-center justify-center rounded-md p-0.5 max-sm:p-0 hover:text-gray-800 dark:hover:text-gray-200"><svg class="sm:size-3.5 size-3" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----></span> <span dir="auto">Copy page</span></button> <button class="inline-flex items-center justify-center w-6 max-sm:w-5 h-7 max-sm:h-7 disabled:pointer-events-none text-sm text-gray-500 hover:text-gray-700 dark:hover:text-white rounded-r-md max-sm:rounded-r-sm border border-l transition border-gray-200 bg-white hover:shadow-inner dark:border-gray-850 dark:bg-gray-950 dark:text-gray-200 dark:hover:bg-gray-800" aria-haspopup="menu" aria-expanded="false" aria-label="Open copy menu"><svg class="transition-transform text-gray-400 overflow-visible sm:size-3.5 size-3 rotate-0" width="1em" height="1em" viewBox="0 0 12 7" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 1L6 6L11 1" stroke="currentColor"></path></svg><!----></button></div> <!--[-1--><!--]--></div><!----> <!--[0--><h1 class="relative group"><a id="add-a-model-with-modular-transformers" 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-a-model-with-modular-transformers"><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><!---->Ajouter un modèle avec des transformers modulaires<!----></span></h1><!--]--><!----> <p>Modular transformers réduit le code nécessaire pour ajouter un modèle en permettant les imports et l'héritage, contrairement à la politique <a href="https://huggingface.co/blog/transformers-design-philosophy" rel="nofollow">un modèle, un seul fichier</a>. Au lieu de répéter les composants du modèle dans plusieurs fichiers, ajoutez un fichier <em>modulaire</em> à votre dossier de modèle et héritez des classes existantes.</p> <p>Un convertisseur génère des fichiers autonomes à partir du fichier modulaire. Les utilisateurs obtiennent la même interface monofichier qu’ils connaissent déjà.</p> <blockquote class="note"><p>Modular transformers n’est pas destiné à remplacer le <a href="./add_new_model">code de modélisation legacy</a>. Si votre modèle n’est pas basé sur un modèle existant, ajoutez manuellement un fichier <code>modeling.py</code>. Il en va de même pour les fichiers de configuration, de tokenisation ou de traitement qui ne peuvent pas hériter proprement d’un fichier similaire.</p> <p>Il n’existe pas non plus d’ordre unique à respecter. Certains contributeurs rédigent d’abord le fichier modulaire et le génèrent à partir de celui-ci. D’autres commencent par un <code>modeling.py</code> écrit à la main, puis le refactorisent en fichier modulaire par la suite. Les deux approches fonctionnent.</p></blockquote> <!--[1--><h2 class="relative group"><a id="implementing-a-modular-file" 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="#implementing-a-modular-file"><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><!---->Mise en œuvre d'un fichier modulaire<!----></span></h2><!--]--><!----> <p>Commencez par trouver un modèle dans Transformers similaire au vôtre. De bons points de départ sont <a href="./model_doc/mistral">Mistral</a>, <a href="./model_doc/qwen2">Qwen2</a>, <a href="./model_doc/cohere">Cohere</a> et <a href="./model_doc/cohere2">Cohere2</a>, ainsi que <a href="./model_doc/llama">Llama</a>. Le tableau ci-dessous associe les composants courants aux modèles dont vous pouvez hériter.</p> <table><thead><tr><th>Composant</th><th>Modèle</th></tr></thead><tbody><tr><td>Mélange d'experts</td><td>Mixtral ou Qwen2-MoE</td></tr><tr><td>Incrustation rotative entrelacée (et/ou partielle)</td><td>GLM, Phi</td></tr><tr><td>Modèles d'espace d'état</td><td>Jamba, Bamba, Zamba, Mamba2</td></tr><tr><td>États cachés récurrents</td><td>Gemma2</td></tr><tr><td>Motifs d'attention par fenêtre glissante / attention complète par couche</td><td>Gemma2, Cohere2</td></tr><tr><td>Clipping QKV</td><td>Olmo</td></tr><tr><td>Normalisation QK</td><td>Olmo2, Cohere</td></tr><tr><td>QKV fusionné (non recommandé)</td><td>Phi3</td></tr></tbody></table> <blockquote class="tip"><p>Utilisez l’outil <a href="https://huggingface.co/spaces/Molbap/modular-detector-v2" rel="nofollow">modular-detector-v2</a> pour trouver des implémentations existantes dont vous pouvez hériter. Collez un extrait de code et il renvoie les méthodes les plus similaires déjà présentes dans Transformers, afin que vous puissiez identifier la meilleure classe parente avant de commencer à écrire.</p></blockquote> <p>Ne modifiez pas un modèle existant uniquement pour que l’héritage fonctionne avec votre nouveau modèle. Si le renommage ou la sous-classement d’une classe parente est trop contraignant, copiez directement le code pertinent à la place.</p> <p>Créez <code>src/transformers/models/<name>/modular_<name>.py</code>, où <code><name></code> correspond au nom du répertoire du modèle en snake_case. Cette section vous guide dans l’implémentation de <a href="./model_doc/olmo2">Olmo2</a> à partir de <a href="./model_doc/olmo">Olmo</a> avec l’approche modulaire (reportez-vous au fichier <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/models/olmo2/modular_olmo2.py" rel="nofollow">modular_olmo2.py</a> d’origine).</p> <!--[2--><h3 class="relative group"><a id="config" 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="#config"><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><!---->Configuration<!----></span></h3><!--]--><!----> <p>Il y a deux points où <a href="/docs/transformers/main/fr/model_doc/olmo2#transformers.Olmo2Config">Olmo2Config</a> diffère de <a href="/docs/transformers/main/fr/model_doc/olmo#transformers.OlmoConfig">OlmoConfig</a>.</p> <ol><li>Un nouvel argument, <code>rms_norm_eps</code>, a été ajouté.</li> <li>L'argument <code>clip_qkv</code> n'est plus utilisé.</li></ol> <p>Déclarez les nouveaux arguments sous forme d’annotations de type au niveau de la classe, avec une valeur par défaut. Pour les arguments supprimés, affectez <code>AttributeError()</code> afin de supprimer l’attribut hérité dans le fichier généré (voir <a href="#removing-attributes">Suppression d’attributs</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-diff "><!----><span class="hljs-deletion">- @auto_docstring(checkpoint="allenai/OLMo-7B-hf")</span> | |
| <span class="hljs-addition">+ @auto_docstring(checkpoint="allenai/Olmo2-7B-1124-hf")</span> | |
| <span class="hljs-addition">+ @strict</span> | |
| <span class="hljs-deletion">- class OlmoConfig(PreTrainedConfig):</span> | |
| <span class="hljs-addition">+ class Olmo2Config(OlmoConfig):</span> | |
| ... | |
| <span class="hljs-deletion">- model_type = "olmo"</span> | |
| <span class="hljs-addition">+ model_type = "olmo2"</span> | |
| ... | |
| <span class="hljs-addition">+ rms_norm_eps: float = 1e-5</span> | |
| <span class="hljs-deletion">- clip_qkv: float | None = None</span> | |
| <span class="hljs-addition">+ clip_qkv = AttributeError()</span><!----></pre></div><!----> <p><code>@auto_docstring</code> génère automatiquement la documentation standard des arguments (voir le guide <a href="./auto_docstring">@auto_docstring</a>). <code>@strict</code> rejette les mots-clés inconnus lors de l'instantiation, ce qui permet de détecter précocement les fautes de frappe et les arguments obsolètes. Ajoutez les deux à chaque classe de configuration, car les décorateurs ne sont pas hérités de la classe parente. Déclarez-les explicitement, même si la configuration parente les possède déjà.</p> <p>Pour définir un attribut dérivé ou gérer la logique de rétrocompatibilité, utilisez <code>__post_init__</code> plutôt que <code>__init__</code>. Par exemple, Cohere2 calcule <code>head_dim</code> et dérive <code>layer_types</code> lors de l’initialisation.</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">def</span> <span class="hljs-title function_">__post_init__</span>(<span class="hljs-params">self, **kwargs</span>): | |
| <span class="hljs-keyword">if</span> <span class="hljs-variable language_">self</span>.num_key_value_heads <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>: | |
| <span class="hljs-variable language_">self</span>.num_key_value_heads = <span class="hljs-variable language_">self</span>.num_attention_heads | |
| <span class="hljs-variable language_">self</span>.head_dim = <span class="hljs-variable language_">self</span>.hidden_size // <span class="hljs-variable language_">self</span>.num_attention_heads | |
| <span class="hljs-built_in">super</span>().__post_init__(**kwargs)<!----></pre></div><!----> <p>Pour les modèles prenant en charge le parallélisme de tenseurs ou de pipeline, définissez <code>base_model_tp_plan</code> et <code>base_model_pp_plan</code> sous forme de dictionnaires au niveau de la classe dans la configuration. Les deux dictionnaires définissent comment fractionner le modèle sur les différents appareils. Consultez les configurations existantes telles que <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/models/olmo2/modular_olmo2.py" rel="nofollow">Olmo2</a> ou <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/models/cohere2/modular_cohere2.py" rel="nofollow">Cohere2</a> pour des exemples.</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">class</span> <span class="hljs-title class_">MyNewModelConfig</span>(<span class="hljs-title class_ inherited__">PreTrainedConfig</span>): | |
| model_type = <span class="hljs-string">"my_new_model"</span> | |
| <span class="hljs-comment"># Tensor parallelism: maps layer name patterns to sharding strategies.</span> | |
| <span class="hljs-comment"># Use "colwise" / "rowwise" for standard sharding, or the "gather_output" /</span> | |
| <span class="hljs-comment"># "split_input" variants when an extra op (e.g. a QK norm) prevents fusing.</span> | |
| base_model_tp_plan = { | |
| <span class="hljs-string">"layers.*.self_attn.q_proj"</span>: <span class="hljs-string">"colwise"</span>, | |
| <span class="hljs-string">"layers.*.self_attn.k_proj"</span>: <span class="hljs-string">"colwise"</span>, | |
| <span class="hljs-string">"layers.*.self_attn.v_proj"</span>: <span class="hljs-string">"colwise"</span>, | |
| <span class="hljs-string">"layers.*.self_attn.o_proj"</span>: <span class="hljs-string">"rowwise"</span>, | |
| <span class="hljs-string">"layers.*.mlp.gate_proj"</span>: <span class="hljs-string">"colwise"</span>, | |
| <span class="hljs-string">"layers.*.mlp.up_proj"</span>: <span class="hljs-string">"colwise"</span>, | |
| <span class="hljs-string">"layers.*.mlp.down_proj"</span>: <span class="hljs-string">"rowwise"</span>, | |
| } | |
| <span class="hljs-comment"># Pipeline parallelism: maps submodule names to their (input, output) tensor names.</span> | |
| base_model_pp_plan = { | |
| <span class="hljs-string">"embed_tokens"</span>: ([<span class="hljs-string">"input_ids"</span>], [<span class="hljs-string">"inputs_embeds"</span>]), | |
| <span class="hljs-string">"layers"</span>: ([<span class="hljs-string">"hidden_states"</span>, <span class="hljs-string">"attention_mask"</span>], [<span class="hljs-string">"hidden_states"</span>]), | |
| <span class="hljs-string">"norm"</span>: ([<span class="hljs-string">"hidden_states"</span>], [<span class="hljs-string">"hidden_states"</span>]), | |
| }<!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="norm" 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="#norm"><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><!---->Norme<!----></span></h3><!--]--><!----> <p>Pour copier une classe parente sans modification, héritez avec <code>pass</code>. L’outil de linter copie le contenu de la classe parente et renomme toutes les références pour correspondre au nouveau modèle.</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> ..olmo.modeling_olmo <span class="hljs-keyword">import</span> OlmoRotaryEmbedding | |
| <span class="hljs-keyword">class</span> <span class="hljs-title class_">Olmo2RotaryEmbedding</span>(<span class="hljs-title class_ inherited__">OlmoRotaryEmbedding</span>): | |
| <span class="hljs-keyword">pass</span><!----></pre></div><!----> <p>Pour modifier un comportement spécifique, héritez et n'écrasez que ce qui diffère. <code>Olmo2RMSNorm</code> diffère de <code>LlamaRMSNorm</code> sur une seule ligne. La multiplication a lieu <em>avant</em> le retour au type de données d'entrée, et non aprè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-diff "><!----> from ..llama.modeling_llama import LlamaRMSNorm | |
| class Olmo2RMSNorm(LlamaRMSNorm): | |
| def forward(self, hidden_states): | |
| input_dtype = hidden_states.dtype | |
| hidden_states = hidden_states.to(torch.float32) | |
| variance = hidden_states.pow(2).mean(-1, keepdim=True) | |
| hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) | |
| <span class="hljs-deletion">- return self.weight * hidden_states.to(input_dtype)</span> | |
| <span class="hljs-addition">+ return (self.weight * hidden_states).to(input_dtype)</span><!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="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="#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<!----></span></h3><!--]--><!----> <p>L’attention d’Olmo2 est identique à celle d’Olmo, sauf qu’elle applique <code>RMSNorm</code> aux requêtes et aux clés, et supprime le clipping de qkv. <code>super().__init__(...)</code> copie le corps de la classe parente et ajoute les deux nouvelles lignes de normalisation. La méthode <code>forward</code> est entièrement redéfinie car les requêtes et les clés passent désormais par des normalisations avant la projection. L’outil de vérification de code intègre également dans le fichier généré toutes les fonctions importées, y compris <code>apply_rotary_pos_emb</code>, <code>eager_attention_forward</code> et leurs dépendances.</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-diff "><!----> class Olmo2Attention(OlmoAttention): | |
| def __init__(self, config: Olmo2Config, layer_idx: int | None = None): | |
| super().__init__(config, layer_idx=layer_idx) | |
| <span class="hljs-addition">+ self.q_norm = Olmo2RMSNorm(config.num_attention_heads * self.head_dim, config.rms_norm_eps)</span> | |
| <span class="hljs-addition">+ self.k_norm = Olmo2RMSNorm(config.num_key_value_heads * self.head_dim, config.rms_norm_eps)</span> | |
| def forward(self, ...): | |
| ... | |
| <span class="hljs-deletion">- query_states = self.q_proj(hidden_states)</span> | |
| <span class="hljs-deletion">- key_states = self.k_proj(hidden_states)</span> | |
| <span class="hljs-addition">+ query_states = self.q_norm(self.q_proj(hidden_states))</span> | |
| <span class="hljs-addition">+ key_states = self.k_norm(self.k_proj(hidden_states))</span> | |
| value_states = self.v_proj(hidden_states) | |
| <span class="hljs-deletion">- if self.config.clip_qkv is not None:</span> | |
| <span class="hljs-deletion">- query_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)</span> | |
| <span class="hljs-deletion">- key_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)</span> | |
| <span class="hljs-deletion">- value_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)</span> | |
| <span class="hljs-deletion">-</span> | |
| ...<!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="decoderlayer" 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="#decoderlayer"><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><!---->DecoderLayer<!----></span></h3><!--]--><!----> <p>Après <code>super().__init__(...)</code>, écrasez les attributs de normalisation avec des instances de <code>Olmo2RMSNorm</code> et réaffectez <code>self.self_attn</code> à la nouvelle classe <code>Olmo2Attention</code>. La ligne <code>del self.input_layernorm</code> supprime l’assignation de <code>input_layernorm</code> de la classe parente, car Olmo2 applique la normalisation <em>après</em> l’attention plutôt qu’avant. Consultez <a href="#removing-attributes">Suppression d’attributs</a> pour plus de détails sur ce que <code>del</code> supprime et ce qu’il ne supprime pas.</p> <p>Le <code>forward</code> est réécrit pour refléter le placement de la normalisation post-attention. Une réécriture du <code>forward</code> n'est nécessaire que lorsqu'un attribut est renommé, et non lorsque seul son type change.</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-diff "><!----> class Olmo2DecoderLayer(OlmoDecoderLayer): | |
| def __init__(self, config: Olmo2Config, layer_idx: int): | |
| super().__init__(config, layer_idx=layer_idx) | |
| <span class="hljs-deletion">- self.self_attn = OlmoAttention(config=config, layer_idx=layer_idx)</span> | |
| <span class="hljs-deletion">- self.input_layernorm = OlmoLayerNorm(config.hidden_size)</span> | |
| <span class="hljs-deletion">- self.post_attention_layernorm = OlmoLayerNorm(config.hidden_size)</span> | |
| <span class="hljs-addition">+ self.self_attn = Olmo2Attention(config=config, layer_idx=layer_idx)</span> | |
| <span class="hljs-addition">+ del self.input_layernorm</span> | |
| <span class="hljs-addition">+ self.post_attention_layernorm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)</span> | |
| <span class="hljs-addition">+ self.post_feedforward_layernorm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)</span> | |
| def forward(self, ...): | |
| residual = hidden_states | |
| <span class="hljs-deletion">- hidden_states = self.input_layernorm(hidden_states)</span> | |
| # Self Attention | |
| hidden_states, _ = self.self_attn(...) | |
| <span class="hljs-deletion">- hidden_states = residual + hidden_states</span> | |
| <span class="hljs-addition">+ hidden_states = self.post_attention_layernorm(hidden_states)</span> | |
| <span class="hljs-addition">+ hidden_states = residual + hidden_states</span> | |
| # Fully Connected | |
| residual = hidden_states | |
| <span class="hljs-deletion">- hidden_states = self.post_attention_layernorm(hidden_states)</span> | |
| hidden_states = self.mlp(hidden_states) | |
| <span class="hljs-deletion">- hidden_states = residual + hidden_states</span> | |
| <span class="hljs-addition">+ hidden_states = self.post_feedforward_layernorm(hidden_states)</span> | |
| <span class="hljs-addition">+ hidden_states = residual + hidden_states</span> | |
| return hidden_states<!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="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="#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><!---->Modèle<!----></span></h3><!--]--><!----> <p>Seul le type de <code>self.norm</code> change ici. La méthode <code>forward</code> est identique à celle de la classe parente, le linter la reprend donc automatiquement.</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-diff "><!----> class Olmo2Model(OlmoModel): | |
| def __init__(self, config: Olmo2Config): | |
| super().__init__(config) | |
| <span class="hljs-deletion">- self.layers = nn.ModuleList(</span> | |
| <span class="hljs-deletion">- [OlmoDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]</span> | |
| <span class="hljs-deletion">- )</span> | |
| <span class="hljs-deletion">- self.norm = OlmoLayerNorm(config.hidden_size)</span> | |
| <span class="hljs-addition">+ self.norm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)</span> | |
| <span class="hljs-addition">+ self.layers = nn.ModuleList(</span> | |
| <span class="hljs-addition">+ [Olmo2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]</span> | |
| <span class="hljs-addition">+ )</span><!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="model-head" 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="#model-head"><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><!---->Tête de modèle<!----></span></h3><!--]--><!----> <p>La logique est identique à celle de <a href="/docs/transformers/main/fr/model_doc/olmo#transformers.OlmoForCausalLM">OlmoForCausalLM</a>, aucune modification n'est donc nécessaire.</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> ..olmo.modeling_olmo <span class="hljs-keyword">import</span> OlmoForCausalLM | |
| <span class="hljs-keyword">class</span> <span class="hljs-title class_">Olmo2ForCausalLM</span>(<span class="hljs-title class_ inherited__">OlmoForCausalLM</span>): | |
| <span class="hljs-keyword">pass</span><!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="other-classes" 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="#other-classes"><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><!---->Autres classes<!----></span></h3><!--]--><!----> <p>Le fichier <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/models/olmo2/modeling_olmo2.py" rel="nofollow">modeling_olmo2.py</a> généré par le linter contient également des classes (<code>Olmo2MLP</code>, <code>Olmo2RotaryEmbedding</code>, <code>Olmo2PreTrainedModel</code>) qui n’étaient pas explicitement définies dans <code>modular_olmo2.py</code>.</p> <p>Le linter importe toute classe dont une classe héritée dépend, à moins que vous ne la redéfinissiez explicitement. Les fonctions importées comme <code>apply_rotary_pos_emb</code> suivent la même règle.</p> <p>Par exemple, <code>OlmoDecoderLayer</code> possède <code>self.mlp = OlmoMLP(config)</code>. <code>Olmo2MLP</code> n’étant jamais défini dans le fichier modulaire, le linter le crée automatiquement, ce qui équivaut à utiliser <code>pass</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">from</span> ..olmo.modeling_olmo <span class="hljs-keyword">import</span> OlmoMLP | |
| <span class="hljs-keyword">class</span> <span class="hljs-title class_">Olmo2MLP</span>(<span class="hljs-title class_ inherited__">OlmoMLP</span>): | |
| <span class="hljs-keyword">pass</span><!----></pre></div><!----> <p>Si vous souhaitez que <code>Olmo2MLP</code> hérite d'un autre modèle, soyez explicite.</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-comment"># switch to Mistral definition</span> | |
| <span class="hljs-keyword">from</span> ..mistral.modeling_mistral <span class="hljs-keyword">import</span> MistralMLP | |
| <span class="hljs-keyword">class</span> <span class="hljs-title class_">Olmo2MLP</span>(<span class="hljs-title class_ inherited__">MistralMLP</span>): | |
| <span class="hljs-keyword">pass</span><!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="finishing-the-file" 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="#finishing-the-file"><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><!---->Finaliser le fichier<!----></span></h3><!--]--><!----> <p>Chaque fichier modulaire doit déclarer un <code>logger</code> et une liste <code>__all__</code> au niveau du module.</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 "><!---->logger = logging.get_logger(__name__) | |
| __all__ = [ | |
| <span class="hljs-string">"Olmo2Config"</span>, | |
| <span class="hljs-string">"Olmo2ForCausalLM"</span>, | |
| <span class="hljs-string">"Olmo2Model"</span>, | |
| <span class="hljs-string">"Olmo2PreTrainedModel"</span>, | |
| ]<!----></pre></div><!----> <p><code>__all__</code> doit lister chaque classe publique du fichier. Le convertisseur et les imports en aval en dépendent. Une classe absente de <code>__all__</code> ne sera pas exportée correctement.</p> <!--[1--><h2 class="relative group"><a id="generate-the-modeling-files" 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="#generate-the-modeling-files"><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><!---->Générer les fichiers de modélisation<!----></span></h2><!--]--><!----> <p>Le script <code>modular_model_converter.py</code> génère des fichiers autonomes <code>modeling.py</code>, <code>configuration.py</code> et autres à partir de votre fichier modulaire. Pour chaque classe héritée, il copie le corps de la classe parente dans la classe enfant, renomme toutes les références pour correspondre au nouveau modèle et intègre les fonctions ou classes auxiliaires dont ces classes parentes dépendent.</p> <p>Les fichiers de sortie ne contiennent ni importation inter-modèles ni héritage depuis d’autres répertoires de modèles. L’outil de vérification aplatit l’héritage sur un seul niveau. Si <code>Olmo2Attention</code> hérite de <code>OlmoAttention</code>, la classe <code>Olmo2Attention</code> générée est entièrement autonome. En revanche, si <code>OlmoAttention</code> héritait elle-même d’une autre classe, l’outil de vérification n’intègre pas ce grand-parent.</p> <p>Exécutez la commande ci-dessous pour générer des fichiers à partir d'un fichier modulaire.</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-bash "><!---->python utils/modular_model_converter.py your_model<!----></pre></div><!----> <p>Ne modifiez jamais directement les fichiers générés, car toute modification sera écrasée lors de l'exécution suivante.</p> <!--[1--><h2 class="relative group"><a id="patterns-for-modular-files" 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="#patterns-for-modular-files"><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><!---->Modèles pour les fichiers modulaires<!----></span></h2><!--]--><!----> <p>Les sections ci-dessous documentent les schémas d’utilisation courants, tels que la suppression d’attributs ou la réécriture de méthodes décorées, lors du travail avec un fichier modulaire.</p> <!--[2--><h3 class="relative group"><a id="removing-attributes" 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="#removing-attributes"><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><!---->Suppression des attributs<!----></span></h3><!--]--><!----> <p>La suppression d'un attribut hérité dépend de savoir si vous travaillez avec une classe de configuration ou un sous-ensemble de <code>nn.Module</code>.</p> <p>Pour une classe de configuration, affectez <code>AttributeError()</code> à l'attribut au niveau de la classe.</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">class</span> <span class="hljs-title class_">MyNewConfig</span>(<span class="hljs-title class_ inherited__">ParentConfig</span>): | |
| removed_attr = AttributeError()<!----></pre></div><!----> <p>Le linter supprime entièrement la déclaration de l’attribut du fichier de configuration généré. Les classes de configuration utilisent une structure de type dataclass sans <code>__init__</code>, de sorte qu’assigner <code>AttributeError()</code> au niveau de la classe est la bonne approche.</p> <p>Pour une sous-classe de <code>nn.Module</code>, utilisez <code>del self.attribute</code> après <code>super().__init__(...)</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">class</span> <span class="hljs-title class_">MyNewModel</span>(<span class="hljs-title class_ inherited__">ParentModel</span>): | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, config: MyNewConfig</span>): | |
| <span class="hljs-built_in">super</span>().__init__(config) | |
| <span class="hljs-keyword">del</span> <span class="hljs-variable language_">self</span>.attribute<!----></pre></div><!----> <p><code>del self.attribute</code> supprime uniquement la ligne d’assignation <code>self.attribute = ...</code> du corps du parent copié. Elle ne supprime pas les autres lignes qui référencent <code>self.attribute</code>. Si la méthode <code>forward</code> du parent ou d’autres méthodes référencent également cet attribut, il faut surcharger ces méthodes aussi.</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">class</span> <span class="hljs-title class_">DummyModel</span>(nn.Module): | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, config: DummyConfig</span>): | |
| <span class="hljs-built_in">super</span>().__init__() | |
| <span class="hljs-variable language_">self</span>.attribute = config.attribute | |
| <span class="hljs-keyword">if</span> <span class="hljs-variable language_">self</span>.attribute: | |
| <span class="hljs-comment"># do more stuff with `self.attribute` here</span> | |
| ... | |
| <span class="hljs-keyword">class</span> <span class="hljs-title class_">MyNewDummyModel</span>(<span class="hljs-title class_ inherited__">DummyModel</span>): | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, config: MyNewDummyConfig</span>): | |
| <span class="hljs-built_in">super</span>().__init__(config) | |
| <span class="hljs-keyword">del</span> <span class="hljs-variable language_">self</span>.attribute | |
| <span class="hljs-comment"># 'self.attribute = config.attribute' is removed, but the 'if self.attribute:' block remains.</span> | |
| <span class="hljs-comment"># Override forward() or any other method that references self.attribute.</span><!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="working-with-super" 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="#working-with-super"><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><!---->Travailler avec super()<!----></span></h3><!--]--><!----> <p><code>super().__init__(config)</code> indique au convertisseur de copier le corps de la classe parente dans la classe enfant. Deux modèles permettent de remplacer ce comportement.</p> <ul><li>Appelez directement une classe parente spécifique lorsque vous avez besoin que la sortie générée appelle un grand-parent (<code>nn.Module.__init__</code>) plutôt que la classe parente modulaire.</li> <li>Utilisez <code>**super_kwargs</code> pour hériter de la signature complète d’une méthode parente tout en ajoutant une docstring personnalisée ou en remplaçant un décorateur.</li></ul> <!--[3--><h4 class="relative group"><a id="call-a-grandparent-class-directly" 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="#call-a-grandparent-class-directly"><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><!---->Appeler directement une classe grand-mère<!----></span></h4><!--]--><!----> <p>Soyez explicite sur la classe que vous appelez lorsque vous avez besoin de <code>super()</code> pour cibler le parent de la classe générée plutôt que le parent modulaire. L’exemple ci-dessous appelle directement <code>nn.Module.__init__(self)</code>. <code>DummyModule</code> est lui-même un <code>nn.Module</code>, de sorte que le convertisseur l’écrit sous la forme <code>super().__init__()</code> dans la classe générée <code>MyNewDummyModule</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">class</span> <span class="hljs-title class_">MyNewDummyModule</span>(<span class="hljs-title class_ inherited__">DummyModule</span>): | <span class="hljs-keyword">class</span> <span class="hljs-title class_">MyNewDummyModule</span>(nn.Module): | |
| | | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self</span>): | <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self</span>): | |
| nn.Module.__init__(<span class="hljs-variable language_">self</span>) | <span class="hljs-built_in">super</span>().__init__() | |
| <span class="hljs-variable language_">self</span>.foo = config.foo | <span class="hljs-variable language_">self</span>.foo = config.foo | |
| ... | ...<!----></pre></div><!----> <!--[3--><h4 class="relative group"><a id="superkwargs" 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="#superkwargs"><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><!---->super_kwargs<!----></span></h4><!--]--><!----> <p>Utilisez <code>**super_kwargs</code> pour hériter de la signature complète d’une méthode parente tout en ajoutant une docstring personnalisée ou en remplaçant un décorateur. Dans la signature redéfinie, il indique au linter de déployer tous les arguments de la méthode parente dans la sortie générée.</p> <p>L'utilisation la plus courante consiste à ajouter une docstring spécifique au modèle, par exemple pour documenter l'argument <code>labels</code>, sans réécrire la signature complète.</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-comment"># modular_gemma.py</span> | |
| <span class="hljs-keyword">class</span> <span class="hljs-title class_">GemmaForCausalLM</span>(<span class="hljs-title class_ inherited__">LlamaForCausalLM</span>): | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">forward</span>(<span class="hljs-params">**super_kwargs</span>): | |
| <span class="hljs-string">r""" | |
| Example: | |
| ```python | |
| >>> from transformers import AutoTokenizer, GemmaForCausalLM | |
| >>> model = GemmaForCausalLM.from_pretrained("google/gemma-7b") | |
| ... | |
| ```"""</span> | |
| <span class="hljs-keyword">return</span> <span class="hljs-built_in">super</span>().forward(**super_kwargs)<!----></pre></div><!----> <p>La méthode <code>GemmaForCausalLM.forward</code> générée possède la signature complète de <code>LlamaForCausalLM</code>, sans copie manuelle nécessaire.</p> <p><code>**super_kwargs</code> est un raccourci destiné aux cas de niche. Si vous modifiez le comportement, écrivez plutôt la signature complète.</p> <!--[2--><h3 class="relative group"><a id="deleting-unused-methods" 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="#deleting-unused-methods"><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><!---->Suppression des méthodes inutilisées<!----></span></h3><!--]--><!----> <p>Supprimez une méthode parente en la surchargeant avec une instruction <code>raise AttributeError("")</code>. L'outil de linting supprime la méthode du fichier généré.</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">class</span> <span class="hljs-title class_">GemmaTokenizer</span>(<span class="hljs-title class_ inherited__">LlamaTokenizer</span>): | |
| ... | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">get_spm_processor</span>(<span class="hljs-params">self</span>): | |
| <span class="hljs-keyword">raise</span> AttributeError(<span class="hljs-string">"Not needed for Gemma"</span>) | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">unk_token_length</span>(<span class="hljs-params">self</span>): | |
| <span class="hljs-keyword">raise</span> AttributeError(<span class="hljs-string">"Not needed for Gemma"</span>)<!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="overriding-decorated-methods" 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="#overriding-decorated-methods"><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><!---->Écraser des méthodes décorées<!----></span></h3><!--]--><!----> <p>Lorsque vous écrasez une méthode parente décorée, le décorateur de la méthode parente est automatiquement repris. Si vous ajoutez votre propre décorateur, il remplace celui de la méthode parente.</p> <p>Deux décorateurs apparaissent dans toute la bibliothèque, l'un pour <a href="./model_output_tracing">capturer les sorties intermédiaires du modèle</a> et l'autre pour <a href="./auto_docstring">générer automatiquement les docstrings</a>.</p> <p>Dans l’exemple ci-dessous, une sous-classe redéfinit une méthode parente décorée sans ajouter son propre décorateur. Le décorateur de la classe parente est conservé.</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">class</span> <span class="hljs-title class_">NewModel</span>(<span class="hljs-title class_ inherited__">DummyModel</span>): | <span class="hljs-keyword">class</span> <span class="hljs-title class_">NewModel</span>(nn.Module): | |
| ... | ... | |
| | | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">forward</span>(<span class="hljs-params">...</span>): | @decorator(...) | |
| ... | <span class="hljs-keyword">def</span> <span class="hljs-title function_">forward</span>(<span class="hljs-params">...</span>): | |
| | ...<!----></pre></div><!----> <p>Si vous ajoutez un nouveau décorateur, votre décorateur remplace celui du parent.</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">class</span> <span class="hljs-title class_">NewModel</span>(<span class="hljs-title class_ inherited__">DummyModel</span>): | <span class="hljs-keyword">class</span> <span class="hljs-title class_">NewModel</span>(nn.Module): | |
| ... | ... | |
| | | |
| <span class="hljs-meta"> @my_new_decorator(<span class="hljs-params">...</span>) | @my_new_decorator(<span class="hljs-params">...</span>)</span> | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">forward</span>(<span class="hljs-params">...</span>): | <span class="hljs-keyword">def</span> <span class="hljs-title function_">forward</span>(<span class="hljs-params">...</span>): | |
| ... | ...<!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="special-naming" 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="#special-naming"><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><!---->Nommage spécial<!----></span></h3><!--]--><!----> <p>Le linter renomme automatiquement tout lors de l'héritage d'une classe. Utilisez le même préfixe de nom de classe pour toutes les classes d'un même fichier.</p> <p>Évitez de mélanger des préfixes comme dans l’exemple ci-dessous. <code>MyModelIncredibleMLP</code> viole les conventions de nommage, et le linter ne saura pas s’il doit utiliser <code>MyModelIncredible</code> ou <code>MyModel</code> lors du renommage des dépendances de plus haut niveau.</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">class</span> <span class="hljs-title class_">MyModelIncredibleMLP</span>(<span class="hljs-title class_ inherited__">LlamaMLP</span>): | |
| ... | |
| <span class="hljs-keyword">class</span> <span class="hljs-title class_">MyModelDecoderLayer</span>(<span class="hljs-title class_ inherited__">LlamaDecoderLayer</span>): | |
| ...<!----></pre></div><!----> <p>En l'absence de <a href="#other-classes">dépendances implicites</a>, vous pouvez renommer une seule classe localement. Redéfinissez explicitement chaque autre mention de cette classe avec le nouveau motif de nom. Sinon, le linter ajoute une classe <code>MyModelMLP</code> indésirable à côté de <code>MyModelIncredibleMLP</code>.</p> <p>Le linter émet un avertissement lorsqu'il détecte un préfixe ambigu.</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 "><!---->We detected multiple prefix names when inheriting from transformers.models.llama.modeling_llama: ('Emu3Text', 'Emu3'). We will only use the most used 'Emu3' prefix when grabbing args and dependencies. Make sure to subclass the intermediate classes with the prefix you want (if different from 'Emu3') or use a single prefix in all the modular (best).<!----></pre></div><!----> <p>Les préfixes ambigus sont les plus fréquents dans les modèles multimodaux, où les noms de classes incluent un qualificatif de modalité tel que <code>Text</code>. Pour attribuer un préfixe spécifique à une dépendance, renommez-la explicitement à l'aide d'un <code>pass</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">class</span> <span class="hljs-title class_">Emu3TextMLP</span>(<span class="hljs-title class_ inherited__">LlamaMLP</span>): | |
| <span class="hljs-keyword">pass</span><!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="config-docstrings" 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="#config-docstrings"><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><!---->Docstrings de configuration<!----></span></h3><!--]--><!----> <p>Le linter ne prend pas encore en charge l’héritage partiel des docstrings. Lors de l’ajout ou de la suppression d’attributs de configuration, ajoutez la docstring complète directement dans le fichier modulaire, sous la définition de la classe.</p> <!--[1--><h2 class="relative group"><a id="checkpoint-conversion" 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="#checkpoint-conversion"><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><!---->Conversion de points de contrôle<!----></span></h2><!--]--><!----> <p>Une fois que vous avez généré vos fichiers de modélisation, vérifiez que les poids réels se chargent correctement. Rédigez un script de conversion pour traduire le format de point de contrôle amont en un format compatible avec Transformers, puis enregistrez-le sur le Hub.</p> <!--[2--><h3 class="relative group"><a id="write-a-conversion-script" 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="#write-a-conversion-script"><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><!---->Écrire un script de conversion<!----></span></h3><!--]--><!----> <p>Ajoutez un fichier <code>convert_<model>_to_hf.py</code> dans <code>src/transformers/models/<model>/</code>. Le script charge les poids en amont, renomme et redimensionne les clés pour qu’elles correspondent aux noms des paramètres de votre module, puis enregistre le résultat avec <a href="/docs/transformers/main/fr/main_classes/model#transformers.PreTrainedModel.save_pretrained">save_pretrained()</a>.</p> <blockquote class="tip"><p>Cherchez un script existant à copier et à adapter. Les modèles situés dans <code>src/transformers/models/</code> incluent un <code>convert_*_to_hf.py</code> que vous pouvez utiliser comme point de départ.</p></blockquote> <p>Après avoir exécuté le script, chargez le point de contrôle enregistré avec <a href="/docs/transformers/main/fr/main_classes/model#transformers.PreTrainedModel.from_pretrained">from_pretrained()</a> et vérifiez que chaque poids attendu a bien été chargé correctement. Les clés du point de contrôle non utilisées indiquent des noms non correspondants ; affichez-les donc pour détecter les problèmes rapidement.</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 = YourModelForTask.from_pretrained(<span class="hljs-string">"path/to/output/"</span>)<!----></pre></div><!----> <p>Vérifiez que les formes et les noms correspondent lors de l'itération sur les clés. Les incohérences de forme indiquent généralement qu'un paramètre de votre configuration est incorrect, que l'architecture diffère de l'originale, ou qu'un poids doit être transposé.</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">for</span> key, tensor <span class="hljs-keyword">in</span> original_state_dict.items(): | |
| hf_tensor = hf_model.state_dict().get(mapped_key) | |
| <span class="hljs-keyword">assert</span> hf_tensor.shape == tensor.shape, ( | |
| <span class="hljs-string">f"Shape mismatch for <span class="hljs-subst">{key}</span>: expected <span class="hljs-subst">{tensor.shape}</span>, got <span class="hljs-subst">{hf_tensor.shape}</span>"</span> | |
| )<!----></pre></div><!----> <p>Corrigez les problèmes en itérant entre votre fichier modulaire, le fichier de modélisation généré et le script de conversion, jusqu’à ce que tous les poids se chargent correctement.</p> <p>Une fois que le point de contrôle est chargé sans erreur, poussez-le sur le Hub à l'aide de <a href="/docs/transformers/main/fr/main_classes/model#transformers.utils.PushToHubMixin.push_to_hub">push_to_hub()</a>. Consultez le guide sur le <a href="./model_sharing">partage de modèles</a> pour plus de détails.</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.push_to_hub(<span class="hljs-string">"username/your-model-name"</span>)<!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="runtime-conversion-mapping" 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="#runtime-conversion-mapping"><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><!---->Cartographie de conversion au moment de l'exécution<!----></span></h3><!--]--><!----> <p>Ajoutez une correspondance d’exécution dans <code>src/transformers/conversion_mapping.py</code> lorsque les poids publiés ne correspondent pas à la disposition des paramètres de votre module. Les cas courants incluent les poids fusionnés stockés séparément et les tenseurs d’experts MoE qui nécessitent un empilement. Cette correspondance permet à <a href="/docs/transformers/main/fr/main_classes/model#transformers.PreTrainedModel.from_pretrained">from_pretrained()</a> de charger le point de contrôle du Hub sans étape d’exportation distincte.</p> <p>Reportez-vous au guide sur le <a href="./weightconverter">chargement dynamique des poids</a> pour savoir comment écrire des règles <code>WeightRenaming</code> et <a href="/docs/transformers/main/fr/internal/modeling_utils#transformers.WeightConverter">WeightConverter</a> et les enregistrer pour votre <code>model_type</code>.</p> <!--[1--><h2 class="relative group"><a id="next-steps" 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="#next-steps"><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><!---->Étapes suivantes<!----></span></h2><!--]--><!----> <ul><li>Les <a href="./modeling_rules">règles de structure des modèles</a> sont des règles statiques appliquées à tous les fichiers <code>modeling_*.py</code>, <code>modular_*.py</code> et <code>configuration_*.py</code>. Exécutez <code>make typing</code> pour les vérifier avant d'ouvrir une PR.</li> <li><a href="./add_vision_processing_components">Ajouter des composants de traitement visuel</a> détaille l’ajout d’un processeur d’images, d’un processeur de vidéos et d’un processeur pour un modèle multimodal.</li> <li><a href="./auto_docstring">Génération automatique des docstrings</a> montre comment utiliser <code>@auto_docstring</code> afin de ne pas avoir à rédiger manuellement la documentation des arguments pour les API de modèles partagées.</li> <li><a href="./testing">Rédiger des tests de modèle</a> explique comment rédiger des tests d'intégration pour votre nouveau modèle et l'exécuter localement.</li> <li><a href="./pr_checks">Contrôles des pull requests</a> explique les contrôles CI que votre PR doit passer avant de pouvoir être fusionnée, et comment les reproduire et les corriger localement.</li></ul> <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/modular_transformers.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_1m6yd5j = { | |
| 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.DYIO-UII.js"), | |
| import("/docs/transformers/main/en/_app/immutable/entry/app.D2_KizbC.js") | |
| ]).then(([kit, app]) => { | |
| kit.start(app, element, { | |
| node_ids: [0, 675], | |
| data: [null,null], | |
| form: null, | |
| error: null | |
| }); | |
| }); | |
| } | |
| </script> | |
Xet Storage Details
- Size:
- 111 kB
- Xet hash:
- 9cf1de86cb135fd2400672e60be0fc1a761a3a570427ee6b1d25f37af9f00c2f
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.