Buckets:

mishig's picture
download
raw
35.2 kB
<meta charset="utf-8" /><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Contribuir&quot;,&quot;local&quot;:&quot;contribute&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Requisitos&quot;,&quot;local&quot;:&quot;requirements&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Crear la nueva clase HFQuantizer&quot;,&quot;local&quot;:&quot;create-new-hfquantizer-class&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Resumen de archivos&quot;,&quot;local&quot;:&quot;files-overview&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Comprender get_quantize_ops frente a get_weight_conversions&quot;,&quot;local&quot;:&quot;understanding-getquantizeops-vs-getweightconversions&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;get_quantize_ops — Cuantización en tiempo real&quot;,&quot;local&quot;:&quot;getquantizeops--quantize-on-the-fly&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;get_weight_conversions — Cargar puntos de control pre-cuantizados&quot;,&quot;local&quot;:&quot;getweightconversions--load-pre-quantized-checkpoints&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3}],&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/703.CAsO0Fiz.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/D-dvW--N.js" rel="modulepreload">
<!--a24xey--><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Contribute&quot;,&quot;local&quot;:&quot;contribute&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Requirements&quot;,&quot;local&quot;:&quot;requirements&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Create new HFQuantizer class&quot;,&quot;local&quot;:&quot;create-new-hfquantizer-class&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Files overview&quot;,&quot;local&quot;:&quot;files-overview&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Understanding get_quantize_ops vs get_weight_conversions&quot;,&quot;local&quot;:&quot;understanding-getquantizeops-vs-getweightconversions&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;get_quantize_ops — Quantize on the fly&quot;,&quot;local&quot;:&quot;getquantizeops--quantize-on-the-fly&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;get_weight_conversions — Load pre-quantized checkpoints&quot;,&quot;local&quot;:&quot;getweightconversions--load-pre-quantized-checkpoints&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3}],&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="contribute" 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="#contribute"><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><!---->Contribuir<!----></span></h1><!--]--><!----> <p>Transformers admite muchos métodos de cuantización, como QLoRA, GPTQ, LLM.int8 y AWQ. Sin embargo, aún existen muchos más enfoques de cuantización que no se han integrado todavía. Para facilitar la adición y el uso de estos métodos de cuantización con Transformers, utilice la clase <a href="/docs/transformers/main/es/main_classes/quantization#transformers.quantizers.HfQuantizer">HfQuantizer</a>. <a href="/docs/transformers/main/es/main_classes/quantization#transformers.quantizers.HfQuantizer">HfQuantizer</a> está diseñada para ser una clase auxiliar interna para agregar un método de cuantización, en lugar de algo que se aplique a cada módulo de PyTorch.</p> <p>Esta guía le mostrará cómo integrar un nuevo método de cuantización con <a href="/docs/transformers/main/es/main_classes/quantization#transformers.quantizers.HfQuantizer">HfQuantizer</a>.</p> <!--[1--><h2 class="relative group"><a id="requirements" 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="#requirements"><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><!---->Requisitos<!----></span></h2><!--]--><!----> <p>Antes de integrar un nuevo método de cuantización en Transformers, asegúrese de que el método cumpla con los siguientes requisitos. Solo se admiten los métodos de cuantización que pueden ejecutarse con módulos de PyTorch.</p> <ul><li><p>El método de cuantización está disponible a través de un paquete de Python que se puede instalar con pip (también está bien si solo puedes instalar el paquete desde el código fuente). Idealmente, el paquete de pip incluye kernels precompilados.</p></li> <li><p>El método puede ejecutarse en hardware de uso común (CPU, GPU, etc.).</p></li> <li><p>El método está envuelto en un <a href="https://pytorch.org/docs/stable/generated/torch.nn.Module.html" rel="nofollow">nn.Module</a> (<code>~bitsandbytes.nn.Linear8bitLt</code>, <code>~bitsandbytes.nn.Linear4bit</code>), y la capa lineal cuantizada debe tener la siguiente definición.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copiado</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">class</span> <span class="hljs-title class_">Linear4bit</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_">forward</span>(<span class="hljs-params">self, x</span>):
<span class="hljs-keyword">return</span> my_4bit_kernel(x, <span class="hljs-variable language_">self</span>.weight, <span class="hljs-variable language_">self</span>.bias)<!----></pre></div><!----> <p>De esta manera, los modelos de Transformers se cuantizan fácilmente reemplazando las instancias de <a href="https://pytorch.org/docs/stable/generated/torch.nn.Linear.html" rel="nofollow">nn.Linear</a> por una clase objetivo.</p></li> <li><p>El método de cuantización debe ser serializable. Puede guardar los pesos cuantizados localmente o subirlos al Hub.</p></li> <li><p>Asegúrese de que el paquete que contiene los kernels/primitivas de cuantización sea estable (sin cambios frecuentes que rompan la compatibilidad).</p></li></ul> <p>Algunos métodos de cuantización pueden requerir “pre-cuantizar” el modelo mediante calibración de datos (AWQ). En este caso, preferimos admitir solo la inferencia en Transformers y dejar que la biblioteca de terceros mantenida por la comunidad de ML se encargue de la cuantización del modelo.</p> <!--[1--><h2 class="relative group"><a id="create-new-hfquantizer-class" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#create-new-hfquantizer-class"><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><!---->Crear la nueva clase HFQuantizer<!----></span></h2><!--]--><!----> <ol start="0"><li><p>El mejor punto de partida sería echar un vistazo a otro método de cuantización, como Finegrained Fp8. Tendrá que actualizar o crear un total de tres archivos: el <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/utils/quantization_config.py" rel="nofollow">archivo de configuración</a>, el <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/integrations/finegrained_fp8.py" rel="nofollow">archivo de integración</a> y el <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/quantizers/quantizer_finegrained_fp8.py" rel="nofollow">archivo del cuantizador</a>.</p></li> <li><p>Cree una nueva clase de configuración de cuantización dentro de <a href="https://github.com/huggingface/transformers/blob/abbffc4525566a48a9733639797c812301218b83/src/transformers/utils/quantization_config.py" rel="nofollow">src/transformers/utils/quantization_config.py</a>. Añada la nueva configuración de cuantización a <a href="https://github.com/huggingface/transformers/blob/abbffc4525566a48a9733639797c812301218b83/src/transformers/__init__.py#L1088" rel="nofollow">_import_structure</a> dentro del archivo <a href="https://github.com/huggingface/transformers/blob/abbffc4525566a48a9733639797c812301218b83/src/transformers/__init__.py" rel="nofollow">src/transformers/__init__.py</a> de Transformers.</p></li> <li><p>Cree un nuevo archivo dentro de <a href="https://github.com/huggingface/transformers/tree/abbffc4525566a48a9733639797c812301218b83/src/transformers/quantizers" rel="nofollow">src/transformers/quantizers/</a> llamado <code>quantizer_your_method.py</code> y haga que herede de [`~quantizers.HfQuantizer`]. Asegúrese de agregar el nuevo cuantizador y la configuración de cuantización en el mapeo automático de cuantización en <a href="https://github.com/huggingface/transformers/blob/abbffc4525566a48a9733639797c812301218b83/src/transformers/quantizers/auto.py" rel="nofollow">src/transformers/quantizers/auto.py</a>.</p></li> <li><p>Defina los siguientes atributos de clase y métodos de propiedad para su método de cuantización:</p> <ul><li><code>requires_calibration</code>: Indica si el método de cuantización requiere un proceso de calibración de datos. Si se establece en <code>True</code>, solo se puede admitir la inferencia (con pesos cuantizados) y no la inferencia y la cuantización.</li> <li><code>is_serializable</code>: un método de propiedad para determinar si el método es serializable o no.</li> <li><code>is_trainable</code>: un método de propiedad para determinar si se pueden ajustar modelos sobre el método de cuantización (con o sin enfoques PEFT).</li></ul></li> <li><p>Escribe los métodos <code>validate_environment</code> y <code>update_dtype</code>. Estos métodos se llaman antes de crear el modelo cuantizado para asegurarse de que los usuarios utilicen la configuración correcta. Consulta otros cuantizadores para ver un ejemplo de cómo se implementan.</p></li> <li><p>Escriba el método <code>_process_model_before_weight_loading</code>. En Transformers, los modelos cuantizados se inicializan primero en el dispositivo <code>"meta"</code> antes de cargar los pesos. Esto significa que el método <code>_process_model_before_weight_loading</code> se encarga de manipular el esqueleto del modelo para reemplazar algunos módulos (<a href="https://pytorch.org/docs/stable/generated/torch.nn.Linear.html" rel="nofollow">nn.Linear</a>) con los módulos objetivo (módulos de cuantización).</p></li></ol> <p>Puede definir la lógica de reemplazo de módulos o cualquier otro método de utilidad creando un nuevo archivo en <a href="https://github.com/huggingface/transformers/tree/abbffc4525566a48a9733639797c812301218b83/src/transformers/integrations" rel="nofollow">transformers/src/integrations/</a> y exponiendo los métodos relevantes en el archivo <code>__init__.py</code> de esa carpeta.</p> <ol start="6"><li><p>Agregue el método <code>get_quantize_ops</code> a la clase cuantizadora si la cuantización admite la cuantización sobre la marcha. En transformers, materializamos cada tensor y aplicamos una secuencia de operaciones diferentes sobre él. En nuestro caso, la operación de cuantización ocurre al final. Debe crear un <code>XXXQuantize</code>, una subclase de <code>ConversionOps</code>, y agregar un método <code>convert</code>. En el método <code>convert</code>, debe cuantizar los pesos y devolver un diccionario de parámetros cuantizados.</p></li> <li><p>Agregue el método <code>get_weight_conversions</code> a la clase cuantizador si la cuantización admite la carga de pesos precuantizados. En transformers, podemos recopilar varios tensores y aplicar operaciones sobre ellos. Esto resulta especialmente útil cuando tenemos tensores en el checkpoint que deben reagruparse para recrear los tensores cuantizados.</p></li> <li><p>Escriba el método <code>_process_model_after_weight_loading</code> si es necesario. Este método permite implementar funciones adicionales que requieran manipular el modelo después de cargar los pesos.</p></li> <li><p>¡Documenta todo! Asegúrate de que tu método de cuantización esté documentado añadiendo un nuevo archivo bajo <code>docs/source/en/quantization</code>.</p></li> <li><p>Deberías añadir pruebas incluyendo el paquete en nuestro Dockerfile de pruebas nocturnas dentro de <code>docker/transformers-quantization-latest-gpu</code> y luego añadiendo un nuevo archivo de pruebas en <code>tests/quantization/xxx</code>. Puedes consultar los métodos de cuantización existentes para ver cómo se implementa.</p></li></ol> <!--[1--><h2 class="relative group"><a id="files-overview" 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="#files-overview"><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><!---->Resumen de archivos<!----></span></h2><!--]--><!----> <table><thead><tr><th>Archivo</th><th>Propósito</th></tr></thead><tbody><tr><td><code>utils/quantization_config.py</code></td><td>Defina <code>YourMethodConfig</code> heredando de <code>QuantizationConfigMixin</code></td></tr><tr><td><code>quantizers/quantizer_your_method.py</code></td><td>Implementa <code>YourMethodHfQuantizer</code> heredando de <code>HfQuantizer</code></td></tr><tr><td><code>integrations/your_method.py</code></td><td>Implementa subclases de <code>ConversionOps</code> y funciones auxiliares</td></tr><tr><td><code>quantizers/auto.py</code></td><td>Registra el cuantizador y la configuración en <code>AUTO_QUANTIZER_MAPPING</code> y <code>AUTO_QUANTIZATION_CONFIG_MAPPING</code></td></tr><tr><td><code>docs/source/en/quantization/your_method.md</code></td><td>Documentar el uso para los usuarios</td></tr><tr><td><code>tests/quantization/your_method/</code></td><td>Agregar pruebas de integración</td></tr></tbody></table> <!--[1--><h2 class="relative group"><a id="understanding-getquantizeops-vs-getweightconversions" 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="#understanding-getquantizeops-vs-getweightconversions"><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><!---->Comprender get_quantize_ops frente a get_weight_conversions<!----></span></h2><!--]--><!----> <p>Estos dos métodos gestionan diferentes escenarios para la carga de pesos. Comprender cuándo usar cada uno es esencial.</p> <!--[2--><h3 class="relative group"><a id="getquantizeops--quantize-on-the-fly" 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="#getquantizeops--quantize-on-the-fly"><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><!---->get_quantize_ops — Cuantización en tiempo real<!----></span></h3><!--]--><!----> <p>Utilice esto al cargar un <strong>punto de control no cuantizado</strong> (p. ej., pesos float16/bfloat16) y cuantizar durante la carga.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copiado</div><!----></button><!----></div> <pre class="language-text "><!---->Checkpoint: model.safetensors (float16 weights for example)
↓
get_quantize_ops → YourQuantize.convert()
↓
Result: Quantized weights in memory<!----></pre></div><!----> <p>El método <code>convert</code> recibe un tensor a la vez, lo cuantiza y puede devolver un diccionario de parámetros cuantizados, por ejemplo:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copiado</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">class</span> <span class="hljs-title class_">YourQuantize</span>(<span class="hljs-title class_ inherited__">ConversionOps</span>):
<span class="hljs-keyword">def</span> <span class="hljs-title function_">convert</span>(<span class="hljs-params">self, input_dict, model, full_layer_name, missing_keys, **kwargs</span>):
<span class="hljs-comment"># input_dict = {&quot;layer.weight&quot;: &lt;float16 tensor&gt;}</span>
value = <span class="hljs-built_in">list</span>(input_dict.values())[<span class="hljs-number">0</span>]
module, tensor_name = get_module_from_name(model, full_layer_name)
<span class="hljs-comment"># Quantize and assign</span>
quantized, scale, zero_point = your_quantize_fn(value)
<span class="hljs-keyword">return</span> {full_layer_name: quantized, full_layer_name + <span class="hljs-string">&quot;.scale&quot;</span>: scale, full_layer_name + <span class="hljs-string">&quot;.zero_point&quot;</span>: zero_point}<!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="getweightconversions--load-pre-quantized-checkpoints" 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="#getweightconversions--load-pre-quantized-checkpoints"><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><!---->get_weight_conversions — Cargar puntos de control pre-cuantizados<!----></span></h3><!--]--><!----> <p>Utilice esto al cargar un <strong>punto de control pre-cuantizado</strong> en el que los pesos cuantizados se guardan como varios componentes separados (como datos, escala y punto cero) y que deben combinarse en un solo tensor durante la carga. No todos los métodos de cuantización requieren esta etapa de reconstrucción: por ejemplo, algunos métodos como FP8 simplemente cargan los pesos y las escalas tal como están, sin combinarlos. Otros, como torchao, sí requieren reensamblar el tensor cuantizado a partir de sus múltiples componentes guardados.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copiado</div><!----></button><!----></div> <pre class="language-text "><!---->Checkpoint: model.safetensors (quantized components)
- layer._weight_qdata
- layer._weight_scale
- layer._weight_zero_point
↓
get_weight_conversions → WeightConverter + YourDeserialize.convert()
↓
Result: Reconstructed quantized tensor → layer.weight<!----></pre></div><!----> <p>El <code>WeightConverter</code> recopila los tensores relacionados en función de <code>source_patterns</code> y luego los pasa a su método <code>convert</code>:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copiado</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">def</span> <span class="hljs-title function_">get_weight_conversions</span>(<span class="hljs-params">self</span>):
<span class="hljs-keyword">if</span> <span class="hljs-variable language_">self</span>.pre_quantized:
<span class="hljs-keyword">return</span> [
WeightConverter(
source_patterns=[<span class="hljs-string">&quot;_weight_qdata&quot;</span>, <span class="hljs-string">&quot;_weight_scale&quot;</span>, <span class="hljs-string">&quot;_weight_zero_point&quot;</span>],
target_patterns=<span class="hljs-string">&quot;weight&quot;</span>,
operations=[YourDeserialize(<span class="hljs-variable language_">self</span>)],
),
]
<span class="hljs-keyword">return</span> []
<span class="hljs-keyword">class</span> <span class="hljs-title class_">YourDeserialize</span>(<span class="hljs-title class_ inherited__">ConversionOps</span>):
<span class="hljs-keyword">def</span> <span class="hljs-title function_">convert</span>(<span class="hljs-params">self, input_dict, model, full_layer_name, **kwargs</span>):
<span class="hljs-comment"># input_dict contains all collected tensors</span>
<span class="hljs-comment"># Reconstruct the quantized tensor from components</span>
reconstructed_tensor = reconstruct_from_components(input_dict)
<span class="hljs-keyword">return</span> {full_layer_name: reconstructed_tensor}<!----></pre></div><!----> <a class="!text-gray-400 !no-underline text-sm flex items-center not-prose mt-4" href="https://github.com/huggingface/transformers/blob/main/docs/source/en/quantization/contribute.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, 703],
data: [null,null],
form: null,
error: null
});
});
}
</script>

Xet Storage Details

Size:
35.2 kB
·
Xet hash:
5693c2579c92d179c974d04abe3808ff70193fd24664802da91329f9df1ddc81

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