Buckets:
| <meta charset="utf-8" /><meta name="hf:doc:metadata" content="{"title":"Conceptos básicos de chat","local":"conceptos-básicos-de-chat","sections":[{"title":"CLI de chat","local":"cli-de-chat","sections":[],"depth":2},{"title":"TextGenerationPipeline","local":"textgenerationpipeline","sections":[],"depth":2},{"title":"Rendimiento y uso de memoria","local":"rendimiento-y-uso-de-memoria","sections":[],"depth":2}],"depth":1}"> | |
| <link href="/docs/transformers/main/es/_app/immutable/assets/0.e3b0c442.css" rel="modulepreload"> | |
| <link rel="modulepreload" href="/docs/transformers/main/es/_app/immutable/entry/start.ef1076ce.js"> | |
| <link rel="modulepreload" href="/docs/transformers/main/es/_app/immutable/chunks/scheduler.80ba32b1.js"> | |
| <link rel="modulepreload" href="/docs/transformers/main/es/_app/immutable/chunks/singletons.45a91c7d.js"> | |
| <link rel="modulepreload" href="/docs/transformers/main/es/_app/immutable/chunks/index.ee85231c.js"> | |
| <link rel="modulepreload" href="/docs/transformers/main/es/_app/immutable/chunks/paths.258ac66e.js"> | |
| <link rel="modulepreload" href="/docs/transformers/main/es/_app/immutable/entry/app.b1bc2a15.js"> | |
| <link rel="modulepreload" href="/docs/transformers/main/es/_app/immutable/chunks/preload-helper.dd42f084.js"> | |
| <link rel="modulepreload" href="/docs/transformers/main/es/_app/immutable/chunks/index.2df20f66.js"> | |
| <link rel="modulepreload" href="/docs/transformers/main/es/_app/immutable/nodes/0.8f4d7807.js"> | |
| <link rel="modulepreload" href="/docs/transformers/main/es/_app/immutable/chunks/each.e59479a4.js"> | |
| <link rel="modulepreload" href="/docs/transformers/main/es/_app/immutable/nodes/9.79f0fb14.js"> | |
| <link rel="modulepreload" href="/docs/transformers/main/es/_app/immutable/chunks/MermaidChart.svelte_svelte_type_style_lang.9fb840ae.js"> | |
| <link rel="modulepreload" href="/docs/transformers/main/es/_app/immutable/chunks/CodeBlock.1f1e6bf6.js"><!-- HEAD_svelte-u9bgzb_START --><meta name="hf:doc:metadata" content="{"title":"Conceptos básicos de chat","local":"conceptos-básicos-de-chat","sections":[{"title":"CLI de chat","local":"cli-de-chat","sections":[],"depth":2},{"title":"TextGenerationPipeline","local":"textgenerationpipeline","sections":[],"depth":2},{"title":"Rendimiento y uso de memoria","local":"rendimiento-y-uso-de-memoria","sections":[],"depth":2}],"depth":1}"><!-- HEAD_svelte-u9bgzb_END --> <p></p> <div class="items-center shrink-0 min-w-[100px] max-sm:min-w-[50px] justify-end ml-auto flex" style="float: right; margin-left: 10px; display: inline-flex; position: relative; z-index: 10;"><div 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>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> </div> <h1 class="relative group"><a id="conceptos-básicos-de-chat" 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="#conceptos-básicos-de-chat"><span><svg class="" 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>Conceptos básicos de chat</span></h1> <p data-svelte-h="svelte-1i1n5oi">Los modelos de chat son modelos conversacionales a los que puedes enviar un mensaje y recibir una respuesta. La mayoría de los modelos de lenguaje desde mediados de 2023 en adelante son modelos de chat y pueden denominarse modelos “instruct” o “instruction-tuned”. Los modelos que no soportan chat suelen llamarse modelos “base” o “preentrenados”.</p> <p data-svelte-h="svelte-3hyxq5">Los modelos más grandes y recientes son generalmente más capaces, pero los modelos especializados en ciertos dominios (texto médico, legal, idiomas distintos al inglés, etc.) a menudo pueden superar a estos modelos más grandes. Prueba tablas de clasificación como <a href="https://hf.co/spaces/HuggingFaceH4/open_llm_leaderboard" rel="nofollow">OpenLLM</a> y <a href="https://chat.lmsys.org/?leaderboard" rel="nofollow">LMSys Chatbot Arena</a> para ayudarte a identificar el mejor modelo para tu caso de uso.</p> <p data-svelte-h="svelte-1vlm7c7">Esta guía te muestra cómo cargar rápidamente modelos de chat en Transformers desde la línea de comandos, cómo construir y formatear una conversación, y cómo chatear usando el <code>TextGenerationPipeline</code>.</p> <h2 class="relative group"><a id="cli-de-chat" 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="#cli-de-chat"><span><svg class="" 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>CLI de chat</span></h2> <p data-svelte-h="svelte-eq567g">Después de <a href="./installation">instalar Transformers</a>, puedes chatear con un modelo directamente desde la línea de comandos. El siguiente comando inicia una sesión interactiva con un modelo, con algunos comandos base listados al inicio de la sesión.</p> <blockquote data-svelte-h="svelte-1yh4u0"><p>Para los siguientes comandos, asegúrate de que <a href="https://huggingface.co/docs/transformers/main/en/serving" rel="nofollow"><code>transformers serve</code> esté ejecutándose</a>.</p></blockquote> <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 class="" 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> Copied</div></button></div> <pre class="language-bash "><!-- HTML_TAG_START -->transformers chat Qwen/Qwen2.5-0.5B-Instruct<!-- HTML_TAG_END --></pre></div> <div class="flex justify-center" data-svelte-h="svelte-1q6uti0"><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/transformers-chat-cli.png"></div> <p data-svelte-h="svelte-ts2fou">Puedes iniciar el CLI con flags arbitrarios de <code>generate</code>, con el formato <code>arg_1=valor_1 arg_2=valor_2 ...</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 class="" 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> Copied</div></button></div> <pre class="language-bash "><!-- HTML_TAG_START -->transformers chat Qwen/Qwen2.5-0.5B-Instruct do_sample=False max_new_tokens=10<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-jwvgux">Para una lista completa de opciones, ejecuta el siguiente comando.</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 class="" 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> Copied</div></button></div> <pre class="language-bash "><!-- HTML_TAG_START -->transformers chat -h<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-ddt7rj">El chat está implementado sobre <a href="./model_doc/auto">AutoClass</a>, usando herramientas de <a href="./llm_tutorial">generación de texto</a> y <a href="./chat_templating">chat</a>. Usa el CLI <code>transformers serve</code> internamente (<a href="./serve-cli/serving">docs</a>).</p> <h2 class="relative group"><a id="textgenerationpipeline" 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="#textgenerationpipeline"><span><svg class="" 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>TextGenerationPipeline</span></h2> <p data-svelte-h="svelte-1qg79xx"><code>TextGenerationPipeline</code> es una clase de alto nivel para generación de texto con un “modo chat”. El modo chat se activa cuando se detecta un modelo conversacional y el prompt de chat está <a href="./llm_tutorial#wrong-prompt-format">correctamente formateado</a>.</p> <p data-svelte-h="svelte-tfw8b7">Los modelos de chat aceptan una lista de mensajes (el historial de chat) como entrada. Cada mensaje es un diccionario con las claves <code>role</code> y <code>content</code>. | |
| Para iniciar el chat, agrega un solo mensaje <code>user</code>. Opcionalmente puedes incluir un mensaje <code>system</code> para dar al modelo instrucciones sobre cómo comportarse.</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 class="" 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> Copied</div></button></div> <pre class="language-py "><!-- HTML_TAG_START -->chat = [ | |
| {<span class="hljs-string">"role"</span>: <span class="hljs-string">"system"</span>, <span class="hljs-string">"content"</span>: <span class="hljs-string">"Eres un asistente científico útil."</span>}, | |
| {<span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: <span class="hljs-string">"Oye, ¿puedes explicarme la gravedad?"</span>} | |
| ]<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-zoqvc8">Crea el <code>TextGenerationPipeline</code> y pásale <code>chat</code>. Para modelos grandes, configurar <a href="./models#big-model-inference">device_map=“auto”</a> ayuda a cargar el modelo más rápido y lo coloca automáticamente en el dispositivo más rápido disponible.</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 class="" 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> Copied</div></button></div> <pre class="language-py "><!-- HTML_TAG_START --><span class="hljs-keyword">import</span> torch | |
| <span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> pipeline | |
| pipeline = pipeline(task=<span class="hljs-string">"text-generation"</span>, model=<span class="hljs-string">"HuggingFaceTB/SmolLM2-1.7B-Instruct"</span>, dtype=<span class="hljs-string">"auto"</span>, device_map=<span class="hljs-string">"auto"</span>) | |
| response = pipeline(chat, max_new_tokens=<span class="hljs-number">512</span>) | |
| <span class="hljs-built_in">print</span>(response[<span class="hljs-number">0</span>][<span class="hljs-string">"generated_text"</span>][-<span class="hljs-number">1</span>][<span class="hljs-string">"content"</span>])<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1jupndd">Si esto funciona correctamente, ¡deberías ver una respuesta del modelo! Si quieres continuar la conversación, necesitas actualizar el historial de chat con la respuesta del modelo. Puedes hacerlo agregando el texto a <code>chat</code> (usando el rol <code>assistant</code>), o leyendo <code>response[0]["generated_text"]</code>, que contiene el historial completo del chat, incluyendo la respuesta más reciente.</p> <p data-svelte-h="svelte-1bz9bvc">Una vez que tienes la respuesta del modelo, puedes continuar la conversación agregando un nuevo mensaje <code>user</code> al historial de chat.</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 class="" 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> Copied</div></button></div> <pre class="language-py "><!-- HTML_TAG_START -->chat = response[<span class="hljs-number">0</span>][<span class="hljs-string">"generated_text"</span>] | |
| chat.append( | |
| {<span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: <span class="hljs-string">"¡Wow! ¿Pero se puede reconciliar con la mecánica cuántica?"</span>} | |
| ) | |
| response = pipeline(chat, max_new_tokens=<span class="hljs-number">512</span>) | |
| <span class="hljs-built_in">print</span>(response[<span class="hljs-number">0</span>][<span class="hljs-string">"generated_text"</span>][-<span class="hljs-number">1</span>][<span class="hljs-string">"content"</span>])<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-11wz724">Repitiendo este proceso, puedes continuar la conversación tanto como quieras, al menos hasta que el modelo se quede sin ventana de contexto o te quedes sin memoria.</p> <h2 class="relative group"><a id="rendimiento-y-uso-de-memoria" 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="#rendimiento-y-uso-de-memoria"><span><svg class="" 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>Rendimiento y uso de memoria</span></h2> <p data-svelte-h="svelte-o5btj0">Transformers carga los modelos en precisión completa <code>float32</code> por defecto, y para un modelo de 8B, ¡esto requiere ~32GB de memoria! Usa el argumento <code>torch_dtype="auto"</code>, que generalmente usa <code>bfloat16</code> para modelos que fueron entrenados con él, para reducir tu uso de memoria.</p> <blockquote class="tip" data-svelte-h="svelte-1n3kza6"><p>Consulta la documentación de <a href="./quantization/overview">Cuantización</a> para más información sobre los diferentes backends de cuantización disponibles.</p></blockquote> <p data-svelte-h="svelte-938e71">Para reducir el uso de memoria aún más, puedes cuantizar el modelo a 8 bits o 4 bits con <a href="https://hf.co/docs/bitsandbytes/index" rel="nofollow">bitsandbytes</a>. Crea un <code>BitsAndBytesConfig</code> con la configuración de cuantización deseada y pásalo al parámetro <code>model_kwargs</code> del pipeline. El siguiente ejemplo cuantiza un modelo a 8 bits.</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 class="" 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> Copied</div></button></div> <pre class="language-py "><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> pipeline, BitsAndBytesConfig | |
| quantization_config = BitsAndBytesConfig(load_in_8bit=<span class="hljs-literal">True</span>) | |
| pipeline = pipeline(task=<span class="hljs-string">"text-generation"</span>, model=<span class="hljs-string">"meta-llama/Meta-Llama-3-8B-Instruct"</span>, device_map=<span class="hljs-string">"auto"</span>, model_kwargs={<span class="hljs-string">"quantization_config"</span>: quantization_config})<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-76t8e0">En general, el tamaño del modelo y el rendimiento están directamente correlacionados. Los modelos más grandes son más lentos además de requerir más memoria porque cada parámetro activo debe leerse de la memoria por cada token generado. | |
| Este es un cuello de botella para la generación de texto con LLMs y las principales opciones para mejorar la velocidad de generación son cuantizar el modelo o usar hardware con mayor ancho de banda de memoria. Agregar más poder de cómputo no ayuda significativamente.</p> <p data-svelte-h="svelte-rusdjg">También puedes probar técnicas como la <a href="./generation_strategies#speculative-decoding">decodificación especulativa</a>, donde un modelo más pequeño genera tokens candidatos que son verificados por el modelo más grande. Si los tokens candidatos son correctos, el modelo más grande puede generar más de un token a la vez. Esto alivia significativamente el cuello de botella de ancho de banda y mejora la velocidad de generación.</p> <blockquote class="tip" data-svelte-h="svelte-1nrl1re"><p>Los modelos Mixture-of-Expert (MoE) como <a href="./model_doc/mixtral">Mixtral</a>, <a href="./model_doc/qwen2_moe">Qwen2MoE</a> y <a href="./model_doc/gpt-oss">GPT-OSS</a> tienen muchos parámetros, pero solo “activan” una pequeña fracción de ellos para generar cada token. Como resultado, los modelos MoE generalmente tienen requisitos de ancho de banda de memoria mucho menores y pueden ser más rápidos que un LLM regular del mismo tamaño. Sin embargo, técnicas como la decodificación especulativa son inefectivas con modelos MoE porque más parámetros se activan con cada nuevo token especulado.</p></blockquote> <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/es/conversations.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 data-svelte-h="svelte-zjs2n5"><span class="underline">Update</span> on GitHub</span></a> <p></p> | |
| <script> | |
| { | |
| __sveltekit_1buzbw1 = { | |
| assets: "/docs/transformers/main/es", | |
| base: "/docs/transformers/main/es", | |
| env: {} | |
| }; | |
| const element = document.currentScript.parentElement; | |
| const data = [null,null]; | |
| Promise.all([ | |
| import("/docs/transformers/main/es/_app/immutable/entry/start.ef1076ce.js"), | |
| import("/docs/transformers/main/es/_app/immutable/entry/app.b1bc2a15.js") | |
| ]).then(([kit, app]) => { | |
| kit.start(app, element, { | |
| node_ids: [0, 9], | |
| data, | |
| form: null, | |
| error: null | |
| }); | |
| }); | |
| } | |
| </script> | |
Xet Storage Details
- Size:
- 29 kB
- Xet hash:
- a91a5e8ba06778caec0b6e14e6aa2646a37cbeadcd572e246afaf099707ec8d1
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.