Buckets:
| <meta charset="utf-8" /><meta name="hf:doc:metadata" content="{"title":"Добавление компонентов обработки изображений","local":"add-vision-processing-components","sections":[{"title":"Обработчики изображений","local":"image-processors","sections":[{"title":"torchvision","local":"torchvision","sections":[],"depth":3},{"title":"PIL","local":"pil","sections":[],"depth":3},{"title":"Добавить методы постобработки","local":"add-post-processing-methods","sections":[],"depth":3}],"depth":2},{"title":"Процессор видео","local":"video-processor","sections":[],"depth":2},{"title":"Регистрация классов","local":"register-the-classes","sections":[],"depth":2},{"title":"Тестирование","local":"testing","sections":[{"title":"Тесты процессора изображений","local":"image-processor-tests","sections":[],"depth":3},{"title":"Тесты процессора видео","local":"video-processor-tests","sections":[],"depth":3}],"depth":2},{"title":"Дальнейшие шаги","local":"next-steps","sections":[],"depth":2}],"depth":1}"/> | |
| <link href="/docs/transformers/main/en/_app/immutable/entry/start.DYIO-UII.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/DSYYoqAA.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/BovLmb3z.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/entry/app.D2_KizbC.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/WyYpyc-L.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/DYBfcveH.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/DOLBYqcr.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/DsnmJJEf.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/nodes/0.ByO_lNbj.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/ZtBhN-Ei.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/nodes/6.B05ZmGdC.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/D-dvW--N.js" rel="modulepreload"> | |
| <!--1o4t0vs--><meta name="hf:doc:metadata" content="{"title":"Add vision processing components","local":"add-vision-processing-components","sections":[{"title":"Image processors","local":"image-processors","sections":[{"title":"torchvision","local":"torchvision","sections":[],"depth":3},{"title":"PIL","local":"pil","sections":[],"depth":3},{"title":"Add post-processing methods","local":"add-post-processing-methods","sections":[],"depth":3}],"depth":2},{"title":"Video processor","local":"video-processor","sections":[],"depth":2},{"title":"Register the classes","local":"register-the-classes","sections":[],"depth":2},{"title":"Testing","local":"testing","sections":[{"title":"Image processor tests","local":"image-processor-tests","sections":[],"depth":3},{"title":"Video processor tests","local":"video-processor-tests","sections":[],"depth":3}],"depth":2},{"title":"Next steps","local":"next-steps","sections":[],"depth":2}],"depth":1}"/><!----> | |
| <link href="/docs/transformers/main/en/_app/immutable/assets/0.tn0RQdqM.css" rel="modulepreload"> <!--[--><!--[0--><!--[--><!--[0--><!--[--><p></p> <div class="items-center shrink-0 min-w-[100px] max-sm:min-w-[50px] justify-end ml-auto flex" style="float: inline-end; margin-inline-start: 10px; display: inline-flex; position: relative; z-index: 10;"><div dir="ltr" class="inline-flex rounded-md max-sm:rounded-sm"><button class="inline-flex items-center gap-1 h-7 max-sm:h-7 px-2 max-sm:px-1.5 text-sm font-medium text-gray-800 border border-r-0 rounded-l-md max-sm:rounded-l-sm border-gray-200 bg-white hover:shadow-inner dark:border-gray-850 dark:bg-gray-950 dark:text-gray-200 dark:hover:bg-gray-800" aria-live="polite"><span class="inline-flex items-center justify-center rounded-md p-0.5 max-sm:p-0 hover:text-gray-800 dark:hover:text-gray-200"><svg class="sm:size-3.5 size-3" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----></span> <span dir="auto">Copy page</span></button> <button class="inline-flex items-center justify-center w-6 max-sm:w-5 h-7 max-sm:h-7 disabled:pointer-events-none text-sm text-gray-500 hover:text-gray-700 dark:hover:text-white rounded-r-md max-sm:rounded-r-sm border border-l transition border-gray-200 bg-white hover:shadow-inner dark:border-gray-850 dark:bg-gray-950 dark:text-gray-200 dark:hover:bg-gray-800" aria-haspopup="menu" aria-expanded="false" aria-label="Open copy menu"><svg class="transition-transform text-gray-400 overflow-visible sm:size-3.5 size-3 rotate-0" width="1em" height="1em" viewBox="0 0 12 7" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 1L6 6L11 1" stroke="currentColor"></path></svg><!----></button></div> <!--[-1--><!--]--></div><!----> <!--[0--><h1 class="relative group"><a id="add-vision-processing-components" 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-vision-processing-components"><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>Добавление модели зрения требует компонентов для обработки изображений или видео в дополнение к стандартному <a href="./modular_transformers">модульному</a> подходу. Модели, работающие только с изображениями, нуждаются в процессоре изображений, а модели для видео — в процессоре видео; оба доступны через точки входа <a href="/docs/transformers/main/ru/model_doc/auto#transformers.AutoImageProcessor">AutoImageProcessor</a> и <a href="/docs/transformers/main/ru/model_doc/auto#transformers.AutoVideoProcessor">AutoVideoProcessor</a>.</p> <blockquote class="note"><p>Для шагов моделирования и конфигурации сначала следуйте <a href="./modular_transformers">модульному</a> руководству.</p></blockquote> <!--[1--><h2 class="relative group"><a id="image-processors" 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="#image-processors"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Обработчики изображений<!----></span></h2><!--]--><!----> <p>Создавайте обработчики изображений, когда модель принимает изображения в качестве входных данных. Бэкенд <a href="https://docs.pytorch.org/vision/stable/index.html" rel="nofollow">torchvision</a> используется по умолчанию и поддерживает ускорение на GPU. <a href="https://pillow.readthedocs.io/en/stable/index.html" rel="nofollow">PIL</a> применяется как запасной вариант, если torchvision недоступен.</p> <p>Оба класса процессоров изображений используют одинаковую логику предобработки, но имеют разные бэкенды. Их сигнатуры конструкторов и значения по умолчанию должны быть идентичны. <a href="/docs/transformers/main/ru/model_doc/auto#transformers.AutoImageProcessor.from_pretrained">AutoImageProcessor.from_pretrained()</a> выбирает бэкенд при загрузке и переключается на PIL, если torchvision недоступен. Несовпадение сигнатур приводит к тому, что один и тот же сохранённый конфиг ведёт себя по-разному в разных средах.</p> <!--[2--><h3 class="relative group"><a id="torchvision" 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="#torchvision"><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><!---->torchvision<!----></span></h3><!--]--><!----> <p>Создайте <code>image_processing_<model_name>.py</code> с классом, наследующим от <a href="/docs/transformers/main/ru/main_classes/image_processor#transformers.TorchvisionBackend">TorchvisionBackend</a>. Если вашему процессору требуются дополнительные параметры помимо стандартных [ImagesKwargs], определите класс kwargs.</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> ...image_processing_backends <span class="hljs-keyword">import</span> TorchvisionBackend | |
| <span class="hljs-keyword">from</span> ...image_utils <span class="hljs-keyword">import</span> OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, PILImageResampling | |
| <span class="hljs-keyword">from</span> ...processing_utils <span class="hljs-keyword">import</span> ImagesKwargs, Unpack | |
| <span class="hljs-keyword">from</span> ...utils <span class="hljs-keyword">import</span> auto_docstring | |
| <span class="hljs-keyword">class</span> <span class="hljs-title class_">MyModelImageProcessorKwargs</span>(ImagesKwargs, total=<span class="hljs-literal">False</span>): | |
| tile_size: <span class="hljs-built_in">int</span> <span class="hljs-comment"># any model-specific kwargs</span> | |
| <span class="hljs-meta">@auto_docstring</span> | |
| <span class="hljs-keyword">class</span> <span class="hljs-title class_">MyModelImageProcessor</span>(<span class="hljs-title class_ inherited__">TorchvisionBackend</span>): | |
| resample = PILImageResampling.BICUBIC | |
| image_mean = OPENAI_CLIP_MEAN | |
| image_std = OPENAI_CLIP_STD | |
| size = {<span class="hljs-string">"shortest_edge"</span>: <span class="hljs-number">224</span>} | |
| do_resize = <span class="hljs-literal">True</span> | |
| do_rescale = <span class="hljs-literal">True</span> | |
| do_normalize = <span class="hljs-literal">True</span> | |
| do_convert_rgb = <span class="hljs-literal">True</span> | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, **kwargs: Unpack[MyModelImageProcessorKwargs]</span>): | |
| <span class="hljs-built_in">super</span>().__init__(**kwargs)<!----></pre></div><!----> <blockquote class="tip"><p>См. <a href="/docs/transformers/main/ru/model_doc/llava_onevision#transformers.LlavaOnevisionImageProcessor">LlavaOnevisionImageProcessor</a> для справки.</p></blockquote> <!--[2--><h3 class="relative group"><a id="pil" 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="#pil"><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><!---->PIL<!----></span></h3><!--]--><!----> <p>Создайте <code>image_processing_pil_<model_name>.py</code> с классом, наследующим от <a href="/docs/transformers/main/ru/main_classes/image_processor#transformers.PilBackend">PilBackend</a>. Дублируйте здесь класс kwargs, а не импортируйте его из файла torchvision, так как импорт может завершиться ошибкой, если torchvision не установлен. Добавьте комментарий <code># Adapted from</code>, чтобы два файла оставались синхронизированными. Для процессоров без пользовательских параметров используйте <a href="/docs/transformers/main/ru/main_classes/processors#transformers.ImagesKwargs">ImagesKwargs</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> ...image_processing_backends <span class="hljs-keyword">import</span> PilBackend | |
| <span class="hljs-keyword">from</span> ...image_utils <span class="hljs-keyword">import</span> OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, PILImageResampling | |
| <span class="hljs-keyword">from</span> ...processing_utils <span class="hljs-keyword">import</span> ImagesKwargs, Unpack | |
| <span class="hljs-keyword">from</span> ...utils <span class="hljs-keyword">import</span> auto_docstring | |
| <span class="hljs-comment"># Adapted from transformers.models.my_model.image_processing_my_model.MyModelImageProcessorKwargs</span> | |
| <span class="hljs-keyword">class</span> <span class="hljs-title class_">MyModelImageProcessorKwargs</span>(ImagesKwargs, total=<span class="hljs-literal">False</span>): | |
| tile_size: <span class="hljs-built_in">int</span> <span class="hljs-comment"># any model-specific kwargs</span> | |
| <span class="hljs-meta">@auto_docstring</span> | |
| <span class="hljs-keyword">class</span> <span class="hljs-title class_">MyModelImageProcessorPil</span>(<span class="hljs-title class_ inherited__">PilBackend</span>): | |
| resample = PILImageResampling.BICUBIC | |
| image_mean = OPENAI_CLIP_MEAN | |
| image_std = OPENAI_CLIP_STD | |
| size = {<span class="hljs-string">"shortest_edge"</span>: <span class="hljs-number">224</span>} | |
| do_resize = <span class="hljs-literal">True</span> | |
| do_rescale = <span class="hljs-literal">True</span> | |
| do_normalize = <span class="hljs-literal">True</span> | |
| do_convert_rgb = <span class="hljs-literal">True</span> | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, **kwargs: Unpack[MyModelImageProcessorKwargs]</span>): | |
| <span class="hljs-built_in">super</span>().__init__(**kwargs)<!----></pre></div><!----> <blockquote class="tip"><p>См. <a href="/docs/transformers/main/ru/model_doc/llava_onevision#transformers.LlavaOnevisionImageProcessorPil">LlavaOnevisionImageProcessorPil</a> для справки.</p></blockquote> <!--[2--><h3 class="relative group"><a id="add-post-processing-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="#add-post-processing-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>outputs</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_">MyModelImageProcessor</span>(<span class="hljs-title class_ inherited__">TorchvisionBackend</span>): | |
| ... | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">post_process_my_task</span>(<span class="hljs-params">self, outputs, ...</span>): | |
| ...<!----></pre></div><!----> <p>Post-processors возвращают либо список простых объектов (<code>list[str]</code> или <code>list[torch.Tensor]</code>), либо список сложных объектов (<code>list[MyTaskPostProcessorOutput]</code> или <code>list[dict]</code>). Выходные данные post-processor'ов определены в <code>src/transformers/image_processing_outputs.py</code> и наследуются от <a href="/docs/transformers/main/ru/main_classes/feature_extractor#transformers.BatchFeature">BatchFeature</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_">MyTaskPostProcessorOutput</span>(<span class="hljs-title class_ inherited__">BatchFeature</span>): | |
| predictions: torch.Tensor | |
| scores: torch.Tensor<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="video-processor" 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="#video-processor"><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> <p>Создайте <code>video_processing_<model_name>.py</code> в каталоге модели. <a href="/docs/transformers/main/ru/main_classes/video_processor#transformers.BaseVideoProcessor">BaseVideoProcessor</a> наследуется от <a href="/docs/transformers/main/ru/main_classes/image_processor#transformers.TorchvisionBackend">TorchvisionBackend</a> и обеспечивает общее поведение для декодирования, выборки кадров, изменения размера, масштабирования, нормализации, сохранения и загрузки.</p> <p>Атрибуты класса представляют значения предобработки по умолчанию. Пользователи могут переопределить их при инициализации или в момент вызова. По возможности используйте те же имена, что и в <a href="/docs/transformers/main/ru/main_classes/processors#transformers.VideosKwargs">VideosKwargs</a>, например <code>size</code>, <code>crop_size</code>, <code>do_resize</code>, <code>do_sample_frames</code>, <code>num_frames</code> и <code>fps</code>.</p> <p>Определите класс kwargs, если вашему видео-процессору требуются дополнительные параметры помимо стандартных <a href="/docs/transformers/main/ru/main_classes/processors#transformers.VideosKwargs">VideosKwargs</a>. Укажите его в качестве <code>valid_kwargs</code> и используйте для аннотации <code>__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">from</span> ...processing_utils <span class="hljs-keyword">import</span> Unpack, VideosKwargs | |
| <span class="hljs-keyword">from</span> ...utils <span class="hljs-keyword">import</span> auto_docstring | |
| <span class="hljs-keyword">from</span> ...video_processing_utils <span class="hljs-keyword">import</span> BaseVideoProcessor | |
| <span class="hljs-keyword">class</span> <span class="hljs-title class_">MyModelVideoProcessorKwargs</span>(VideosKwargs, total=<span class="hljs-literal">False</span>): | |
| min_frames: <span class="hljs-built_in">int</span> | |
| max_frames: <span class="hljs-built_in">int</span> | |
| <span class="hljs-meta">@auto_docstring</span> | |
| <span class="hljs-keyword">class</span> <span class="hljs-title class_">MyModelVideoProcessor</span>(<span class="hljs-title class_ inherited__">BaseVideoProcessor</span>): | |
| size = {<span class="hljs-string">"shortest_edge"</span>: <span class="hljs-number">224</span>} | |
| crop_size = {<span class="hljs-string">"height"</span>: <span class="hljs-number">224</span>, <span class="hljs-string">"width"</span>: <span class="hljs-number">224</span>} | |
| do_resize = <span class="hljs-literal">True</span> | |
| do_center_crop = <span class="hljs-literal">True</span> | |
| do_normalize = <span class="hljs-literal">True</span> | |
| do_sample_frames = <span class="hljs-literal">True</span> | |
| num_frames = <span class="hljs-number">16</span> | |
| model_input_names = [<span class="hljs-string">"pixel_values_videos"</span>] | |
| valid_kwargs = MyModelVideoProcessorKwargs | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, **kwargs: Unpack[MyModelVideoProcessorKwargs]</span>): | |
| <span class="hljs-built_in">super</span>().__init__(**kwargs)<!----></pre></div><!----> <p>Переопределяйте <a href="/docs/transformers/main/ru/main_classes/video_processor#transformers.BaseVideoProcessor.sample_frames">sample_frames()</a> только в том случае, если модели требуется правило выборки, которое базовый равномерный сэмплер не может выразить. Например, некоторые модели устанавливают минимальное или максимальное количество кадров или выполняют выборку на основе специфичных для модели ограничений.</p> <p>Если метод forward модели ожидает устаревшее имя входного параметра, переопределите <code>preprocess</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_">MyModelVideoProcessor</span>(<span class="hljs-title class_ inherited__">BaseVideoProcessor</span>): | |
| model_input_names = [<span class="hljs-string">"pixel_values"</span>] | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">preprocess</span>(<span class="hljs-params">self, videos, **kwargs</span>): | |
| batch = <span class="hljs-built_in">super</span>().preprocess(videos, **kwargs) | |
| batch[<span class="hljs-string">"pixel_values"</span>] = batch.pop(<span class="hljs-string">"pixel_values_videos"</span>) | |
| <span class="hljs-keyword">return</span> batch<!----></pre></div><!----> <p>Сохраните видео-процессор вместе с контрольной точкой, создав его экземпляр в скрипте конвертации и вызвав <a href="/docs/transformers/main/ru/main_classes/video_processor#transformers.VideoProcessorMixin.save_pretrained">save_pretrained()</a>. Если <a href="/docs/transformers/main/ru/main_classes/processors#transformers.ProcessorMixin">ProcessorMixin</a> оборачивает видео-процессор, вызовите вместо этого <a href="/docs/transformers/main/ru/model_doc/wav2vec2#transformers.Wav2Vec2Processor.save_pretrained">save_pretrained()</a>. Не создавайте и не редактируйте файлы конфигурации предобработки вручную.</p> <blockquote class="tip"><p>См. <a href="/docs/transformers/main/ru/model_doc/qwen3_vl#transformers.Qwen3VLVideoProcessor">Qwen3VLVideoProcessor</a> для справки.</p></blockquote> <!--[1--><h2 class="relative group"><a id="register-the-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="#register-the-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></h2><!--]--><!----> <p>Добавьте новые классы в <code>__all__</code> в конце файла, затем пересоздайте <code>__init__.py</code> с помощью:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-bash "><!---->python utils/check_inits.py --fix_and_overwrite<!----></pre></div><!----> <p>Соотнесите новые классы с конфигурацией модели, чтобы классы <code>Auto</code> могли их загрузить. В сгенерированном файле авто-сопоставления вверху есть предупреждение. Не редактируйте его вручную. Добавьте или обновите конфигурацию модели, затем выполните:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-bash "><!---->python utils/check_auto.py --fix_and_overwrite<!----></pre></div><!----> <p>После генерации маппинга убедитесь, что тип модели присутствует в соответствующих маппингах в <code>src/transformers/models/auto/auto_mappings.py</code>.</p> <ul><li><code>IMAGE_PROCESSOR_MAPPING_NAMES</code> для <a href="/docs/transformers/main/ru/model_doc/auto#transformers.AutoImageProcessor">AutoImageProcessor</a></li> <li><code>VIDEO_PROCESSOR_MAPPING_NAMES</code> для <a href="/docs/transformers/main/ru/model_doc/auto#transformers.AutoVideoProcessor">AutoVideoProcessor</a></li></ul> <!--[1--><h2 class="relative group"><a id="testing" 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="#testing"><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="image-processor-tests" 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="#image-processor-tests"><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>tests/models/<model_name>/test_image_processing_<model_name>.py</code>. Определите тестер, наследующийся от <code>ImageProcessingTester</code>, и класс тестов, наследующийся от <code>ImageProcessingTestMixin</code> и <code>unittest.TestCase</code>.</p> <p>Тестер обработки изображений определяет атрибуты тестов по умолчанию, такие как аргументы инициализации процессора и параметры для создания случайных входных данных для тестов. Переопределяйте аргументы только в том случае, если они должны отличаться от значений по умолчанию для процессора изображений. Например, мы обычно тестируем с меньшими размерами изображений, чтобы тесты выполнялись быстро. Классы процессоров изображений выводятся автоматически из <code>IMAGE_PROCESSOR_MAPPING_NAMES</code>.</p> <p>Укажите <code>image_processor_tester_class</code> в тестовом классе. Миксин создаёт <code>self.image_processor_tester</code> и уже покрывает большинство необходимых тестовых методов.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> unittest | |
| <span class="hljs-keyword">from</span> transformers.testing_utils <span class="hljs-keyword">import</span> require_torch, require_vision | |
| <span class="hljs-keyword">from</span> ...test_image_processing_common <span class="hljs-keyword">import</span> ImageProcessingTestMixin, ImageProcessingTester | |
| <span class="hljs-keyword">class</span> <span class="hljs-title class_">MyModelImageProcessingTester</span>(<span class="hljs-title class_ inherited__">ImageProcessingTester</span>): | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, **kwargs</span>): | |
| <span class="hljs-comment"># Random test inputs kwargs</span> | |
| kwargs.setdefault(<span class="hljs-string">"batch_size"</span>, <span class="hljs-number">2</span>) <span class="hljs-comment"># default: 7 </span> | |
| kwargs.setdefault(<span class="hljs-string">"num_channels"</span>, <span class="hljs-number">4</span>) <span class="hljs-comment"># default: 3</span> | |
| kwargs.setdefault(<span class="hljs-string">"min_resolution"</span>, <span class="hljs-number">20</span>) <span class="hljs-comment"># default: 30</span> | |
| kwargs.setdefault(<span class="hljs-string">"max_resolution"</span>, <span class="hljs-number">100</span>) <span class="hljs-comment"># default: 400</span> | |
| <span class="hljs-comment"># Image processor init kwargs</span> | |
| kwargs.setdefault(<span class="hljs-string">"size"</span>, {<span class="hljs-string">"shortest_edge"</span>: <span class="hljs-number">20</span>}) | |
| kwargs.setdefault(<span class="hljs-string">"crop_size"</span>, {<span class="hljs-string">"height"</span>: <span class="hljs-number">18</span>, <span class="hljs-string">"width"</span>: <span class="hljs-number">18</span>}) | |
| <span class="hljs-built_in">super</span>().__init__(**kwargs) | |
| <span class="hljs-meta">@require_torch</span> | |
| <span class="hljs-meta">@require_vision</span> | |
| <span class="hljs-keyword">class</span> <span class="hljs-title class_">MyModelImageProcessingTest</span>(ImageProcessingTestMixin, unittest.TestCase): | |
| image_processor_tester_class = MyModelImageProcessingTester | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_inherits_from_mixin</span>(<span class="hljs-params">self</span>): | |
| <span class="hljs-comment"># Always iterate over all image processing classes</span> | |
| <span class="hljs-keyword">for</span> image_processing_class <span class="hljs-keyword">in</span> <span class="hljs-variable language_">self</span>.image_processing_classes.values(): | |
| <span class="hljs-comment"># self.image_processor_dict contains the default processor init kwargs</span> | |
| <span class="hljs-comment"># including overrides from the tester.</span> | |
| image_processor = image_processing_class(**<span class="hljs-variable language_">self</span>.image_processor_dict) | |
| <span class="hljs-variable language_">self</span>.assertIsInstance(image_processor, ImageProcessingMixin)<!----></pre></div><!----> <p>Добавляйте целенаправленные тесты для поведения, которое миксин не может вывести, например, для пользовательских правил изменения размера или специфичных для модели аргументов kwargs.</p> <p>Миксины для тестов постобработки доступны в <code>tests/test_image_processing_common.py</code> и добавляются поверх <code>ImageProcessingTestMixin</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_">MyModelImageProcessingTest</span>(ImageProcessingTestMixin, MyTaskPostProcessTestMixin, unittest.TestCase): | |
| image_processor_tester_class = MyModelImageProcessingTester<!----></pre></div><!----> <p>Тесты автоматически проверяют, что для вашей модели используются правильные миксины. Миксины для новых задач необходимо добавить в <code>tests/test_image_processing_common.py</code>.</p> <!--[2--><h3 class="relative group"><a id="video-processor-tests" 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="#video-processor-tests"><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>tests/models/<model_name>/test_video_processing_<model_name>.py</code> и наследуются от <code>VideoProcessingTestMixin</code>. Установите <code>fast_video_processing_class</code>, определите <code>video_processor_dict</code> и переопределите <code>input_name</code>, если модель использует ключ, отличный от <code>pixel_values_videos</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> transformers.testing_utils <span class="hljs-keyword">import</span> require_torch, require_vision | |
| <span class="hljs-keyword">from</span> transformers.utils <span class="hljs-keyword">import</span> is_torchvision_available | |
| <span class="hljs-keyword">from</span> ...test_video_processing_common <span class="hljs-keyword">import</span> VideoProcessingTestMixin | |
| <span class="hljs-meta">@require_torch</span> | |
| <span class="hljs-meta">@require_vision</span> | |
| <span class="hljs-keyword">class</span> <span class="hljs-title class_">MyModelVideoProcessingTest</span>(VideoProcessingTestMixin, unittest.TestCase): | |
| fast_video_processing_class = MyModelVideoProcessor <span class="hljs-keyword">if</span> is_torchvision_available() <span class="hljs-keyword">else</span> <span class="hljs-literal">None</span> | |
| input_name = <span class="hljs-string">"pixel_values_videos"</span> | |
| <span class="hljs-meta"> @property</span> | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">video_processor_dict</span>(<span class="hljs-params">self</span>): | |
| <span class="hljs-keyword">return</span> {<span class="hljs-string">"size"</span>: {<span class="hljs-string">"shortest_edge"</span>: <span class="hljs-number">224</span>}, <span class="hljs-string">"num_frames"</span>: <span class="hljs-number">16</span>}<!----></pre></div><!----> <p>Добавьте целенаправленные тесты видео для выборки кадров, обработки метаданных, декодированных видео-входов, входов в виде списка кадров и форм выходных данных. Если ваш процессор переименовывает <code>pixel_values_videos</code>, убедитесь, что возвращается переименованный ключ.</p> <p>Если у модели также есть <a href="/docs/transformers/main/ru/main_classes/processors#transformers.ProcessorMixin">ProcessorMixin</a>, который оборачивает процессор изображений или видео, добавьте <code>tests/models/<model_name>/test_processing_<model_name>.py</code> и унаследуйте класс от <code>ProcessorTesterMixin</code>. Задайте <code>processor_class</code> и переопределите класс-методы <code>_setup_<component>()</code> для компонентов, которые не могут быть созданы без аргументов. Используйте <code>_setup_test_attributes()</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> ...test_processing_common <span class="hljs-keyword">import</span> ProcessorTesterMixin | |
| <span class="hljs-keyword">class</span> <span class="hljs-title class_">MyModelProcessorTest</span>(ProcessorTesterMixin, unittest.TestCase): | |
| processor_class = MyModelProcessor | |
| <span class="hljs-meta"> @classmethod</span> | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">_setup_image_processor</span>(<span class="hljs-params">cls</span>): | |
| <span class="hljs-keyword">return</span> cls._get_component_class_from_processor(<span class="hljs-string">"image_processor"</span>)(size={<span class="hljs-string">"shortest_edge"</span>: <span class="hljs-number">224</span>}) | |
| <span class="hljs-meta"> @classmethod</span> | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">_setup_video_processor</span>(<span class="hljs-params">cls</span>): | |
| <span class="hljs-keyword">return</span> cls._get_component_class_from_processor(<span class="hljs-string">"video_processor"</span>)(num_frames=<span class="hljs-number">2</span>) | |
| <span class="hljs-meta"> @classmethod</span> | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">_setup_test_attributes</span>(<span class="hljs-params">cls, processor</span>): | |
| cls.image_token = <span class="hljs-built_in">getattr</span>(processor, <span class="hljs-string">"image_token"</span>, <span class="hljs-string">""</span>) | |
| cls.video_token = <span class="hljs-built_in">getattr</span>(processor, <span class="hljs-string">"video_token"</span>, <span class="hljs-string">""</span>)<!----></pre></div><!----> <!--[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="./auto_docstring">Автоматическая генерация docstrings</a>, чтобы автоматически генерировать согласованные docstrings с помощью <code>@auto_docstring</code>.</li> <li>Ознакомьтесь с руководствами <a href="./image_processors">Image processors</a> и <a href="./video_processors">Video processors</a>, чтобы узнать о поведении предобработки, доступном пользователю.</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/add_vision_processing_components.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, 6], | |
| data: [null,null], | |
| form: null, | |
| error: null | |
| }); | |
| }); | |
| } | |
| </script> | |
Xet Storage Details
- Size:
- 64.9 kB
- Xet hash:
- fd25ed079c8ccb1ee07551b67113faa966bf74f8de36a7890cfd2c1ddb562033
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.