Buckets:

hf-doc-build/doc / transformers /main /ru /modular_transformers.html
mishig's picture
download
raw
121 kB
<meta charset="utf-8" /><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Добавление модели с модульными трансформерами&quot;,&quot;local&quot;:&quot;add-a-model-with-modular-transformers&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Реализация модульного файла&quot;,&quot;local&quot;:&quot;implementing-a-modular-file&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Конфигурация&quot;,&quot;local&quot;:&quot;config&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Норма&quot;,&quot;local&quot;:&quot;norm&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Внимание&quot;,&quot;local&quot;:&quot;attention&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;DecoderLayer&quot;,&quot;local&quot;:&quot;decoderlayer&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Модель&quot;,&quot;local&quot;:&quot;model&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Голова модели&quot;,&quot;local&quot;:&quot;model-head&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Другие классы&quot;,&quot;local&quot;:&quot;other-classes&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Завершение файла&quot;,&quot;local&quot;:&quot;finishing-the-file&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3}],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Сгенерировать файлы моделирования&quot;,&quot;local&quot;:&quot;generate-the-modeling-files&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Шаблоны для модульных файлов&quot;,&quot;local&quot;:&quot;patterns-for-modular-files&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Удаление атрибутов&quot;,&quot;local&quot;:&quot;removing-attributes&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Работа с super()&quot;,&quot;local&quot;:&quot;working-with-super&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Вызов класса-предка напрямую&quot;,&quot;local&quot;:&quot;call-a-grandparent-class-directly&quot;,&quot;sections&quot;:[],&quot;depth&quot;:4},{&quot;title&quot;:&quot;super_kwargs&quot;,&quot;local&quot;:&quot;superkwargs&quot;,&quot;sections&quot;:[],&quot;depth&quot;:4}],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Удаление неиспользуемых методов&quot;,&quot;local&quot;:&quot;deleting-unused-methods&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Переопределение декорированных методов&quot;,&quot;local&quot;:&quot;overriding-decorated-methods&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Особое именование&quot;,&quot;local&quot;:&quot;special-naming&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Строки документации конфигурации&quot;,&quot;local&quot;:&quot;config-docstrings&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3}],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Конвертация контрольных точек&quot;,&quot;local&quot;:&quot;checkpoint-conversion&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Напишите скрипт конвертации&quot;,&quot;local&quot;:&quot;write-a-conversion-script&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Карта преобразований во время выполнения&quot;,&quot;local&quot;:&quot;runtime-conversion-mapping&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3}],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Дальнейшие шаги&quot;,&quot;local&quot;:&quot;next-steps&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2}],&quot;depth&quot;: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="{&quot;title&quot;:&quot;Add a model with modular transformers&quot;,&quot;local&quot;:&quot;add-a-model-with-modular-transformers&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Implementing a modular file&quot;,&quot;local&quot;:&quot;implementing-a-modular-file&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Config&quot;,&quot;local&quot;:&quot;config&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Norm&quot;,&quot;local&quot;:&quot;norm&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Attention&quot;,&quot;local&quot;:&quot;attention&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;DecoderLayer&quot;,&quot;local&quot;:&quot;decoderlayer&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Model&quot;,&quot;local&quot;:&quot;model&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Model head&quot;,&quot;local&quot;:&quot;model-head&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Other classes&quot;,&quot;local&quot;:&quot;other-classes&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Finishing the file&quot;,&quot;local&quot;:&quot;finishing-the-file&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3}],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Generate the modeling files&quot;,&quot;local&quot;:&quot;generate-the-modeling-files&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Patterns for modular files&quot;,&quot;local&quot;:&quot;patterns-for-modular-files&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Removing attributes&quot;,&quot;local&quot;:&quot;removing-attributes&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Working with super()&quot;,&quot;local&quot;:&quot;working-with-super&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Call a grandparent class directly&quot;,&quot;local&quot;:&quot;call-a-grandparent-class-directly&quot;,&quot;sections&quot;:[],&quot;depth&quot;:4},{&quot;title&quot;:&quot;super_kwargs&quot;,&quot;local&quot;:&quot;superkwargs&quot;,&quot;sections&quot;:[],&quot;depth&quot;:4}],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Deleting unused methods&quot;,&quot;local&quot;:&quot;deleting-unused-methods&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Overriding decorated methods&quot;,&quot;local&quot;:&quot;overriding-decorated-methods&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Special naming&quot;,&quot;local&quot;:&quot;special-naming&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Config docstrings&quot;,&quot;local&quot;:&quot;config-docstrings&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3}],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Checkpoint conversion&quot;,&quot;local&quot;:&quot;checkpoint-conversion&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Write a conversion script&quot;,&quot;local&quot;:&quot;write-a-conversion-script&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Runtime conversion mapping&quot;,&quot;local&quot;:&quot;runtime-conversion-mapping&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3}],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Next steps&quot;,&quot;local&quot;:&quot;next-steps&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2}],&quot;depth&quot;:1}"/><!---->
<link href="/docs/transformers/main/en/_app/immutable/assets/0.tn0RQdqM.css" rel="modulepreload"> <!--[--><!--[0--><!--[--><!--[0--><!--[--><p></p> <div class="items-center shrink-0 min-w-[100px] max-sm:min-w-[50px] justify-end ml-auto flex" style="float: inline-end; margin-inline-start: 10px; display: inline-flex; position: relative; z-index: 10;"><div dir="ltr" class="inline-flex rounded-md max-sm:rounded-sm"><button class="inline-flex items-center gap-1 h-7 max-sm:h-7 px-2 max-sm:px-1.5 text-sm font-medium text-gray-800 border border-r-0 rounded-l-md max-sm:rounded-l-sm border-gray-200 bg-white hover:shadow-inner dark:border-gray-850 dark:bg-gray-950 dark:text-gray-200 dark:hover:bg-gray-800" aria-live="polite"><span class="inline-flex items-center justify-center rounded-md p-0.5 max-sm:p-0 hover:text-gray-800 dark:hover:text-gray-200"><svg class="sm:size-3.5 size-3" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----></span> <span dir="auto">Copy page</span></button> <button class="inline-flex items-center justify-center w-6 max-sm:w-5 h-7 max-sm:h-7 disabled:pointer-events-none text-sm text-gray-500 hover:text-gray-700 dark:hover:text-white rounded-r-md max-sm:rounded-r-sm border border-l transition border-gray-200 bg-white hover:shadow-inner dark:border-gray-850 dark:bg-gray-950 dark:text-gray-200 dark:hover:bg-gray-800" aria-haspopup="menu" aria-expanded="false" aria-label="Open copy menu"><svg class="transition-transform text-gray-400 overflow-visible sm:size-3.5 size-3 rotate-0" width="1em" height="1em" viewBox="0 0 12 7" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 1L6 6L11 1" stroke="currentColor"></path></svg><!----></button></div> <!--[-1--><!--]--></div><!----> <!--[0--><h1 class="relative group"><a id="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><!---->Добавление модели с модульными трансформерами<!----></span></h1><!--]--><!----> <p>Modular transformers сокращает объём кода, необходимого для добавления модели, за счёт использования импортов и наследования, в отличие от политики <a href="https://huggingface.co/blog/transformers-design-philosophy" rel="nofollow">одна модель — один файл</a>. Вместо повторения компонентов модели в разных файлах добавьте файл <em>modular</em> в папку вашей модели и наследуйтесь от существующих классов.</p> <p>Конвертер генерирует автономные файлы из модульного файла. Пользователи получают тот же самый интерфейс с одним файлом, который они уже знают.</p> <blockquote class="note"><p>Модульные трансформеры не предназначены для замены <a href="./add_new_model">устаревшего кода моделирования</a>. Если ваша модель не основана на существующей, добавьте файл <code>modeling.py</code> вручную. То же самое касается файлов конфигурации, токенизации или обработки, которые не могут чисто наследоваться от похожего файла.</p> <p>Единого правильного порядка здесь тоже нет. Некоторые участники сначала пишут модульный файл и генерируют из него остальное. Другие начинают с вручную написанного <code>modeling.py</code> и позже рефакторят его в модульный файл. Оба подхода работают.</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><!---->Реализация модульного файла<!----></span></h2><!--]--><!----> <p>Начните с поиска модели в Transformers, похожей на вашу. Хорошей отправной точкой могут служить <a href="./model_doc/mistral">Mistral</a>, <a href="./model_doc/qwen2">Qwen2</a>, <a href="./model_doc/cohere">Cohere</a> и <a href="./model_doc/cohere2">Cohere2</a>, а также <a href="./model_doc/llama">Llama</a>. В таблице ниже приведено соответствие между общими компонентами и моделями, от которых можно наследовать.</p> <table><thead><tr><th>Компонент</th><th>Модель</th></tr></thead><tbody><tr><td>Смесь экспертов</td><td>Mixtral или Qwen2-MoE</td></tr><tr><td>Чередующаяся (и/или частичная) ротационная эмбеддинговая</td><td>GLM, Phi</td></tr><tr><td>Модели пространства состояний</td><td>Jamba, Bamba, Zamba, Mamba2</td></tr><tr><td>Рекуррентные скрытые состояния</td><td>Gemma2</td></tr><tr><td>Паттерны скользящего окна внимания/полного внимания для каждого слоя</td><td>Gemma2, Cohere2</td></tr><tr><td>Обрезание QKV</td><td>Olmo</td></tr><tr><td>Нормализация QK</td><td>Olmo2, Cohere</td></tr><tr><td>Сквозное QKV (не рекомендуется)</td><td>Phi3</td></tr></tbody></table> <blockquote class="tip"><p>Используйте инструмент <a href="https://huggingface.co/spaces/Molbap/modular-detector-v2" rel="nofollow">modular-detector-v2</a>, чтобы найти существующие реализации, от которых можно наследовать. Вставьте фрагмент кода, и он вернёт наиболее похожие методы, уже присутствующие в Transformers, что позволит определить оптимальный родительский класс до начала написания кода.</p></blockquote> <p>Не изменяйте существующую модель только ради того, чтобы наследование работало для вашей новой. Если переименование или создание подкласса родительского класса слишком неудобно, просто скопируйте нужный код напрямую.</p> <p>Создайте <code>src/transformers/models/&lt;name>/modular_&lt;name>.py</code>, где <code>&lt;name></code> совпадает с именем каталога модели в формате snake_case. В этом разделе показано, как реализовать <a href="./model_doc/olmo2">Olmo2</a> на основе <a href="./model_doc/olmo">Olmo</a> с использованием модульного подхода (см. исходный файл <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/models/olmo2/modular_olmo2.py" rel="nofollow">modular_olmo2.py</a>).</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><!---->Конфигурация<!----></span></h3><!--]--><!----> <p>Есть два отличия <a href="/docs/transformers/main/ru/model_doc/olmo2#transformers.Olmo2Config">Olmo2Config</a> от <a href="/docs/transformers/main/ru/model_doc/olmo#transformers.OlmoConfig">OlmoConfig</a>.</p> <ol><li>Добавлен новый аргумент <code>rms_norm_eps</code>.</li> <li>Аргумент <code>clip_qkv</code> больше не используется.</li></ol> <p>Объявляйте новые аргументы как аннотации типов на уровне класса со значением по умолчанию. Для удалённых аргументов присвойте <code>AttributeError()</code>, чтобы подавить унаследованный атрибут в сгенерированном файле (см. <a href="#removing-attributes">Удаление атрибутов</a>).</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-diff "><!----><span class="hljs-deletion">- @auto_docstring(checkpoint=&quot;allenai/OLMo-7B-hf&quot;)</span>
<span class="hljs-addition">+ @auto_docstring(checkpoint=&quot;allenai/Olmo2-7B-1124-hf&quot;)</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 = &quot;olmo&quot;</span>
<span class="hljs-addition">+ model_type = &quot;olmo2&quot;</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> автоматически генерирует стандартные описания аргументов (см. руководство по <a href="./auto_docstring">@auto_docstring</a>). <code>@strict</code> отклоняет неизвестные kwargs при инициализации, позволяя на раннем этапе выявлять опечатки и устаревшие аргументы. Добавляйте оба декоратора в каждый класс конфигурации, так как они не наследуются от родительского класса. Объявляйте их явно, даже если родительский класс конфигурации уже их содержит.</p> <p>Чтобы задать производный атрибут или обработать логику обратной совместимости, используйте <code>__post_init__</code> вместо <code>__init__</code>. Например, Cohere2 вычисляет <code>head_dim</code> и выводит <code>layer_types</code> при инициализации.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">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>Для моделей с поддержкой тензорного или конвейерного параллелизма определите <code>base_model_tp_plan</code> и <code>base_model_pp_plan</code> как словари на уровне класса в конфигурации. Оба словаря определяют, как разбить модель на части для распределения по устройствам. Примеры можно найти в существующих конфигурациях, например <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/models/olmo2/modular_olmo2.py" rel="nofollow">Olmo2</a> или <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/models/cohere2/modular_cohere2.py" rel="nofollow">Cohere2</a>.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">class</span> <span class="hljs-title class_">MyNewModelConfig</span>(<span class="hljs-title class_ inherited__">PreTrainedConfig</span>):
model_type = <span class="hljs-string">&quot;my_new_model&quot;</span>
<span class="hljs-comment"># Tensor parallelism: maps layer name patterns to sharding strategies.</span>
<span class="hljs-comment"># Use &quot;colwise&quot; / &quot;rowwise&quot; for standard sharding, or the &quot;gather_output&quot; /</span>
<span class="hljs-comment"># &quot;split_input&quot; variants when an extra op (e.g. a QK norm) prevents fusing.</span>
base_model_tp_plan = {
<span class="hljs-string">&quot;layers.*.self_attn.q_proj&quot;</span>: <span class="hljs-string">&quot;colwise&quot;</span>,
<span class="hljs-string">&quot;layers.*.self_attn.k_proj&quot;</span>: <span class="hljs-string">&quot;colwise&quot;</span>,
<span class="hljs-string">&quot;layers.*.self_attn.v_proj&quot;</span>: <span class="hljs-string">&quot;colwise&quot;</span>,
<span class="hljs-string">&quot;layers.*.self_attn.o_proj&quot;</span>: <span class="hljs-string">&quot;rowwise&quot;</span>,
<span class="hljs-string">&quot;layers.*.mlp.gate_proj&quot;</span>: <span class="hljs-string">&quot;colwise&quot;</span>,
<span class="hljs-string">&quot;layers.*.mlp.up_proj&quot;</span>: <span class="hljs-string">&quot;colwise&quot;</span>,
<span class="hljs-string">&quot;layers.*.mlp.down_proj&quot;</span>: <span class="hljs-string">&quot;rowwise&quot;</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">&quot;embed_tokens&quot;</span>: ([<span class="hljs-string">&quot;input_ids&quot;</span>], [<span class="hljs-string">&quot;inputs_embeds&quot;</span>]),
<span class="hljs-string">&quot;layers&quot;</span>: ([<span class="hljs-string">&quot;hidden_states&quot;</span>, <span class="hljs-string">&quot;attention_mask&quot;</span>], [<span class="hljs-string">&quot;hidden_states&quot;</span>]),
<span class="hljs-string">&quot;norm&quot;</span>: ([<span class="hljs-string">&quot;hidden_states&quot;</span>], [<span class="hljs-string">&quot;hidden_states&quot;</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><!---->Норма<!----></span></h3><!--]--><!----> <p>Чтобы скопировать родительский класс без изменений, унаследуйте его с помощью <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> Скопировано</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>Чтобы изменить конкретное поведение, наследуйте и переопределяйте только то, что отличается. <code>Olmo2RMSNorm</code> отличается от <code>LlamaRMSNorm</code> одной строкой. Умножение выполняется <em>до</em> приведения обратно к типу данных входных данных, а не после.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-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><!---->Внимание<!----></span></h3><!--]--><!----> <p>Внимание в Olmo2 идентично вниманию в Olmo, за исключением того, что к запросам и ключам применяется <code>RMSNorm</code>, а обрезание qkv удалено. Вызов <code>super().__init__(...)</code> копирует тело родительского класса и добавляет две новые строки нормализации. Метод <code>forward</code> полностью переопределён, поскольку теперь запросы и ключи проходят через нормализацию перед проекцией. Линтер также переносит в сгенерированный файл все импортированные функции, включая <code>apply_rotary_pos_emb</code>, <code>eager_attention_forward</code> и их зависимости.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-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>После <code>super().__init__(...)</code> перезапишите атрибуты нормализации экземплярами <code>Olmo2RMSNorm</code> и переназначьте <code>self.self_attn</code> на новый класс <code>Olmo2Attention</code>. Оператор <code>del self.input_layernorm</code> удаляет присваивание <code>input_layernorm</code> из родительского класса, поскольку Olmo2 применяет нормализацию <em>после</em> внимания, а не до него. Подробности о том, что удаляет, а что оставляет оператор <code>del</code>, см. в разделе <a href="#removing-attributes">Удаление атрибутов</a>.</p> <p>Метод <code>forward</code> переписан с учётом нового расположения нормализации после внимания. Переписывание <code>forward</code> требуется только при переименовании атрибута, а не при изменении только его типа.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-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><!---->Модель<!----></span></h3><!--]--><!----> <p>Здесь меняется только тип <code>self.norm</code>. Метод <code>forward</code> идентичен методу родительского класса, поэтому линтер переносит его автоматически.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-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><!---->Голова модели<!----></span></h3><!--]--><!----> <p>Логика идентична логике <a href="/docs/transformers/main/ru/model_doc/olmo#transformers.OlmoForCausalLM">OlmoForCausalLM</a>, поэтому изменения не требуются.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">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><!---->Другие классы<!----></span></h3><!--]--><!----> <p>Файл <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/models/olmo2/modeling_olmo2.py" rel="nofollow">modeling_olmo2.py</a>, сгенерированный линтером, также содержит классы (<code>Olmo2MLP</code>, <code>Olmo2RotaryEmbedding</code>, <code>Olmo2PreTrainedModel</code>), которые не были явно определены в <code>modular_olmo2.py</code>.</p> <p>Линтер подтягивает любой класс, от которого зависит наследуемый класс, если вы не переопределяете его явно. Импортированные функции, такие как <code>apply_rotary_pos_emb</code>, подчиняются тому же правилу.</p> <p>Например, <code>OlmoDecoderLayer</code> содержит <code>self.mlp = OlmoMLP(config)</code>. <code>Olmo2MLP</code> не был определён в модульном файле, поэтому линтер создаёт его автоматически, что эквивалентно использованию <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> Скопировано</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>Если вы хотите, чтобы <code>Olmo2MLP</code> наследовался от другой модели, укажите это явно.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-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><!---->Завершение файла<!----></span></h3><!--]--><!----> <p>Каждый модульный файл должен объявлять <code>logger</code> и список <code>__all__</code> на уровне модуля.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->logger = logging.get_logger(__name__)
__all__ = [
<span class="hljs-string">&quot;Olmo2Config&quot;</span>,
<span class="hljs-string">&quot;Olmo2ForCausalLM&quot;</span>,
<span class="hljs-string">&quot;Olmo2Model&quot;</span>,
<span class="hljs-string">&quot;Olmo2PreTrainedModel&quot;</span>,
]<!----></pre></div><!----> <p><code>__all__</code> должен перечислять все публичные классы в файле. Конвертер и последующие импорты зависят от него. Класс, отсутствующий в <code>__all__</code>, не будет экспортирован корректно.</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><!---->Сгенерировать файлы моделирования<!----></span></h2><!--]--><!----> <p>Скрипт <code>modular_model_converter.py</code> генерирует автономные файлы <code>modeling.py</code>, <code>configuration.py</code> и другие на основе вашего модульного файла. Для каждого наследуемого класса он копирует тело родительского класса в дочерний, переименовывает все ссылки в соответствии с новой моделью и подтягивает вспомогательные функции или классы, от которых зависят эти родительские классы.</p> <p>В выходных файлах отсутствуют импорты между моделями и наследование из других каталогов моделей. Linter сворачивает наследование до одного уровня. Если <code>Olmo2Attention</code> наследуется от <code>OlmoAttention</code>, то сгенерированный <code>Olmo2Attention</code> является полностью самодостаточным. Однако, если <code>OlmoAttention</code> сам наследовался от чего-то другого, linter не инлайнит этого «прадеда».</p> <p>Выполните команду ниже, чтобы сгенерировать файлы из модульного файла.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-bash "><!---->python utils/modular_model_converter.py your_model<!----></pre></div><!----> <p>Никогда не редактируйте сгенерированные файлы напрямую, так как любые изменения будут перезаписаны при следующем запуске.</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><!---->Шаблоны для модульных файлов<!----></span></h2><!--]--><!----> <p>Разделы ниже описывают типичные сценарии использования, такие как удаление атрибутов или переопределение декорированных методов, при работе с модульным файлом.</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><!---->Удаление атрибутов<!----></span></h3><!--]--><!----> <p>Способ удаления унаследованного атрибута зависит от того, работаете ли вы с классом конфигурации или с подклассом <code>nn.Module</code>.</p> <p>Для класса конфигурации присвойте <code>AttributeError()</code> атрибуту на уровне класса.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">class</span> <span class="hljs-title class_">MyNewConfig</span>(<span class="hljs-title class_ inherited__">ParentConfig</span>):
removed_attr = AttributeError()<!----></pre></div><!----> <p>Инструмент проверки кода полностью удаляет объявление атрибута из сгенерированного файла конфигурации. Классы конфигурации используют структуру в стиле dataclass без <code>__init__</code>, поэтому присваивание <code>AttributeError()</code> на уровне класса является правильным подходом.</p> <p>Для подкласса <code>nn.Module</code> используйте <code>del self.attribute</code> после <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> Скопировано</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> удаляет только строку присваивания <code>self.attribute = ...</code> из скопированного тела родительского класса. Она не удаляет другие строки, в которых используется <code>self.attribute</code>. Если в методе <code>forward</code> родителя или в других методах также есть ссылки на этот атрибут, переопределите и эти методы.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">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"># &#x27;self.attribute = config.attribute&#x27; is removed, but the &#x27;if self.attribute:&#x27; 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><!---->Работа с super()<!----></span></h3><!--]--><!----> <p><code>super().__init__(config)</code> указывает конвертеру скопировать тело родительского класса в дочерний. Два паттерна позволяют переопределить это поведение.</p> <ul><li>Вызывайте конкретный родительский класс напрямую, если сгенерированный вывод должен вызывать класс-прадедушку (<code>nn.Module.__init__</code>), а не модульный родительский класс.</li> <li>Используйте <code>**super_kwargs</code>, чтобы унаследовать полную сигнатуру родительского метода, добавив при этом собственный docstring или заменив декоратор.</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><!---->Вызов класса-предка напрямую<!----></span></h4><!--]--><!----> <p>Будьте явны в том, какой класс вы вызываете, когда вам нужно, чтобы <code>super()</code> обращался к родительскому классу сгенерированного класса, а не к родительскому модульному классу. В примере ниже напрямую вызывается <code>nn.Module.__init__(self)</code>. <code>DummyModule</code> сам по себе является <code>nn.Module</code>, поэтому конвертер записывает его как <code>super().__init__()</code> в сгенерированном <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> Скопировано</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>Используйте <code>**super_kwargs</code>, чтобы унаследовать полную сигнатуру родительского метода, добавив при этом собственный docstring или заменив декоратор. В переопределённой сигнатуре этот параметр указывает линтеру развернуть все аргументы родительского метода в сгенерированном результате.</p> <p>Наиболее частое применение — добавление docstring, специфичного для модели, например, документирование аргумента <code>labels</code>, без переписывания полной сигнатуры.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-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&quot;&quot;&quot;
Example:
```python
&gt;&gt;&gt; from transformers import AutoTokenizer, GemmaForCausalLM
&gt;&gt;&gt; model = GemmaForCausalLM.from_pretrained(&quot;google/gemma-7b&quot;)
...
```&quot;&quot;&quot;</span>
<span class="hljs-keyword">return</span> <span class="hljs-built_in">super</span>().forward(**super_kwargs)<!----></pre></div><!----> <p>Сгенерированный <code>GemmaForCausalLM.forward</code> имеет полную сигнатуру <code>LlamaForCausalLM</code>, поэтому ручное копирование не требуется.</p> <p><code>**super_kwargs</code> — это сокращение для узкоспециализированных случаев. Если вы изменяете поведение, лучше указать полную сигнатуру.</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><!---->Удаление неиспользуемых методов<!----></span></h3><!--]--><!----> <p>Удалите родительский метод, переопределив его с помощью оператора <code>raise AttributeError("")</code>. Линтер удалит метод из сгенерированного файла.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">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">&quot;Not needed for Gemma&quot;</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">&quot;Not needed for Gemma&quot;</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><!---->Переопределение декорированных методов<!----></span></h3><!--]--><!----> <p>При переопределении метода родительского класса, имеющего декоратор, декоратор родителя автоматически переносится на переопределённый метод. Если вы добавите собственный декоратор, он заменит декоратор родителя.</p> <p>В библиотеке используются два декоратора: один для <a href="./model_output_tracing">захвата промежуточных выходов модели</a>, а другой — для <a href="./auto_docstring">автоматической генерации docstrings</a>.</p> <p>В примере ниже подкласс переопределяет декорированный метод родительского класса, не добавляя собственный декоратор. Декоратор родительского метода переносится на переопределённый метод.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-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>Если вы добавите новый декоратор, он заменит декоратор родительского класса.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">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><!---->Особое именование<!----></span></h3><!--]--><!----> <p>Инструмент проверки кода автоматически переименовывает всё при наследовании от класса. Используйте одинаковый префикс имени класса для всех классов в одном файле.</p> <p>Избегайте смешивания префиксов, как в примере ниже. <code>MyModelIncredibleMLP</code> нарушает соглашения об именовании, и линтер не сможет определить, использовать ли <code>MyModelIncredible</code> или <code>MyModel</code> при переименовании зависимостей более высокого уровня.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">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>Благодаря отсутствию <a href="#other-classes">неявных зависимостей</a> можно переименовать один класс локально. Явно переопределите каждое другое упоминание этого класса с новым именем. В противном случае линтер добавит нежелательный класс <code>MyModelMLP</code> рядом с <code>MyModelIncredibleMLP</code>.</p> <p>Линтер выдает предупреждение, если обнаруживает неоднозначный префикс.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-text "><!---->We detected multiple prefix names when inheriting from transformers.models.llama.modeling_llama: (&#x27;Emu3Text&#x27;, &#x27;Emu3&#x27;). We will only use the most used &#x27;Emu3&#x27; prefix when grabbing args and dependencies. Make sure to subclass the intermediate classes with the prefix you want (if different from &#x27;Emu3&#x27;) or use a single prefix in all the modular (best).<!----></pre></div><!----> <p>Двусмысленные префиксы чаще всего встречаются в мультимодальных моделях, где имена классов содержат модальный квалификатор, например <code>Text</code>. Чтобы задать конкретный префикс для зависимости, явно переименуйте её с помощью <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> Скопировано</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><!---->Строки документации конфигурации<!----></span></h3><!--]--><!----> <p>Линтер пока не поддерживает частичное наследование docstring. При добавлении или удалении атрибутов конфигурации добавляйте полный docstring непосредственно в модульном файле под определением класса.</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><!---->Конвертация контрольных точек<!----></span></h2><!--]--><!----> <p>После того как вы сгенерировали файлы моделирования, убедитесь, что реальные веса загружаются корректно. Напишите скрипт конвертации, который преобразует формат чекпоинта из исходного репозитория в формат, совместимый с Transformers, а затем сохраните его на 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><!---->Напишите скрипт конвертации<!----></span></h3><!--]--><!----> <p>Добавьте файл <code>convert_&lt;model>_to_hf.py</code> в <code>src/transformers/models/&lt;model>/</code>. Скрипт загружает веса из исходного репозитория, переименовывает и изменяет размерность ключей, чтобы они соответствовали именам параметров вашего модуля, и сохраняет результат с помощью <a href="/docs/transformers/main/ru/main_classes/model#transformers.PreTrainedModel.save_pretrained">save_pretrained()</a>.</p> <blockquote class="tip"><p>Ищите существующий скрипт, который можно скопировать и адаптировать. В моделях, расположенных в <code>src/transformers/models/</code>, есть <code>convert_*_to_hf.py</code>, который можно использовать в качестве отправной точки.</p></blockquote> <p>После запуска скрипта загрузите сохранённую контрольную точку с помощью <a href="/docs/transformers/main/ru/main_classes/model#transformers.PreTrainedModel.from_pretrained">from_pretrained()</a> и убедитесь, что все ожидаемые веса загружены корректно. Непроизведённые ключи контрольной точки указывают на несоответствие имён, поэтому выводите их, чтобы выявлять проблемы на раннем этапе.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->model = YourModelForTask.from_pretrained(<span class="hljs-string">&quot;path/to/output/&quot;</span>)<!----></pre></div><!----> <p>Проверяйте совпадение формы и имени при итерации по ключам. Несоответствие форм обычно означает, что параметр в вашем конфиге указан неверно, архитектура отличается от исходной или вес необходимо транспонировать.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><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&quot;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>&quot;</span>
)<!----></pre></div><!----> <p>Устраняйте проблемы, последовательно переключаясь между модульным файлом, сгенерированным файлом модели и скриптом конвертации, пока все веса не будут загружены без ошибок.</p> <p>После успешной загрузки чекпоинта отправьте его на Hub с помощью <a href="/docs/transformers/main/ru/main_classes/model#transformers.utils.PushToHubMixin.push_to_hub">push_to_hub()</a>. Подробнее см. в руководстве по <a href="./model_sharing">обмену моделями</a>.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->model.push_to_hub(<span class="hljs-string">&quot;username/your-model-name&quot;</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><!---->Карта преобразований во время выполнения<!----></span></h3><!--]--><!----> <p>Добавьте маппинг времени выполнения в <code>src/transformers/conversion_mapping.py</code>, если опубликованные веса не соответствуют структуре параметров вашего модуля. Типичные случаи включают слиянные веса, хранящиеся отдельно, и тензоры экспертов MoE, требующие стекирования. Маппинг позволяет <a href="/docs/transformers/main/ru/main_classes/model#transformers.PreTrainedModel.from_pretrained">from_pretrained()</a> загрузить чекпоинт с Hub без отдельного шага экспорта.</p> <p>См. руководство по <a href="./weightconverter">динамической загрузке весов</a>, чтобы узнать, как написать правила <code>WeightRenaming</code> и <a href="/docs/transformers/main/ru/internal/modeling_utils#transformers.WeightConverter">WeightConverter</a> и зарегистрировать их для вашего <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><!---->Дальнейшие шаги<!----></span></h2><!--]--><!----> <ul><li><a href="./modeling_rules">Правила структуры модели</a> — это статические правила, применяемые ко всем файлам <code>modeling_*.py</code>, <code>modular_*.py</code> и <code>configuration_*.py</code>. Запустите <code>make typing</code>, чтобы проверить их перед созданием PR.</li> <li><a href="./add_vision_processing_components">Добавление компонентов обработки изображений</a> описывает, как добавить image processor, video processor и processor для мультимодальной модели.</li> <li><a href="./auto_docstring">Автоматическая генерация docstrings</a> показывает, как использовать <code>@auto_docstring</code>, чтобы не писать вручную документацию аргументов для общих API моделей.</li> <li><a href="./testing">Создание тестов для моделей</a> описывает, как написать интеграционные тесты для новой модели и запустить её локально.</li> <li><a href="./pr_checks">Проверки pull request</a> описывает проверки CI, которые должен пройти ваш PR перед слиянием, и объясняет, как воспроизвести и исправить их локально.</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:
121 kB
·
Xet hash:
0a14f206277a6940a083848d15a685ede417379706952924704d039b372f7a0a

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