Buckets:

hf-doc-build/doc / transformers /main /es /assisted_decoding.html
mishig's picture
download
raw
53 kB
<meta charset="utf-8" /><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Decodificación asistida&quot;,&quot;local&quot;:&quot;assisted-decoding&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Decodificación especulativa&quot;,&quot;local&quot;:&quot;speculative-decoding&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Decodificación mediante búsqueda de indicaciones&quot;,&quot;local&quot;:&quot;prompt-lookup-decoding&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Decodificación especulativa auto&quot;,&quot;local&quot;:&quot;self-speculative-decoding&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Capa de predicción de múltiples tokens (MTP)&quot;,&quot;local&quot;:&quot;multi-token-prediction-mtp-layer&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Drafter de predicción de múltiples tokens&quot;,&quot;local&quot;:&quot;multi-token-prediction-drafter&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Decodificación asistida universal&quot;,&quot;local&quot;:&quot;universal-assisted-decoding&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Verificación de conjuntos estáticos&quot;,&quot;local&quot;:&quot;static-ensemble-verification&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3}],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Recursos&quot;,&quot;local&quot;:&quot;resources&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2}],&quot;depth&quot;:1}"/>
<link href="/docs/transformers/main/en/_app/immutable/entry/start.DQNWq7h2.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/BihK2JwZ.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/zj-Gos1K.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/entry/app.oB0bM4f9.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/BKrnOUpv.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/chunks/qnJB2jjJ.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/hq0rnfO3.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/nodes/0.B0E0Itpp.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/DB3-R0mf.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/nodes/3.vkwMAj1u.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/pyBWJTcr.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/adfQQeGC.js" rel="modulepreload">
<!--14zg6nh--><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Assisted decoding&quot;,&quot;local&quot;:&quot;assisted-decoding&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Speculative decoding&quot;,&quot;local&quot;:&quot;speculative-decoding&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Prompt lookup decoding&quot;,&quot;local&quot;:&quot;prompt-lookup-decoding&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Self-speculative decoding&quot;,&quot;local&quot;:&quot;self-speculative-decoding&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Multi-token prediction (MTP) layer&quot;,&quot;local&quot;:&quot;multi-token-prediction-mtp-layer&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Multi-token prediction drafter&quot;,&quot;local&quot;:&quot;multi-token-prediction-drafter&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Universal assisted decoding&quot;,&quot;local&quot;:&quot;universal-assisted-decoding&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Static ensemble verification&quot;,&quot;local&quot;:&quot;static-ensemble-verification&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3}],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Resources&quot;,&quot;local&quot;:&quot;resources&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2}],&quot;depth&quot;:1}"/><!---->
<link href="/docs/transformers/main/en/_app/immutable/assets/0.tn0RQdqM.css" rel="modulepreload"> <!--[--><!--[0--><!--[--><!--[0--><!--[--><p></p> <div class="items-center shrink-0 min-w-[100px] max-sm:min-w-[50px] justify-end ml-auto flex" style="float: inline-end; margin-inline-start: 10px; display: inline-flex; position: relative; z-index: 10;"><div dir="ltr" class="inline-flex rounded-md max-sm:rounded-sm"><button class="inline-flex items-center gap-1 h-7 max-sm:h-7 px-2 max-sm:px-1.5 text-sm font-medium text-gray-800 border border-r-0 rounded-l-md max-sm:rounded-l-sm border-gray-200 bg-white hover:shadow-inner dark:border-gray-850 dark:bg-gray-950 dark:text-gray-200 dark:hover:bg-gray-800" aria-live="polite"><span class="inline-flex items-center justify-center rounded-md p-0.5 max-sm:p-0 hover:text-gray-800 dark:hover:text-gray-200"><svg class="sm:size-3.5 size-3" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----></span> <span dir="auto">Copy page</span></button> <button class="inline-flex items-center justify-center w-6 max-sm:w-5 h-7 max-sm:h-7 disabled:pointer-events-none text-sm text-gray-500 hover:text-gray-700 dark:hover:text-white rounded-r-md max-sm:rounded-r-sm border border-l transition border-gray-200 bg-white hover:shadow-inner dark:border-gray-850 dark:bg-gray-950 dark:text-gray-200 dark:hover:bg-gray-800" aria-haspopup="menu" aria-expanded="false" aria-label="Open copy menu"><svg class="transition-transform text-gray-400 overflow-visible sm:size-3.5 size-3 rotate-0" width="1em" height="1em" viewBox="0 0 12 7" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 1L6 6L11 1" stroke="currentColor"></path></svg><!----></button></div> <!--[-1--><!--]--></div><!----> <!--[0--><h1 class="relative group"><a id="assisted-decoding" 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="#assisted-decoding"><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><!---->Decodificación asistida<!----></span></h1><!--]--><!----> <p>La decodificación asistida acelera la generación de texto al permitir que un modelo auxiliar proponga tokens candidatos antes de que el modelo principal los confirme. El modelo principal verifica los tokens candidatos en una sola pasada hacia adelante. El modelo auxiliar es rápido y económico, y puede reemplazar a decenas de pasadas hacia adelante más costosas del modelo principal.</p> <p>Esta guía cubre los métodos de decodificación asistida en Transformers.</p> <!--[1--><h2 class="relative group"><a id="speculative-decoding" 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="#speculative-decoding"><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><!---->Decodificación especulativa<!----></span></h2><!--]--><!----> <p><a href="https://hf.co/papers/2211.17192" rel="nofollow">Decodificación especulativa</a> utiliza un modelo asistente más pequeño para redactar tokens candidatos. El modelo principal verifica estos tokens en una sola pasada. Los tokens validados entran en la salida final y los tokens rechazados activan el muestreo estándar. La generación es más rápida porque el modelo principal realiza menos pasadas hacia adelante costosas.</p> <p>El método funciona mejor cuando el modelo asistente es significativamente más pequeño que el modelo principal y utiliza el mismo tokenizer. La decodificación especulativa admite la búsqueda codiciosa y el muestreo, pero no las entradas por lotes.</p> <p>Pasa <code>assistant_model</code> a <a href="/docs/transformers/main/es/main_classes/text_generation#transformers.GenerationMixin.generate">generate()</a>. Establece <code>do_sample=True</code> para re-muestrear si la validación de tokens falla.</p> <blockquote class="tip"><p>Pase <code>cache_implementation="static"</code> para ejecutar el paso de verificación del modelo principal a través de <a href="./perf_torch_compile">torch.compile</a>, consulte <a href="./kv_cache#fixed-size-cache">KV cache</a>. El asistente sigue ejecutándose de forma ágil, ya que su longitud de borrador varía entre rondas.</p></blockquote> <div class="flex space-x-2 items-center my-1.5 mr-8 h-7 !pl-0 -mx-3 md:mx-0"><!--[--><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd border-gray-800 bg-black dark:bg-gray-700 text-white">búsqueda voraz</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">sampling</div><!--]--></div> <div class="language-select"><div><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">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;HuggingFaceTB/SmolLM-1.7B&quot;</span>)
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;HuggingFaceTB/SmolLM-1.7B&quot;</span>, dtype=<span class="hljs-string">&quot;auto&quot;</span>)
assistant_model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;HuggingFaceTB/SmolLM-135M&quot;</span>, dtype=<span class="hljs-string">&quot;auto&quot;</span>)
inputs = tokenizer(<span class="hljs-string">&quot;Hugging Face is an open-source company&quot;</span>, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>)
outputs = model.generate(**inputs, assistant_model=assistant_model)
tokenizer.batch_decode(outputs, skip_special_tokens=<span class="hljs-literal">True</span>)
<span class="hljs-string">&#x27;Hugging Face is an open-source company that provides a platform for developers to build and deploy machine&#x27;</span><!----></pre></div><!----> <p>El argumento <code>assistant_model</code> también está disponible en la API de <a href="/docs/transformers/main/es/main_classes/pipelines#transformers.Pipeline">Pipeline</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> Copiado</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> pipeline
pipeline = pipeline(
<span class="hljs-string">&quot;text-generation&quot;</span>,
model=<span class="hljs-string">&quot;meta-llama/Llama-3.1-8B&quot;</span>,
assistant_model=<span class="hljs-string">&quot;meta-llama/Llama-3.2-1B&quot;</span>,
dtype=<span class="hljs-string">&quot;auto&quot;</span>
)
pipeline(<span class="hljs-string">&quot;Hugging Face is an open-source company, &quot;</span>, max_new_tokens=<span class="hljs-number">50</span>, do_sample=<span class="hljs-literal">False</span>)<!----></pre></div><!----><!----></div><!----> <div hidden=""><p>Establezca <code>temperature</code> para controlar la aleatoriedad. Temperaturas más bajas suelen mejorar la latencia.</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">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;HuggingFaceTB/SmolLM-1.7B&quot;</span>)
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;HuggingFaceTB/SmolLM-1.7B&quot;</span>, dtype=<span class="hljs-string">&quot;auto&quot;</span>)
assistant_model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;HuggingFaceTB/SmolLM-135M&quot;</span>, dtype=<span class="hljs-string">&quot;auto&quot;</span>)
inputs = tokenizer(<span class="hljs-string">&quot;Hugging Face is an open-source company&quot;</span>, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>)
outputs = model.generate(**inputs, assistant_model=assistant_model, do_sample=<span class="hljs-literal">True</span>, temperature=<span class="hljs-number">0.5</span>)
tokenizer.batch_decode(outputs, skip_special_tokens=<span class="hljs-literal">True</span>)
<span class="hljs-string">&#x27;Hugging Face is an open-source company that is dedicated to creating a better world through technology.&#x27;</span><!----></pre></div><!----><!----></div><!----><!----></div><!----> <!--[1--><h2 class="relative group"><a id="prompt-lookup-decoding" 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="#prompt-lookup-decoding"><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><!---->Decodificación mediante búsqueda de indicaciones<!----></span></h2><!--]--><!----> <p>El decodificado mediante búsqueda en el prompt no requiere un modelo asistente. Encuentra n-gramas superpuestos en el prompt para proponer tokens candidatos. Si no existe coincidencia, recurre a la decodificación autoregresiva normal. Esto es adecuado para tareas basadas en la entrada, como la resumición y la traducción, porque los tokens candidatos suelen reflejar patrones locales del texto de origen.</p> <p>Pase <code>prompt_lookup_num_tokens</code> a <a href="/docs/transformers/main/es/main_classes/text_generation#transformers.GenerationMixin.generate">generate()</a>. Esto define cuántos tokens el algoritmo intenta copiar de una parte anterior del prompt cuando detecta un patrón repetido.</p> <div class="flex space-x-2 items-center my-1.5 mr-8 h-7 !pl-0 -mx-3 md:mx-0"><!--[--><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd border-gray-800 bg-black dark:bg-gray-700 text-white">decodificación codiciosa</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">sampling</div><!--]--></div> <div class="language-select"><div><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">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;HuggingFaceTB/SmolLM-1.7B&quot;</span>)
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;HuggingFaceTB/SmolLM-1.7B&quot;</span>, dtype=<span class="hljs-string">&quot;auto&quot;</span>)
inputs = tokenizer(<span class="hljs-string">&quot;Hugging Face is an open-source company&quot;</span>, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>)
outputs = model.generate(**inputs, prompt_lookup_num_tokens=<span class="hljs-number">5</span>)
tokenizer.batch_decode(outputs, skip_special_tokens=<span class="hljs-literal">True</span>)
<span class="hljs-string">&#x27;Hugging Face is an open-source company that provides a platform for developers to build and deploy machine learning models. It offers a variety of tools&#x27;</span><!----></pre></div><!----></div><!----> <div hidden=""><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">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;HuggingFaceTB/SmolLM-1.7B&quot;</span>)
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;HuggingFaceTB/SmolLM-1.7B&quot;</span>, dtype=<span class="hljs-string">&quot;auto&quot;</span>)
inputs = tokenizer(<span class="hljs-string">&quot;Hugging Face is an open-source company&quot;</span>, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>)
outputs = model.generate(**inputs, prompt_lookup_num_tokens=<span class="hljs-number">5</span>, do_sample=<span class="hljs-literal">True</span>, temperature=<span class="hljs-number">0.5</span>)
tokenizer.batch_decode(outputs, skip_special_tokens=<span class="hljs-literal">True</span>)
<span class="hljs-string">&#x27;Hugging Face is an open-source company that provides a platform for developers to build and deploy machine learning models. It offers a variety of tools&#x27;</span><!----></pre></div><!----></div><!----><!----></div><!----> <!--[1--><h2 class="relative group"><a id="self-speculative-decoding" 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="#self-speculative-decoding"><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><!---->Decodificación especulativa auto<!----></span></h2><!--]--><!----> <p>La decodificación especulativa autocontenida utiliza las capas intermedias de un modelo como asistente para proponer tokens candidatos. Si la propuesta coincide, el modelo finaliza de forma anticipada y las capas restantes verifican o corrigen los tokens.</p> <p>Dado que todo es un solo modelo, los pesos y las cachés se comparten, lo que aumenta la velocidad sin un sobrecosto adicional de memoria. Esta técnica solo funciona para modelos entrenados para admitir logits de salida temprana desde capas intermedias.</p> <p>Pasa <code>assistant_early_exit</code> a <a href="/docs/transformers/main/es/main_classes/text_generation#transformers.GenerationMixin.generate">generate()</a> para establecer la capa de salida.</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">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;facebook/layerskip-llama3.2-1B&quot;</span>)
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;facebook/layerskip-llama3.2-1B&quot;</span>, dtype=<span class="hljs-string">&quot;auto&quot;</span>)
inputs = tokenizer(<span class="hljs-string">&quot;Hugging Face is an open-source company&quot;</span>, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>)
outputs = model.generate(**inputs, assistant_early_exit=<span class="hljs-number">4</span>, do_sample=<span class="hljs-literal">False</span>, max_new_tokens=<span class="hljs-number">20</span>)
tokenizer.batch_decode(outputs, skip_special_tokens=<span class="hljs-literal">True</span>)<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="multi-token-prediction-mtp-layer" 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="#multi-token-prediction-mtp-layer"><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><!---->Capa de predicción de múltiples tokens (MTP)<!----></span></h2><!--]--><!----> <p>La capa de predicción de múltiples tokens (MTP) genera tokens candidatos mediante capas de predicción adicionales que provienen del propio checkpoint del modelo principal. Las capas MTP reutilizan los embeddings y la cabeza de salida del modelo principal. Cada capa MTP genera un token, por lo que el número de candidatos por paso coincide con la cantidad de capas MTP del checkpoint. El modelo principal verifica los borradores en una sola pasada hacia adelante.</p> <p>MTP solo funciona con puntos de control entrenados con capas MTP, como <a href="https://huggingface.co/deepseek-ai/DeepSeek-V3" rel="nofollow">DeepSeek-V3</a> y <a href="https://huggingface.co/zai-org/GLM-4.5" rel="nofollow">GLM-4.5</a>. Estos puntos de control incluyen pesos MTP y establecen <code>num_mtp_layers</code> en su configuración, que aparece como <code>num_nextn_predict_layers</code> en <code>config.json</code>.</p> <p>Pase <code>use_mtp=True</code> a <a href="/docs/transformers/main/es/main_classes/text_generation#transformers.GenerationMixin.generate">generate()</a>, lo que genera un error si el modelo no tiene capas MTP. Al igual que la decodificación especulativa, MTP admite búsqueda codiciosa y muestreo, pero no entradas por lotes.</p> <p>Aquí, MTP se refiere a las capas de predicción incluidas en el checkpoint objetivo, como en DeepSeek-V3 y GLM-4.5. Gemma 4 utiliza un checkpoint de asistente separado para la decodificación MTP. Pásalo como <code>assistant_model</code> (ver <a href="#multi-token-prediction-drafter">Drafter de predicción de múltiples tokens</a>).</p> <p>El pipeline <code>text-generation</code> y <a href="/docs/transformers/main/es/main_classes/text_generation#transformers.GenerationMixin.generate">generate()</a> aceptan ambos <code>use_mtp=True</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">from</span> transformers <span class="hljs-keyword">import</span> pipeline
pipe = pipeline(
<span class="hljs-string">&quot;text-generation&quot;</span>,
model=<span class="hljs-string">&quot;zai-org/GLM-4.5-Air&quot;</span>,
device_map=<span class="hljs-string">&quot;auto&quot;</span>,
)
outputs = pipe(
<span class="hljs-string">&quot;Hugging Face is an open-source company&quot;</span>,
use_mtp=<span class="hljs-literal">True</span>,
do_sample=<span class="hljs-literal">False</span>,
max_new_tokens=<span class="hljs-number">50</span>,
add_special_tokens=<span class="hljs-literal">True</span>,
return_full_text=<span class="hljs-literal">True</span>,
)
[output[<span class="hljs-string">&quot;generated_text&quot;</span>] <span class="hljs-keyword">for</span> output <span class="hljs-keyword">in</span> outputs]<!----></pre></div><!----> <p>Alternativamente, puede inferir de la siguiente manera.</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">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;zai-org/GLM-4.5-Air&quot;</span>)
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;zai-org/GLM-4.5-Air&quot;</span>, device_map=<span class="hljs-string">&quot;auto&quot;</span>)
inputs = tokenizer(<span class="hljs-string">&quot;Hugging Face is an open-source company&quot;</span>, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(model.device)
outputs = model.generate(**inputs, use_mtp=<span class="hljs-literal">True</span>, do_sample=<span class="hljs-literal">False</span>, max_new_tokens=<span class="hljs-number">50</span>)
tokenizer.batch_decode(outputs, skip_special_tokens=<span class="hljs-literal">True</span>)<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="multi-token-prediction-drafter" 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="#multi-token-prediction-drafter"><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><!---->Drafter de predicción de múltiples tokens<!----></span></h2><!--]--><!----> <p>Un redactor MTP es un modelo asistente ligero que se carga desde un punto de control (checkpoint) separado. Propone tokens candidatos para que el modelo objetivo los verifique. El redactor utiliza las incrustaciones de entrada del modelo objetivo y atiende a su caché KV. Comienza con los estados ocultos del modelo objetivo y luego redacta tokens de forma autoregresiva. Para cada token siguiente, reintroduce su estado oculto proyectado en el redactor. El modelo objetivo verifica los tokens redactados en una sola pasada hacia adelante, tal como en la decodificación especulativa.</p> <p>A diferencia de las capas MTP, que forman parte del checkpoint objetivo y comparten su cabeza de salida, un redactor MTP es un modelo asistente independiente. Utiliza los embeddings de entrada y la caché KV del modelo objetivo para proponer tokens.</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">from</span> transformers <span class="hljs-keyword">import</span> AutoProcessor, AutoModelForCausalLM
processor = AutoProcessor.from_pretrained(<span class="hljs-string">&quot;google/gemma-4-E4B-it&quot;</span>)
target_model = AutoModelForCausalLM.from_pretrained(
<span class="hljs-string">&quot;google/gemma-4-E4B-it&quot;</span>,
dtype=<span class="hljs-string">&quot;auto&quot;</span>,
device_map=<span class="hljs-string">&quot;auto&quot;</span>,
)
assistant_model = AutoModelForCausalLM.from_pretrained(
<span class="hljs-string">&quot;google/gemma-4-E4B-it-assistant&quot;</span>,
dtype=<span class="hljs-string">&quot;auto&quot;</span>,
device_map=<span class="hljs-string">&quot;auto&quot;</span>,
)
messages = [
{<span class="hljs-string">&quot;role&quot;</span>: <span class="hljs-string">&quot;system&quot;</span>, <span class="hljs-string">&quot;content&quot;</span>: <span class="hljs-string">&quot;You are a helpful assistant.&quot;</span>},
{<span class="hljs-string">&quot;role&quot;</span>: <span class="hljs-string">&quot;user&quot;</span>, <span class="hljs-string">&quot;content&quot;</span>: <span class="hljs-string">&quot;Write a short joke about saving RAM.&quot;</span>},
]
inputs = processor.apply_chat_template(
messages,
tokenize=<span class="hljs-literal">True</span>,
return_dict=<span class="hljs-literal">True</span>,
return_tensors=<span class="hljs-string">&quot;pt&quot;</span>,
add_generation_prompt=<span class="hljs-literal">True</span>,
enable_thinking=<span class="hljs-literal">False</span>
).to(target_model.device)
input_len = inputs[<span class="hljs-string">&quot;input_ids&quot;</span>].shape[-<span class="hljs-number">1</span>]
outputs = target_model.generate(
**inputs,
assistant_model=assistant_model,
max_new_tokens=<span class="hljs-number">256</span>,
)
response = processor.decode(outputs[<span class="hljs-number">0</span>][input_len:], skip_special_tokens=<span class="hljs-literal">False</span>)
processor.parse_response(response)<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="universal-assisted-decoding" 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="#universal-assisted-decoding"><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><!---->Decodificación asistida universal<!----></span></h2><!--]--><!----> <p>El decodificado asistido universal (UAD) hace posible el decodificado especulativo incluso cuando los modelos principal y asistente tienen tokenizadores diferentes. Permite emparejar cualquier modelo asistente pequeño con el modelo principal. Los tokens candidatos se re-codifican y el algoritmo calcula la subsecuencia común más larga para que la continuación permanezca alineada.</p> <p>Pase <code>tokenizer</code>, <code>assistant_tokenizer</code> y <code>assistant_model</code> a <a href="/docs/transformers/main/es/main_classes/text_generation#transformers.GenerationMixin.generate">generate()</a> para habilitar UAD.</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">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AutoTokenizer
assistant_tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;double7/vicuna-68m&quot;</span>)
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;google/gemma-2-9b&quot;</span>)
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;google/gemma-2-9b&quot;</span>, dtype=<span class="hljs-string">&quot;auto&quot;</span>)
assistant_model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;double7/vicuna-68m&quot;</span>, dtype=<span class="hljs-string">&quot;auto&quot;</span>)
inputs = tokenizer(<span class="hljs-string">&quot;Hugging Face is an open-source company&quot;</span>, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>)
outputs = model.generate(**inputs, assistant_model=assistant_model, tokenizer=tokenizer, assistant_tokenizer=assistant_tokenizer)
tokenizer.batch_decode(outputs, skip_special_tokens=<span class="hljs-literal">True</span>)
<span class="hljs-string">&#x27;Hugging Face is an open-source company that is dedicated to creating a better world through technology.&#x27;</span><!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="static-ensemble-verification" 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="#static-ensemble-verification"><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><!---->Verificación de conjuntos estáticos<!----></span></h3><!--]--><!----> <p>La decodificación especulativa estándar es <em>sin pérdida</em>: garantiza que la distribución de salida coincida exactamente con la del modelo objetivo. La <a href="https://arxiv.org/abs/2604.07622" rel="nofollow">verificación de conjunto estática</a> relaja esta condición al verificar contra una mezcla de las distribuciones del modelo objetivo y del borrador, lo que aumenta la tasa de aceptación (inferencia más rápida) a costa de que la distribución de salida sea una mezcla en lugar de la distribución objetivo exacta. Un valor inicial recomendado es <code>0.7</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-python "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;HuggingFaceTB/SmolLM-1.7B&quot;</span>)
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;HuggingFaceTB/SmolLM-1.7B&quot;</span>, dtype=<span class="hljs-string">&quot;auto&quot;</span>)
assistant_model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;HuggingFaceTB/SmolLM-135M&quot;</span>, dtype=<span class="hljs-string">&quot;auto&quot;</span>)
inputs = tokenizer(<span class="hljs-string">&quot;Hugging Face is an open-source company&quot;</span>, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>)
outputs = model.generate(**inputs, assistant_model=assistant_model, assistant_ensemble_weight=<span class="hljs-number">0.7</span>, do_sample=<span class="hljs-literal">True</span>)
tokenizer.batch_decode(outputs, skip_special_tokens=<span class="hljs-literal">True</span>)<!----></pre></div><!----> <p>Esto requiere logits de candidatos del modelo asistente y no se admite con la decodificación mediante búsqueda de indicio.</p> <!--[1--><h2 class="relative group"><a id="resources" 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="#resources"><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><!---->Recursos<!----></span></h2><!--]--><!----> <ul><li>Lea la publicación de blog <a href="https://huggingface.co/blog/assisted-generation" rel="nofollow">Assisted Generation: a new direction toward low-latency text generation</a> para obtener más contexto sobre la latencia de la generación de texto y la generación asistida.</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/assisted_decoding.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_1yucsoj = {
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.DQNWq7h2.js"),
import("/docs/transformers/main/en/_app/immutable/entry/app.oB0bM4f9.js")
]).then(([kit, app]) => {
kit.start(app, element, {
node_ids: [0, 3],
data: [null,null],
form: null,
error: null
});
});
}
</script>

Xet Storage Details

Size:
53 kB
·
Xet hash:
d74aee826a738291afe58b8953395268eed8e01b875db75e36cf14c266378a3c

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