Buckets:

mishig's picture
download
raw
57.5 kB
<meta charset="utf-8" /><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Carregando modelos&quot;,&quot;local&quot;:&quot;loading-models&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Modelos e configurações&quot;,&quot;local&quot;:&quot;models-and-configurations&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Classes de modelo&quot;,&quot;local&quot;:&quot;model-classes&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Modelos grandes&quot;,&quot;local&quot;:&quot;large-models&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Pontos de verificação fragmentados&quot;,&quot;local&quot;:&quot;sharded-checkpoints&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Inferência de Modelos Grandes&quot;,&quot;local&quot;:&quot;big-model-inference&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Deslocamento para o disco&quot;,&quot;local&quot;:&quot;disk-offloading&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Tipo de dados do modelo&quot;,&quot;local&quot;:&quot;model-data-type&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3}],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Modelos personalizados&quot;,&quot;local&quot;:&quot;custom-models&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2}],&quot;depth&quot;:1}"/>
<link href="/docs/transformers/main/en/_app/immutable/entry/start.ByZEd4qm.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/DHdg-_0Z.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/CBySwR1V.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/entry/app.CQqZS61p.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/Cdb1BouH.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/dUGfULTE.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.CEy2b_T8.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/Conj1S5Z.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/nodes/670.DyldRV8D.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/DoQ7MZQh.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/DnCf4Kx5.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/uQdIcFiG.js" rel="modulepreload">
<!--18pldtr--><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Loading models&quot;,&quot;local&quot;:&quot;loading-models&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Models and configurations&quot;,&quot;local&quot;:&quot;models-and-configurations&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Model classes&quot;,&quot;local&quot;:&quot;model-classes&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Large models&quot;,&quot;local&quot;:&quot;large-models&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Sharded checkpoints&quot;,&quot;local&quot;:&quot;sharded-checkpoints&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Big Model Inference&quot;,&quot;local&quot;:&quot;big-model-inference&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Disk offloading&quot;,&quot;local&quot;:&quot;disk-offloading&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Model data type&quot;,&quot;local&quot;:&quot;model-data-type&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3}],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Custom models&quot;,&quot;local&quot;:&quot;custom-models&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="loading-models" 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="#loading-models"><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><!---->Carregando modelos<!----></span></h1><!--]--><!----> <p>O Transformers oferece muitos modelos pré-treinados que estão prontos para uso com uma única linha de código. É necessário uma classe de modelo e o método <a href="/docs/transformers/main/pt/main_classes/model#transformers.PreTrainedModel.from_pretrained">from_pretrained()</a>.</p> <p>Chame <a href="/docs/transformers/main/pt/main_classes/model#transformers.PreTrainedModel.from_pretrained">from_pretrained()</a> para baixar e carregar os pesos e a configuração de um modelo armazenados no <a href="https://hf.co/models" rel="nofollow">Hub</a> do Hugging Face.</p> <blockquote class="tip"><p>O método <a href="/docs/transformers/main/pt/main_classes/model#transformers.PreTrainedModel.from_pretrained">from_pretrained()</a> carrega os pesos armazenados no formato de arquivo <a href="https://hf.co/docs/safetensors/index" rel="nofollow">safetensors</a>, caso estejam disponíveis. Tradicionalmente, os pesos de modelos do PyTorch são serializados com a utilidade <a href="https://docs.python.org/3/library/pickle.html" rel="nofollow">pickle</a>, que é conhecida por ser insegura. Os arquivos Safetensor são mais seguros e mais rápidos para carregar.</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 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
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-2-7b-hf&quot;</span>, device_map=<span class="hljs-string">&quot;auto&quot;</span>)<!----></pre></div><!----> <p>Este guia explica como os modelos são carregados, as diferentes maneiras de carregar um modelo, como superar problemas de memória para modelos muito grandes e como carregar modelos personalizados.</p> <!--[1--><h2 class="relative group"><a id="models-and-configurations" 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="#models-and-configurations"><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><!---->Modelos e configurações<!----></span></h2><!--]--><!----> <p>Todos os modelos possuem um arquivo <code>configuration.py</code> com atributos específicos, como o número de camadas ocultas, o tamanho do vocabulário, a função de ativação e outros. Você também encontrará um arquivo <code>modeling.py</code> que define as camadas e as operações matemáticas realizadas dentro de cada camada. O arquivo <code>modeling.py</code> utiliza os atributos do modelo em <code>configuration.py</code> e constrói o modelo de acordo. Neste ponto, você tem um modelo com pesos aleatórios que precisa ser treinado para produzir resultados significativos.</p> <blockquote class="tip"><p>Uma <em>arquitetura</em> se refere ao esqueleto do modelo e um <em>checkpoint</em> se refere aos pesos do modelo para uma determinada arquitetura. Por exemplo, <a href="./model_doc/bert">BERT</a> é uma arquitetura, enquanto <a href="https://huggingface.co/google-bert/bert-base-uncased" rel="nofollow">google-bert/bert-base-uncased</a> é um checkpoint. Você verá o termo <em>modelo</em> usado de forma intercambiável com arquitetura e checkpoint.</p></blockquote> <p>Existem dois tipos gerais de modelos que você pode carregar:</p> <ol><li>Um modelo básico, como <a href="/docs/transformers/main/pt/model_doc/auto#transformers.AutoModel">AutoModel</a> ou <a href="/docs/transformers/main/pt/model_doc/llama2#transformers.LlamaModel">LlamaModel</a>, que produz estados ocultos.</li> <li>Um modelo com um <em>head</em> específico acoplado, como <a href="/docs/transformers/main/pt/model_doc/auto#transformers.AutoModelForCausalLM">AutoModelForCausalLM</a> ou <a href="/docs/transformers/main/pt/model_doc/llama2#transformers.LlamaForCausalLM">LlamaForCausalLM</a>, para executar tarefas específicas.</li></ol> <!--[1--><h2 class="relative group"><a id="model-classes" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#model-classes"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Classes de modelo<!----></span></h2><!--]--><!----> <p>Para obter um modelo pré-treinado, é necessário carregar os pesos no modelo. Isso é feito chamando <a href="/docs/transformers/main/pt/main_classes/model#transformers.PreTrainedModel.from_pretrained">from_pretrained()</a>, que aceita pesos do Hugging Face Hub ou de um diretório local.</p> <p>Há duas classes de modelo: a classe <a href="./model_doc/auto">AutoModel</a> e uma classe específica do modelo.</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">AutoModel</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">classe específica do modelo</div><!--]--></div> <div class="language-select"><div><iframe class="w-full xl:w-4/6 h-80" src="https://www.youtube-nocookie.com/embed/AhChOFRegn4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen=""></iframe><!----> <p>A classe <a href="./model_doc/auto">AutoModel</a> é uma maneira conveniente de carregar uma arquitetura sem precisar conhecer o nome exato da classe do modelo, pois há muitos modelos disponíveis. Ela seleciona automaticamente a classe de modelo correta com base no arquivo de configuração. Você só precisa conhecer a tarefa e o checkpoint que deseja usar.</p> <p>Alterne facilmente entre modelos ou tarefas, desde que a arquitetura seja suportada para uma tarefa específica.</p> <p>Por exemplo, o mesmo modelo pode ser usado para tarefas separadas.</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, AutoModelForSequenceClassification, AutoModelForQuestionAnswering
<span class="hljs-comment"># use the same API for 3 different tasks</span>
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-2-7b-hf&quot;</span>)
model = AutoModelForSequenceClassification.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-2-7b-hf&quot;</span>)
model = AutoModelForQuestionAnswering.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-2-7b-hf&quot;</span>)<!----></pre></div><!----> <p>Em outros casos, você pode querer testar rapidamente vários modelos diferentes para uma tarefa.</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
<span class="hljs-comment"># use the same API to load 3 different models</span>
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-2-7b-hf&quot;</span>)
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;mistralai/Mistral-7B-v0.1&quot;</span>)
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;google/gemma-7b&quot;</span>)<!----></pre></div><!----><!----></div><!----> <div hidden=""><p>A classe <a href="./model_doc/auto">AutoModel</a> é construída sobre as classes específicas de cada modelo. Todas as classes de modelo que suportam uma tarefa específica são mapeadas para a respectiva classe de tarefa <code>AutoModelFor</code>.</p> <p>Se você já sabe qual classe de modelo deseja usar, pode usar diretamente a classe específica do modelo.</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> LlamaModel, LlamaForCausalLM
model = LlamaForCausalLM.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-2-7b-hf&quot;</span>)<!----></pre></div><!----><!----></div><!----><!----></div><!----> <!--[1--><h2 class="relative group"><a id="large-models" 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="#large-models"><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><!---->Modelos grandes<!----></span></h2><!--]--><!----> <p>Modelos pré-treinados de grande porte exigem muita memória para serem carregados. O processo de carregamento envolve:</p> <ol><li>criando um modelo com pesos aleatórios</li> <li>carregando os pesos pré-treinados</li> <li>colocando os pesos pré-treinados no modelo</li></ol> <p>Você precisa de memória suficiente para armazenar duas cópias dos pesos do modelo (aleatórios e pré-treinados), o que pode não ser possível dependendo do seu hardware. Em ambientes de treinamento distribuído, isso é ainda mais desafiador, pois cada processo carrega um modelo pré-treinado.</p> <p>O Transformers reduz alguns desses desafios relacionados à memória com inicialização rápida, checkpoints particionados, o recurso <a href="https://hf.co/docs/accelerate/usage_guides/big_modeling" rel="nofollow">Big Model Inference</a> do Accelerate e o suporte a tipos de dados de bits mais baixos.</p> <!--[2--><h3 class="relative group"><a id="sharded-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="#sharded-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><!---->Pontos de verificação fragmentados<!----></span></h3><!--]--><!----> <p><a href="/docs/transformers/main/pt/main_classes/model#transformers.PreTrainedModel.save_pretrained">save_pretrained()</a> faz o particionamento automático de checkpoints maiores que 50GB. Isso mantém o número de shards baixo para modelos grandes e simplifica o gerenciamento de arquivos.</p> <p>Os parâmetros são carregados em paralelo e a memória de pico depende apenas do tamanho do modelo. Use <code>max_shard_size</code> em <a href="/docs/transformers/main/pt/main_classes/model#transformers.PreTrainedModel.save_pretrained">save_pretrained()</a> para definir o tamanho máximo do checkpoint antes da divisão em shards.</p> <blockquote class="note"><p>O uso de memória para modelos que exigem conversão dinâmica de pesos depende do tamanho do modelo e do tamanho dos maiores parâmetros em uma única conversão. Isso geralmente se aplica a modelos de mistura de especialistas (MoE), em que o uso de memória é o tamanho do modelo mais o número de especialistas em uma camada. Consulte o guia do <a href="./weightconverter#fast-and-efficient-model-loading">dynamic weight loader</a> para saber mais sobre como os modelos são carregados.</p></blockquote> <p><a href="/docs/transformers/main/pt/main_classes/model#transformers.PreTrainedModel.save_pretrained">save_pretrained()</a> também cria um arquivo de índice que mapeia os nomes dos parâmetros para seus arquivos de fragmento. O índice contém duas chaves, <code>metadata</code> e <code>weight_map</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">import</span> json
<span class="hljs-keyword">import</span> os
<span class="hljs-keyword">import</span> tempfile
<span class="hljs-keyword">with</span> tempfile.TemporaryDirectory() <span class="hljs-keyword">as</span> tmp_dir:
model.save_pretrained(tmp_dir, max_shard_size=<span class="hljs-string">&quot;50GB&quot;</span>)
<span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(os.path.join(tmp_dir, <span class="hljs-string">&quot;model.safetensors.index.json&quot;</span>), <span class="hljs-string">&quot;r&quot;</span>) <span class="hljs-keyword">as</span> f:
index = json.load(f)
<span class="hljs-built_in">print</span>(index.keys())<!----></pre></div><!----> <p><code>metadata</code> armazena o tamanho total do modelo.</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 "><!---->index[<span class="hljs-string">&quot;metadata&quot;</span>]
{<span class="hljs-string">&#x27;total_size&#x27;</span>: <span class="hljs-number">28966928384</span>}<!----></pre></div><!----> <p><code>weight_map</code> mapeia cada parâmetro para seu arquivo de shard.</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 "><!---->index[<span class="hljs-string">&quot;weight_map&quot;</span>]
{<span class="hljs-string">&#x27;lm_head.weight&#x27;</span>: <span class="hljs-string">&#x27;model-00006-of-00006.safetensors&#x27;</span>,
<span class="hljs-string">&#x27;model.embed_tokens.weight&#x27;</span>: <span class="hljs-string">&#x27;model-00001-of-00006.safetensors&#x27;</span>,
<span class="hljs-string">&#x27;model.layers.0.input_layernorm.weight&#x27;</span>: <span class="hljs-string">&#x27;model-00001-of-00006.safetensors&#x27;</span>,
<span class="hljs-string">&#x27;model.layers.0.mlp.down_proj.weight&#x27;</span>: <span class="hljs-string">&#x27;model-00001-of-00006.safetensors&#x27;</span>,
...
}<!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="big-model-inference" 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="#big-model-inference"><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><!---->Inferência de Modelos Grandes<!----></span></h3><!--]--><!----> <blockquote class="tip"><p>Certifique-se de ter o Accelerate v0.9.0 e o PyTorch v1.9.0 ou posterior instalados para usar este recurso!</p></blockquote> <iframe class="w-full xl:w-4/6 h-80" src="https://www.youtube-nocookie.com/embed/MWCSGj9jEAo" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen=""></iframe><!----> <p><a href="/docs/transformers/main/pt/main_classes/model#transformers.PreTrainedModel.from_pretrained">from_pretrained()</a> é superpotencializado pelo recurso <a href="https://hf.co/docs/accelerate/usage_guides/big_modeling" rel="nofollow">Big Model Inference</a> do Accelerate.</p> <p>O Big Model Inference cria um <em>esqueleto do modelo</em> no dispositivo <a href="https://pytorch.org/docs/main/meta.html" rel="nofollow">meta</a> do PyTorch. O dispositivo meta não armazena nenhum dado real, apenas os metadados.</p> <p>Os pesos inicializados aleatoriamente são criados apenas quando os pesos pré-treinados são carregados, a fim de evitar manter duas cópias do modelo na memória ao mesmo tempo. O uso máximo de memória é apenas o tamanho do modelo.</p> <blockquote class="tip"><p>Saiba mais sobre a alocação de dispositivos em <a href="https://hf.co/docs/accelerate/v0.33.0/en/concept_guides/big_model_inference#designing-a-device-map" rel="nofollow">Projetando um mapa de dispositivos</a>.</p></blockquote> <p>A segunda funcionalidade do Big Model Inference está relacionada à forma como os pesos são carregados e distribuídos no esqueleto do modelo. Os pesos do modelo são distribuídos entre todos os dispositivos disponíveis, começando pelo dispositivo mais rápido (geralmente a GPU) e, em seguida, transferindo os pesos restantes para dispositivos mais lentos (CPU e disco rígido).</p> <p>A combinação de ambos os recursos reduz o uso de memória e os tempos de carregamento para grandes modelos pré-treinados.</p> <p>Defina <a href="https://github.com/huggingface/transformers/blob/026a173a64372e9602a16523b8fae9de4b0ff428/src/transformers/modeling_utils.py#L3061" rel="nofollow">device_map</a> como <code>"auto"</code> para habilitar o Big Model Inference.</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
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;google/gemma-7b&quot;</span>, device_map=<span class="hljs-string">&quot;auto&quot;</span>)<!----></pre></div><!----> <p>Você também pode atribuir manualmente camadas a um dispositivo em <code>device_map</code>. Ele deve mapear todos os parâmetros do modelo para um dispositivo, mas você não precisa detalhar para onde cada submódulo de uma camada vai, caso a camada inteira esteja no mesmo dispositivo.</p> <p>Acesse o atributo <code>hf_device_map</code> para ver como um modelo é distribuído entre os dispositivos.</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 "><!---->device_map = {<span class="hljs-string">&quot;model.layers.1&quot;</span>: <span class="hljs-number">0</span>, <span class="hljs-string">&quot;model.layers.14&quot;</span>: <span class="hljs-number">1</span>, <span class="hljs-string">&quot;model.layers.31&quot;</span>: <span class="hljs-string">&quot;cpu&quot;</span>, <span class="hljs-string">&quot;lm_head&quot;</span>: <span class="hljs-string">&quot;disk&quot;</span>}
model.hf_device_map<!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="disk-offloading" 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="#disk-offloading"><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><!---->Deslocamento para o disco<!----></span></h3><!--]--><!----> <p>Quando um modelo é grande demais para a soma das suas GPUs e da RAM da CPU, o Big Model Inference transfere os pesos restantes para o disco. Defina <code>offload_folder</code> para um diretório sempre que qualquer peso for mapeado para <code>"disk"</code>, pois é lá que o Transformers armazena os pesos transferidos.</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
model = AutoModelForCausalLM.from_pretrained(
<span class="hljs-string">&quot;google/gemma-7b&quot;</span>,
device_map=<span class="hljs-string">&quot;auto&quot;</span>,
offload_folder=<span class="hljs-string">&quot;./offload&quot;</span>,
)<!----></pre></div><!----> <p>Use <code>max_memory</code> para limitar a quantidade de memória que cada dispositivo pode usar. O Transformers preenche os dispositivos em ordem de velocidade e envia para o disco o que não couber. O exemplo abaixo limita a GPU a 10GB e a CPU a 30GB, de modo que os pesos restantes ficam armazenados em <code>offload_folder</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 "><!---->model = AutoModelForCausalLM.from_pretrained(
<span class="hljs-string">&quot;google/gemma-7b&quot;</span>,
device_map=<span class="hljs-string">&quot;auto&quot;</span>,
max_memory={<span class="hljs-number">0</span>: <span class="hljs-string">&quot;10GB&quot;</span>, <span class="hljs-string">&quot;cpu&quot;</span>: <span class="hljs-string">&quot;30GB&quot;</span>},
offload_folder=<span class="hljs-string">&quot;./offload&quot;</span>,
)<!----></pre></div><!----> <p>Defina <code>max_memory={}</code> para especificar que não há memória de gpu ou cpu disponível e forçar o offloading do modelo inteiro para o disco.</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 "><!---->model = AutoModelForCausalLM.from_pretrained(
<span class="hljs-string">&quot;google/gemma-7b&quot;</span>,
device_map=<span class="hljs-string">&quot;auto&quot;</span>,
max_memory={},
offload_folder=<span class="hljs-string">&quot;./offload&quot;</span>,
)<!----></pre></div><!----> <blockquote class="note"><p>O offloading para o disco troca memória por velocidade. Ler os pesos do disco a cada passagem de frente é mais lento do que ler da memória da CPU ou da GPU.
O offloading totalmente para o disco requer <code>accelerate>1.14.0</code></p></blockquote> <!--[2--><h3 class="relative group"><a id="model-data-type" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#model-data-type"><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><!---->Tipo de dados do modelo<!----></span></h3><!--]--><!----> <p>O argumento <code>dtype</code> controla o <a href="https://pytorch.org/docs/stable/tensor_attributes.html#torch.dtype" rel="nofollow">dtype</a> do PyTorch usado para instanciar os pesos do modelo. Por padrão, o Transformers carrega os pesos com o valor de <code>dtype</code> ou do legado <code>torch_dtype</code> de <code>config.json</code>. Se o <code>config.json</code> não incluir nenhum desses valores, o Transformers usa o dtype do primeiro peso de ponto flutuante no checkpoint.</p> <p>Substitua o padrão passando um dtype específico.</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
<span class="hljs-comment"># specific dtype</span>
model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;google/gemma-3-1b-it&quot;</span>, dtype=torch.float16)<!----></pre></div><!----> <p><a href="/docs/transformers/main/pt/model_doc/auto#transformers.AutoConfig">AutoConfig</a> também aceita <code>dtype</code> para modelos instanciados do zero.</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> AutoConfig, AutoModel
my_config = AutoConfig.from_pretrained(<span class="hljs-string">&quot;google/gemma-2b&quot;</span>, dtype=torch.float16)
model = AutoModel.from_config(my_config)<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="custom-models" 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="#custom-models"><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><!---->Modelos personalizados<!----></span></h2><!--]--><!----> <p>Modelos personalizados são construídos com base nas classes de configuração e modelagem do Transformers, dão suporte à API <code>AutoClass</code> e são carregados com <a href="/docs/transformers/main/pt/main_classes/model#transformers.PreTrainedModel.from_pretrained">from_pretrained()</a>. A diferença é que o código de modelagem <em>não</em> vem do Transformers.</p> <p>Tenha redobrada cautela ao carregar um modelo personalizado. Embora o Hub inclua <a href="https://hf.co/docs/hub/security-malware#malware-scanning" rel="nofollow">varredura de malware</a> em todos os repositórios, você ainda deve ter cuidado para evitar a execução acidental de código malicioso.</p> <p>Defina <code>trust_remote_code=True</code> em <a href="/docs/transformers/main/pt/main_classes/model#transformers.PreTrainedModel.from_pretrained">from_pretrained()</a> para carregar um modelo personalizado.</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> AutoModelForImageClassification
model = AutoModelForImageClassification.from_pretrained(<span class="hljs-string">&quot;sgugger/custom-resnet50d&quot;</span>, trust_remote_code=<span class="hljs-literal">True</span>)<!----></pre></div><!----> <p>Como uma camada extra de segurança, carregue um modelo personalizado de uma revisão específica para evitar o carregamento de código de modelo que pode ter sido alterado. O hash do commit pode ser copiado do <a href="https://hf.co/sgugger/custom-resnet50d/commits/main" rel="nofollow">histórico de commits</a> dos modelos.</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 "><!---->commit_hash = <span class="hljs-string">&quot;ed94a7c6247d8aedce4647f00f20de6875b5b292&quot;</span>
model = AutoModelForImageClassification.from_pretrained(
<span class="hljs-string">&quot;sgugger/custom-resnet50d&quot;</span>, trust_remote_code=<span class="hljs-literal">True</span>, revision=commit_hash
)<!----></pre></div><!----> <p>Consulte o guia <a href="./custom_models">Customize models</a> para obter mais informações.</p> <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/models.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_1y3v6y9 = {
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.ByZEd4qm.js"),
import("/docs/transformers/main/en/_app/immutable/entry/app.CQqZS61p.js")
]).then(([kit, app]) => {
kit.start(app, element, {
node_ids: [0, 670],
data: [null,null],
form: null,
error: null
});
});
}
</script>

Xet Storage Details

Size:
57.5 kB
·
Xet hash:
286f47a4aca1ff63bd11001464145b7d97c689b8d8651ef402a9538e4732e401

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