Buckets:

hf-doc-build/doc-dev / cookbook /main /en /fine_tuning_code_llm_on_single_gpu.html
rtrm's picture
download
raw
72.3 kB
<meta charset="utf-8" /><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Fine-tuning a Code LLM on Custom Code on a single GPU&quot;,&quot;local&quot;:&quot;fine-tuning-a-code-llm-on-custom-code-on-a-single-gpu&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Dataset&quot;,&quot;local&quot;:&quot;dataset&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Model&quot;,&quot;local&quot;:&quot;model&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Prepare the data&quot;,&quot;local&quot;:&quot;prepare-the-data&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Prepare the model&quot;,&quot;local&quot;:&quot;prepare-the-model&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Train the model&quot;,&quot;local&quot;:&quot;train-the-model&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Inference&quot;,&quot;local&quot;:&quot;inference&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2}],&quot;depth&quot;:1}">
<link href="/docs/cookbook/main/en/_app/immutable/assets/0.e3b0c442.css" rel="modulepreload">
<link rel="modulepreload" href="/docs/cookbook/main/en/_app/immutable/entry/start.96b44205.js">
<link rel="modulepreload" href="/docs/cookbook/main/en/_app/immutable/chunks/scheduler.65852ee5.js">
<link rel="modulepreload" href="/docs/cookbook/main/en/_app/immutable/chunks/singletons.a64a46c3.js">
<link rel="modulepreload" href="/docs/cookbook/main/en/_app/immutable/chunks/paths.f88132ad.js">
<link rel="modulepreload" href="/docs/cookbook/main/en/_app/immutable/entry/app.e92a3d99.js">
<link rel="modulepreload" href="/docs/cookbook/main/en/_app/immutable/chunks/index.aa74147d.js">
<link rel="modulepreload" href="/docs/cookbook/main/en/_app/immutable/nodes/0.0809e592.js">
<link rel="modulepreload" href="/docs/cookbook/main/en/_app/immutable/chunks/each.e59479a4.js">
<link rel="modulepreload" href="/docs/cookbook/main/en/_app/immutable/nodes/21.03b84a64.js">
<link rel="modulepreload" href="/docs/cookbook/main/en/_app/immutable/chunks/DocNotebookDropdown.479f4286.js">
<link rel="modulepreload" href="/docs/cookbook/main/en/_app/immutable/chunks/EditOnGithub.4eda6a96.js"><!-- HEAD_svelte-u9bgzb_START --><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Fine-tuning a Code LLM on Custom Code on a single GPU&quot;,&quot;local&quot;:&quot;fine-tuning-a-code-llm-on-custom-code-on-a-single-gpu&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Dataset&quot;,&quot;local&quot;:&quot;dataset&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Model&quot;,&quot;local&quot;:&quot;model&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Prepare the data&quot;,&quot;local&quot;:&quot;prepare-the-data&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Prepare the model&quot;,&quot;local&quot;:&quot;prepare-the-model&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Train the model&quot;,&quot;local&quot;:&quot;train-the-model&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Inference&quot;,&quot;local&quot;:&quot;inference&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2}],&quot;depth&quot;:1}"><!-- HEAD_svelte-u9bgzb_END --> <p></p> <div class="flex space-x-1 absolute z-10 right-0 top-0"> <a href="https://colab.research.google.com/github/huggingface/cookbook/blob/multiagent_assist_improvements/notebooks/en/fine_tuning_code_llm_on_single_gpu.ipynb" target="_blank"><img alt="Open In Colab" class="!m-0" src="https://colab.research.google.com/assets/colab-badge.svg"></a> </div> <h1 class="relative group"><a id="fine-tuning-a-code-llm-on-custom-code-on-a-single-gpu" 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="#fine-tuning-a-code-llm-on-custom-code-on-a-single-gpu"><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>Fine-tuning a Code LLM on Custom Code on a single GPU</span></h1> <p data-svelte-h="svelte-26mfp8"><em>Authored by: <a href="https://github.com/MKhalusova" rel="nofollow">Maria Khalusova</a></em></p> <p data-svelte-h="svelte-1jkdfbx">Publicly available code LLMs such as Codex, StarCoder, and Code Llama are great at generating code that adheres to general programming principles and syntax, but they may not align with an organization’s internal conventions, or be aware of proprietary libraries.</p> <p data-svelte-h="svelte-twmb21">In this notebook, we’ll see show how you can fine-tune a code LLM on private code bases to enhance its contextual awareness and improve a model’s usefulness to your organization’s needs. Since the code LLMs are quite large, fine-tuning them in a traditional manner can be resource-draining. Worry not! We will show how you can optimize fine-tuning to fit on a single GPU.</p> <h2 class="relative group"><a id="dataset" 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="#dataset"><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>Dataset</span></h2> <p data-svelte-h="svelte-lcmz04">For this example, we picked the top 10 Hugging Face public repositories on GitHub. We have excluded non-code files from the data, such as images, audio files, presentations, and so on. For Jupyter notebooks, we’ve kept only cells containing code. The resulting code is stored as a dataset that you can find on the Hugging Face Hub under <a href="https://huggingface.co/datasets/smangrul/hf-stack-v1" rel="nofollow"><code>smangrul/hf-stack-v1</code></a>. It contains repo id, file path, and file content.</p> <h2 class="relative group"><a id="model" 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"><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>Model</span></h2> <p data-svelte-h="svelte-1wkzu9g">We’ll finetune <a href="https://huggingface.co/bigcode/starcoderbase-1b" rel="nofollow"><code>bigcode/starcoderbase-1b</code></a>, which is a 1B parameter model trained on 80+ programming languages. This is a gated model, so if you plan to run this notebook with this exact model, you’ll need to gain access to it on the model’s page. Log in to your Hugging Face account to do so:</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=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> huggingface_hub <span class="hljs-keyword">import</span> notebook_login
notebook_login()<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-pqckta">To get started, let’s install all the necessary libraries. As you can see, in addition to <code>transformers</code> and <code>datasets</code>, we’ll be using <code>peft</code>, <code>bitsandbytes</code>, and <code>flash-attn</code> to optimize the training.</p> <p data-svelte-h="svelte-1bfizik">By employing parameter-efficient training techniques, we can run this notebook on a single A100 High-RAM GPU.</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=""><!-- HTML_TAG_START -->!pip install -q transformers datasets peft bitsandbytes flash-attn<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1n5u6bj">Let’s define some variables now. Feel free to play with these.</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=""><!-- HTML_TAG_START -->MODEL = <span class="hljs-string">&quot;bigcode/starcoderbase-1b&quot;</span> <span class="hljs-comment"># Model checkpoint on the Hugging Face Hub</span>
DATASET = <span class="hljs-string">&quot;smangrul/hf-stack-v1&quot;</span> <span class="hljs-comment"># Dataset on the Hugging Face Hub</span>
DATA_COLUMN = <span class="hljs-string">&quot;content&quot;</span> <span class="hljs-comment"># Column name containing the code content</span>
SEQ_LENGTH = <span class="hljs-number">2048</span> <span class="hljs-comment"># Sequence length</span>
<span class="hljs-comment"># Training arguments</span>
MAX_STEPS = <span class="hljs-number">2000</span> <span class="hljs-comment"># max_steps</span>
BATCH_SIZE = <span class="hljs-number">16</span> <span class="hljs-comment"># batch_size</span>
GR_ACC_STEPS = <span class="hljs-number">1</span> <span class="hljs-comment"># gradient_accumulation_steps</span>
LR = <span class="hljs-number">5e-4</span> <span class="hljs-comment"># learning_rate</span>
LR_SCHEDULER_TYPE = <span class="hljs-string">&quot;cosine&quot;</span> <span class="hljs-comment"># lr_scheduler_type</span>
WEIGHT_DECAY = <span class="hljs-number">0.01</span> <span class="hljs-comment"># weight_decay</span>
NUM_WARMUP_STEPS = <span class="hljs-number">30</span> <span class="hljs-comment"># num_warmup_steps</span>
EVAL_FREQ = <span class="hljs-number">100</span> <span class="hljs-comment"># eval_freq</span>
SAVE_FREQ = <span class="hljs-number">100</span> <span class="hljs-comment"># save_freq</span>
LOG_FREQ = <span class="hljs-number">25</span> <span class="hljs-comment"># log_freq</span>
OUTPUT_DIR = <span class="hljs-string">&quot;peft-starcoder-lora-a100&quot;</span> <span class="hljs-comment"># output_dir</span>
BF16 = <span class="hljs-literal">True</span> <span class="hljs-comment"># bf16</span>
FP16 = <span class="hljs-literal">False</span> <span class="hljs-comment"># no_fp16</span>
<span class="hljs-comment"># FIM trasformations arguments</span>
FIM_RATE = <span class="hljs-number">0.5</span> <span class="hljs-comment"># fim_rate</span>
FIM_SPM_RATE = <span class="hljs-number">0.5</span> <span class="hljs-comment"># fim_spm_rate</span>
<span class="hljs-comment"># LORA</span>
LORA_R = <span class="hljs-number">8</span> <span class="hljs-comment"># lora_r</span>
LORA_ALPHA = <span class="hljs-number">32</span> <span class="hljs-comment"># lora_alpha</span>
LORA_DROPOUT = <span class="hljs-number">0.0</span> <span class="hljs-comment"># lora_dropout</span>
LORA_TARGET_MODULES = <span class="hljs-string">&quot;c_proj,c_attn,q_attn,c_fc,c_proj&quot;</span> <span class="hljs-comment"># lora_target_modules</span>
<span class="hljs-comment"># bitsandbytes config</span>
USE_NESTED_QUANT = <span class="hljs-literal">True</span> <span class="hljs-comment"># use_nested_quant</span>
BNB_4BIT_COMPUTE_DTYPE = <span class="hljs-string">&quot;bfloat16&quot;</span> <span class="hljs-comment"># bnb_4bit_compute_dtype</span>
SEED = <span class="hljs-number">0</span><!-- HTML_TAG_END --></pre></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 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=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> (
AutoModelForCausalLM,
AutoTokenizer,
Trainer,
TrainingArguments,
logging,
set_seed,
BitsAndBytesConfig,
)
set_seed(SEED)<!-- HTML_TAG_END --></pre></div> <h2 class="relative group"><a id="prepare-the-data" 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="#prepare-the-data"><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>Prepare the data</span></h2> <p data-svelte-h="svelte-p22occ">Begin by loading the data. As the dataset is likely to be quite large, make sure to enable the streaming mode. Streaming allows us to load the data progressively as we iterate over the dataset instead of downloading the whole dataset at once.</p> <p data-svelte-h="svelte-nud4q8">We’ll reserve the first 4000 examples as the validation set, and everything else will be the training data.</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=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> datasets <span class="hljs-keyword">import</span> load_dataset
<span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> tqdm <span class="hljs-keyword">import</span> tqdm
dataset = load_dataset(
DATASET,
data_dir=<span class="hljs-string">&quot;data&quot;</span>,
split=<span class="hljs-string">&quot;train&quot;</span>,
streaming=<span class="hljs-literal">True</span>,
)
valid_data = dataset.take(<span class="hljs-number">4000</span>)
train_data = dataset.skip(<span class="hljs-number">4000</span>)
train_data = train_data.shuffle(buffer_size=<span class="hljs-number">5000</span>, seed=SEED)<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-169rcmc">At this step, the dataset still contains raw data with code of arbitraty length. For training, we need inputs of fixed length. Let’s create an Iterable dataset that would return constant-length chunks of tokens from a stream of text files.</p> <p data-svelte-h="svelte-1n3y7wl">First, let’s estimate the average number of characters per token in the dataset, which will help us later estimate the number of tokens in the text buffer later. By default, we’ll only take 400 examples (<code>nb_examples</code>) from the dataset. Using only a subset of the entire dataset will reduce computational cost while still providing a reasonable estimate of the overall character-to-token ratio.</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=""><!-- HTML_TAG_START --><span class="hljs-meta">&gt;&gt;&gt; </span>tokenizer = AutoTokenizer.from_pretrained(MODEL, trust_remote_code=<span class="hljs-literal">True</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">chars_token_ratio</span>(<span class="hljs-params">dataset, tokenizer, data_column, nb_examples=<span class="hljs-number">400</span></span>):
<span class="hljs-meta">... </span> <span class="hljs-string">&quot;&quot;&quot;
<span class="hljs-meta">... </span> Estimate the average number of characters per token in the dataset.
<span class="hljs-meta">... </span> &quot;&quot;&quot;</span>
<span class="hljs-meta">... </span> total_characters, total_tokens = <span class="hljs-number">0</span>, <span class="hljs-number">0</span>
<span class="hljs-meta">... </span> <span class="hljs-keyword">for</span> _, example <span class="hljs-keyword">in</span> tqdm(<span class="hljs-built_in">zip</span>(<span class="hljs-built_in">range</span>(nb_examples), <span class="hljs-built_in">iter</span>(dataset)), total=nb_examples):
<span class="hljs-meta">... </span> total_characters += <span class="hljs-built_in">len</span>(example[data_column])
<span class="hljs-meta">... </span> total_tokens += <span class="hljs-built_in">len</span>(tokenizer(example[data_column]).tokens())
<span class="hljs-meta">... </span> <span class="hljs-keyword">return</span> total_characters / total_tokens
<span class="hljs-meta">&gt;&gt;&gt; </span>chars_per_token = chars_token_ratio(train_data, tokenizer, DATA_COLUMN)
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;The character to token ratio of the dataset is: <span class="hljs-subst">{chars_per_token:<span class="hljs-number">.2</span>f}</span>&quot;</span>)<!-- HTML_TAG_END --></pre></div> <pre data-svelte-h="svelte-ko6dme">The character to token ratio of the dataset is: 2.43
</pre> <p data-svelte-h="svelte-4527xa">The character-to-token ratio can also be used as an indicator of the quality of text tokenization. For instance, a character-to-token ratio of 1.0 would mean that each character is represented with a token, which is not very meaningful. This would indicate poor tokenization. In standard English text, one token is typically equivalent to approximately four characters, meaning the character-to-token ratio is around 4.0. We can expect a lower ratio in the code dataset, but generally speaking, a number between 2.0 and 3.5 can be considered good enough.</p> <p data-svelte-h="svelte-1lk8r3"><strong>Optional FIM transformations</strong></p> <p data-svelte-h="svelte-1l3szds">Autoregressive language models typically generate sequences from left to right. By applying the FIM transformations, the model can also learn to infill text. Check out <a href="https://arxiv.org/pdf/2207.14255.pdf" rel="nofollow">“Efficient Training of Language Models to Fill in the Middle” paper</a> to learn more about the technique.
We’ll define the FIM transformations here and will use them when creating the Iterable Dataset. However, if you want to omit transformations, feel free to set <code>fim_rate</code> to 0.</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=""><!-- HTML_TAG_START --><span class="hljs-keyword">import</span> functools
<span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-comment"># Helper function to get token ids of the special tokens for prefix, suffix and middle for FIM transformations.</span>
<span class="hljs-meta">@functools.lru_cache(<span class="hljs-params">maxsize=<span class="hljs-literal">None</span></span>)</span>
<span class="hljs-keyword">def</span> <span class="hljs-title function_">get_fim_token_ids</span>(<span class="hljs-params">tokenizer</span>):
<span class="hljs-keyword">try</span>:
FIM_PREFIX, FIM_MIDDLE, FIM_SUFFIX, FIM_PAD = tokenizer.special_tokens_map[<span class="hljs-string">&quot;additional_special_tokens&quot;</span>][<span class="hljs-number">1</span>:<span class="hljs-number">5</span>]
suffix_tok_id, prefix_tok_id, middle_tok_id, pad_tok_id = (
tokenizer.vocab[tok] <span class="hljs-keyword">for</span> tok <span class="hljs-keyword">in</span> [FIM_SUFFIX, FIM_PREFIX, FIM_MIDDLE, FIM_PAD]
)
<span class="hljs-keyword">except</span> KeyError:
suffix_tok_id, prefix_tok_id, middle_tok_id, pad_tok_id = <span class="hljs-literal">None</span>, <span class="hljs-literal">None</span>, <span class="hljs-literal">None</span>, <span class="hljs-literal">None</span>
<span class="hljs-keyword">return</span> suffix_tok_id, prefix_tok_id, middle_tok_id, pad_tok_id
<span class="hljs-comment">## Adapted from https://github.com/bigcode-project/Megatron-LM/blob/6c4bf908df8fd86b4977f54bf5b8bd4b521003d1/megatron/data/gpt_dataset.py</span>
<span class="hljs-keyword">def</span> <span class="hljs-title function_">permute</span>(<span class="hljs-params">
sample,
np_rng,
suffix_tok_id,
prefix_tok_id,
middle_tok_id,
pad_tok_id,
fim_rate=<span class="hljs-number">0.5</span>,
fim_spm_rate=<span class="hljs-number">0.5</span>,
truncate_or_pad=<span class="hljs-literal">False</span>,
</span>):
<span class="hljs-string">&quot;&quot;&quot;
Take in a sample (list of tokens) and perform a FIM transformation on it with a probability of fim_rate, using two FIM modes:
PSM and SPM (with a probability of fim_spm_rate).
&quot;&quot;&quot;</span>
<span class="hljs-comment"># The if condition will trigger with the probability of fim_rate</span>
<span class="hljs-comment"># This means FIM transformations will apply to samples with a probability of fim_rate</span>
<span class="hljs-keyword">if</span> np_rng.binomial(<span class="hljs-number">1</span>, fim_rate):
<span class="hljs-comment"># Split the sample into prefix, middle, and suffix, based on randomly generated indices stored in the boundaries list.</span>
boundaries = <span class="hljs-built_in">list</span>(np_rng.randint(low=<span class="hljs-number">0</span>, high=<span class="hljs-built_in">len</span>(sample) + <span class="hljs-number">1</span>, size=<span class="hljs-number">2</span>))
boundaries.sort()
prefix = np.array(sample[: boundaries[<span class="hljs-number">0</span>]], dtype=np.int64)
middle = np.array(sample[boundaries[<span class="hljs-number">0</span>] : boundaries[<span class="hljs-number">1</span>]], dtype=np.int64)
suffix = np.array(sample[boundaries[<span class="hljs-number">1</span>] :], dtype=np.int64)
<span class="hljs-keyword">if</span> truncate_or_pad:
<span class="hljs-comment"># calculate the new total length of the sample, taking into account tokens indicating prefix, middle, and suffix</span>
new_length = suffix.shape[<span class="hljs-number">0</span>] + prefix.shape[<span class="hljs-number">0</span>] + middle.shape[<span class="hljs-number">0</span>] + <span class="hljs-number">3</span>
diff = new_length - <span class="hljs-built_in">len</span>(sample)
<span class="hljs-comment"># trancate or pad if there&#x27;s a difference in length between the new length and the original</span>
<span class="hljs-keyword">if</span> diff &gt; <span class="hljs-number">0</span>:
<span class="hljs-keyword">if</span> suffix.shape[<span class="hljs-number">0</span>] &lt;= diff:
<span class="hljs-keyword">return</span> sample, np_rng
suffix = suffix[: suffix.shape[<span class="hljs-number">0</span>] - diff]
<span class="hljs-keyword">elif</span> diff &lt; <span class="hljs-number">0</span>:
suffix = np.concatenate([suffix, np.full((-<span class="hljs-number">1</span> * diff), pad_tok_id)])
<span class="hljs-comment"># With the probability of fim_spm_rateapply SPM variant of FIM transformations</span>
<span class="hljs-comment"># SPM: suffix, prefix, middle</span>
<span class="hljs-keyword">if</span> np_rng.binomial(<span class="hljs-number">1</span>, fim_spm_rate):
new_sample = np.concatenate(
[
[prefix_tok_id, suffix_tok_id],
suffix,
[middle_tok_id],
prefix,
middle,
]
)
<span class="hljs-comment"># Otherwise, apply the PSM variant of FIM transformations</span>
<span class="hljs-comment"># PSM: prefix, suffix, middle</span>
<span class="hljs-keyword">else</span>:
new_sample = np.concatenate(
[
[prefix_tok_id],
prefix,
[suffix_tok_id],
suffix,
[middle_tok_id],
middle,
]
)
<span class="hljs-keyword">else</span>:
<span class="hljs-comment"># don&#x27;t apply FIM transformations</span>
new_sample = sample
<span class="hljs-keyword">return</span> <span class="hljs-built_in">list</span>(new_sample), np_rng<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-2233ic">Let’s define the <code>ConstantLengthDataset</code>, an Iterable dataset that will return constant-length chunks of tokens. To do so, we’ll read a buffer of text from the original dataset until we hit the size limits and then apply tokenizer to convert the raw text into tokenized inputs. Optionally, we’ll perform FIM transformations on some sequences (the proportion of sequences affected is controlled by <code>fim_rate</code>).</p> <p data-svelte-h="svelte-155t8oo">Once defined, we can create instances of the <code>ConstantLengthDataset</code> from both training and validation data.</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=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> torch.utils.data <span class="hljs-keyword">import</span> IterableDataset
<span class="hljs-keyword">from</span> torch.utils.data.dataloader <span class="hljs-keyword">import</span> DataLoader
<span class="hljs-keyword">import</span> random
<span class="hljs-comment"># Create an Iterable dataset that returns constant-length chunks of tokens from a stream of text files.</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">ConstantLengthDataset</span>(<span class="hljs-title class_ inherited__">IterableDataset</span>):
<span class="hljs-string">&quot;&quot;&quot;
Iterable dataset that returns constant length chunks of tokens from stream of text files.
Args:
tokenizer (Tokenizer): The processor used for proccessing the data.
dataset (dataset.Dataset): Dataset with text files.
infinite (bool): If True the iterator is reset after dataset reaches end else stops.
seq_length (int): Length of token sequences to return.
num_of_sequences (int): Number of token sequences to keep in buffer.
chars_per_token (int): Number of characters per token used to estimate number of tokens in text buffer.
fim_rate (float): Rate (0.0 to 1.0) that sample will be permuted with FIM.
fim_spm_rate (float): Rate (0.0 to 1.0) of FIM permuations that will use SPM.
seed (int): Seed for random number generator.
&quot;&quot;&quot;</span>
<span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">
self,
tokenizer,
dataset,
infinite=<span class="hljs-literal">False</span>,
seq_length=<span class="hljs-number">1024</span>,
num_of_sequences=<span class="hljs-number">1024</span>,
chars_per_token=<span class="hljs-number">3.6</span>,
content_field=<span class="hljs-string">&quot;content&quot;</span>,
fim_rate=<span class="hljs-number">0.5</span>,
fim_spm_rate=<span class="hljs-number">0.5</span>,
seed=<span class="hljs-number">0</span>,
</span>):
self.tokenizer = tokenizer
self.concat_token_id = tokenizer.eos_token_id
self.dataset = dataset
self.seq_length = seq_length
self.infinite = infinite
self.current_size = <span class="hljs-number">0</span>
self.max_buffer_size = seq_length * chars_per_token * num_of_sequences
self.content_field = content_field
self.fim_rate = fim_rate
self.fim_spm_rate = fim_spm_rate
self.seed = seed
(
self.suffix_tok_id,
self.prefix_tok_id,
self.middle_tok_id,
self.pad_tok_id,
) = get_fim_token_ids(self.tokenizer)
<span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> self.suffix_tok_id <span class="hljs-keyword">and</span> self.fim_rate &gt; <span class="hljs-number">0</span>:
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;FIM is not supported by tokenizer, disabling FIM&quot;</span>)
self.fim_rate = <span class="hljs-number">0</span>
<span class="hljs-keyword">def</span> <span class="hljs-title function_">__iter__</span>(<span class="hljs-params">self</span>):
iterator = <span class="hljs-built_in">iter</span>(self.dataset)
more_examples = <span class="hljs-literal">True</span>
np_rng = np.random.RandomState(seed=self.seed)
<span class="hljs-keyword">while</span> more_examples:
buffer, buffer_len = [], <span class="hljs-number">0</span>
<span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:
<span class="hljs-keyword">if</span> buffer_len &gt;= self.max_buffer_size:
<span class="hljs-keyword">break</span>
<span class="hljs-keyword">try</span>:
buffer.append(<span class="hljs-built_in">next</span>(iterator)[self.content_field])
buffer_len += <span class="hljs-built_in">len</span>(buffer[-<span class="hljs-number">1</span>])
<span class="hljs-keyword">except</span> StopIteration:
<span class="hljs-keyword">if</span> self.infinite:
iterator = <span class="hljs-built_in">iter</span>(self.dataset)
<span class="hljs-keyword">else</span>:
more_examples = <span class="hljs-literal">False</span>
<span class="hljs-keyword">break</span>
tokenized_inputs = self.tokenizer(buffer, truncation=<span class="hljs-literal">False</span>)[<span class="hljs-string">&quot;input_ids&quot;</span>]
all_token_ids = []
<span class="hljs-keyword">for</span> tokenized_input <span class="hljs-keyword">in</span> tokenized_inputs:
<span class="hljs-comment"># optionally do FIM permutations</span>
<span class="hljs-keyword">if</span> self.fim_rate &gt; <span class="hljs-number">0</span>:
tokenized_input, np_rng = permute(
tokenized_input,
np_rng,
self.suffix_tok_id,
self.prefix_tok_id,
self.middle_tok_id,
self.pad_tok_id,
fim_rate=self.fim_rate,
fim_spm_rate=self.fim_spm_rate,
truncate_or_pad=<span class="hljs-literal">False</span>,
)
all_token_ids.extend(tokenized_input + [self.concat_token_id])
examples = []
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">0</span>, <span class="hljs-built_in">len</span>(all_token_ids), self.seq_length):
input_ids = all_token_ids[i : i + self.seq_length]
<span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(input_ids) == self.seq_length:
examples.append(input_ids)
random.shuffle(examples)
<span class="hljs-keyword">for</span> example <span class="hljs-keyword">in</span> examples:
self.current_size += <span class="hljs-number">1</span>
<span class="hljs-keyword">yield</span> {
<span class="hljs-string">&quot;input_ids&quot;</span>: torch.LongTensor(example),
<span class="hljs-string">&quot;labels&quot;</span>: torch.LongTensor(example),
}
train_dataset = ConstantLengthDataset(
tokenizer,
train_data,
infinite=<span class="hljs-literal">True</span>,
seq_length=SEQ_LENGTH,
chars_per_token=chars_per_token,
content_field=DATA_COLUMN,
fim_rate=FIM_RATE,
fim_spm_rate=FIM_SPM_RATE,
seed=SEED,
)
eval_dataset = ConstantLengthDataset(
tokenizer,
valid_data,
infinite=<span class="hljs-literal">False</span>,
seq_length=SEQ_LENGTH,
chars_per_token=chars_per_token,
content_field=DATA_COLUMN,
fim_rate=FIM_RATE,
fim_spm_rate=FIM_SPM_RATE,
seed=SEED,
)<!-- HTML_TAG_END --></pre></div> <h2 class="relative group"><a id="prepare-the-model" 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="#prepare-the-model"><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>Prepare the model</span></h2> <p data-svelte-h="svelte-9bd9cz">Now that the data is prepared, it’s time to load the model! We’re going to load the quantized version of the model.</p> <p data-svelte-h="svelte-1uhrhyi">This will allow us to reduce memory usage, as quantization represents data with fewer bits. We’ll use the <code>bitsandbytes</code> library to quantize the model, as it has a nice integration with <code>transformers</code>. All we need to do is define a <code>bitsandbytes</code> config, and then use it when loading the model.</p> <p data-svelte-h="svelte-2m06yu">There are different variants of 4bit quantization, but generally, we recommend using NF4 quantization for better performance (<code>bnb_4bit_quant_type=&quot;nf4&quot;</code>).</p> <p data-svelte-h="svelte-lrsdq">The <code>bnb_4bit_use_double_quant</code> option adds a second quantization after the first one to save an additional 0.4 bits per parameter.</p> <p data-svelte-h="svelte-1s6fz64">To learn more about quantization, check out the <a href="https://huggingface.co/blog/4bit-transformers-bitsandbytes" rel="nofollow">“Making LLMs even more accessible with bitsandbytes, 4-bit quantization and QLoRA” blog post</a>.</p> <p data-svelte-h="svelte-1uji32v">Once defined, pass the config to the <code>from_pretrained</code> method to load the quantized version of the model.</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=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> peft <span class="hljs-keyword">import</span> LoraConfig, get_peft_model, prepare_model_for_kbit_training
<span class="hljs-keyword">from</span> peft.tuners.lora <span class="hljs-keyword">import</span> LoraLayer
load_in_8bit = <span class="hljs-literal">False</span>
<span class="hljs-comment"># 4-bit quantization</span>
compute_dtype = <span class="hljs-built_in">getattr</span>(torch, BNB_4BIT_COMPUTE_DTYPE)
bnb_config = BitsAndBytesConfig(
load_in_4bit=<span class="hljs-literal">True</span>,
bnb_4bit_quant_type=<span class="hljs-string">&quot;nf4&quot;</span>,
bnb_4bit_compute_dtype=compute_dtype,
bnb_4bit_use_double_quant=USE_NESTED_QUANT,
)
device_map = {<span class="hljs-string">&quot;&quot;</span>: <span class="hljs-number">0</span>}
model = AutoModelForCausalLM.from_pretrained(
MODEL,
load_in_8bit=load_in_8bit,
quantization_config=bnb_config,
device_map=device_map,
use_cache=<span class="hljs-literal">False</span>, <span class="hljs-comment"># We will be using gradient checkpointing</span>
trust_remote_code=<span class="hljs-literal">True</span>,
use_flash_attention_2=<span class="hljs-literal">True</span>,
)<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1h52q0h">When using a quantized model for training, you need to call the <code>prepare_model_for_kbit_training()</code> function to preprocess the quantized model for training.</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=""><!-- HTML_TAG_START -->model = prepare_model_for_kbit_training(model)<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1oeq64f">Now that the quantized model is ready, we can set up a LoRA configuration. LoRA makes fine-tuning more efficient by drastically reducing the number of trainable parameters.</p> <p data-svelte-h="svelte-6kkm2s">To train a model using LoRA technique, we need to wrap the base model as a <code>PeftModel</code>. This involves definign LoRA configuration with <code>LoraConfig</code>, and wrapping the original model with <code>get_peft_model()</code> using the <code>LoraConfig</code>.</p> <p data-svelte-h="svelte-1tuhj0w">To learn more about LoRA and its parameters, refer to <a href="https://huggingface.co/docs/peft/main/en/conceptual_guides/lora" rel="nofollow">PEFT documentation</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 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=""><!-- HTML_TAG_START --><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-comment"># Set up lora</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>peft_config = LoraConfig(
<span class="hljs-meta">... </span> lora_alpha=LORA_ALPHA,
<span class="hljs-meta">... </span> lora_dropout=LORA_DROPOUT,
<span class="hljs-meta">... </span> r=LORA_R,
<span class="hljs-meta">... </span> bias=<span class="hljs-string">&quot;none&quot;</span>,
<span class="hljs-meta">... </span> task_type=<span class="hljs-string">&quot;CAUSAL_LM&quot;</span>,
<span class="hljs-meta">... </span> target_modules=LORA_TARGET_MODULES.split(<span class="hljs-string">&quot;,&quot;</span>),
<span class="hljs-meta">... </span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>model = get_peft_model(model, peft_config)
<span class="hljs-meta">&gt;&gt;&gt; </span>model.print_trainable_parameters()<!-- HTML_TAG_END --></pre></div> <pre data-svelte-h="svelte-hpf32x">trainable params: 5,554,176 || all params: 1,142,761,472 || trainable%: 0.4860310866343243
</pre> <p data-svelte-h="svelte-g92wi0">As you can see, by applying LoRA technique we will now need to train less than 1% of the parameters.</p> <h2 class="relative group"><a id="train-the-model" 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="#train-the-model"><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>Train the model</span></h2> <p data-svelte-h="svelte-nh2kp6">Now that we have prepared the data, and optimized the model, we are ready to bring everything together to start the training.</p> <p data-svelte-h="svelte-rhwpb7">To instantiate a <code>Trainer</code>, you need to define the training configuration. The most important is the <code>TrainingArguments</code>, which is a class that contains all the attributes to configure the training.</p> <p data-svelte-h="svelte-6zfky8">These are similar to any other kind of model training you may run, so we won’t go into detail here.</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=""><!-- HTML_TAG_START -->train_data.start_iteration = <span class="hljs-number">0</span>
training_args = TrainingArguments(
output_dir=<span class="hljs-string">f&quot;Your_HF_username/<span class="hljs-subst">{OUTPUT_DIR}</span>&quot;</span>,
dataloader_drop_last=<span class="hljs-literal">True</span>,
evaluation_strategy=<span class="hljs-string">&quot;steps&quot;</span>,
save_strategy=<span class="hljs-string">&quot;steps&quot;</span>,
max_steps=MAX_STEPS,
eval_steps=EVAL_FREQ,
save_steps=SAVE_FREQ,
logging_steps=LOG_FREQ,
per_device_train_batch_size=BATCH_SIZE,
per_device_eval_batch_size=BATCH_SIZE,
learning_rate=LR,
lr_scheduler_type=LR_SCHEDULER_TYPE,
warmup_steps=NUM_WARMUP_STEPS,
gradient_accumulation_steps=GR_ACC_STEPS,
gradient_checkpointing=<span class="hljs-literal">True</span>,
fp16=FP16,
bf16=BF16,
weight_decay=WEIGHT_DECAY,
push_to_hub=<span class="hljs-literal">True</span>,
include_tokens_per_second=<span class="hljs-literal">True</span>,
)<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1yquuuu">As a final step, instantiate the <code>Trainer</code> and call the <code>train</code> method.</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=""><!-- HTML_TAG_START --><span class="hljs-meta">&gt;&gt;&gt; </span>trainer = Trainer(model=model, args=training_args, train_dataset=train_dataset, eval_dataset=eval_dataset)
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Training...&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>trainer.train()<!-- HTML_TAG_END --></pre></div> <pre data-svelte-h="svelte-9xzew6">Training...
</pre> <p data-svelte-h="svelte-p9ps3w">Finally, you can push the fine-tuned model to your Hub repository to share with your team.</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=""><!-- HTML_TAG_START -->trainer.push_to_hub()<!-- HTML_TAG_END --></pre></div> <h2 class="relative group"><a id="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="#inference"><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>Inference</span></h2> <p data-svelte-h="svelte-lw3peh">Once the model is uploaded to Hub, we can use it for inference. To do so we first initialize the original base model and its tokenizer. Next, we need to merge the fine-duned weights with the base model.</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=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> peft <span class="hljs-keyword">import</span> PeftModel
<span class="hljs-keyword">import</span> torch
<span class="hljs-comment"># load the original model first</span>
tokenizer = AutoTokenizer.from_pretrained(MODEL, trust_remote_code=<span class="hljs-literal">True</span>)
base_model = AutoModelForCausalLM.from_pretrained(
MODEL,
quantization_config=<span class="hljs-literal">None</span>,
device_map=<span class="hljs-literal">None</span>,
trust_remote_code=<span class="hljs-literal">True</span>,
torch_dtype=torch.bfloat16,
).cuda()
<span class="hljs-comment"># merge fine-tuned weights with the base model</span>
peft_model_id = <span class="hljs-string">f&quot;Your_HF_username/<span class="hljs-subst">{OUTPUT_DIR}</span>&quot;</span>
model = PeftModel.from_pretrained(base_model, peft_model_id)
model.merge_and_unload()<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1xk304l">Now we can use the merged model for inference. For convenience, we’ll define a <code>get_code_completion</code> - feel free to experiment with text generation parameters!</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=""><!-- HTML_TAG_START --><span class="hljs-keyword">def</span> <span class="hljs-title function_">get_code_completion</span>(<span class="hljs-params">prefix, suffix</span>):
text = prompt = <span class="hljs-string">f&quot;&quot;&quot;&lt;fim_prefix&gt;<span class="hljs-subst">{prefix}</span>&lt;fim_suffix&gt;<span class="hljs-subst">{suffix}</span>&lt;fim_middle&gt;&quot;&quot;&quot;</span>
model.<span class="hljs-built_in">eval</span>()
outputs = model.generate(
input_ids=tokenizer(text, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).input_ids.cuda(),
max_new_tokens=<span class="hljs-number">128</span>,
temperature=<span class="hljs-number">0.2</span>,
top_k=<span class="hljs-number">50</span>,
top_p=<span class="hljs-number">0.95</span>,
do_sample=<span class="hljs-literal">True</span>,
repetition_penalty=<span class="hljs-number">1.0</span>,
)
<span class="hljs-keyword">return</span> tokenizer.batch_decode(outputs, skip_special_tokens=<span class="hljs-literal">True</span>)[<span class="hljs-number">0</span>]<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1nsj0eg">Now all we need to do to get code completion is call the <code>get_code_complete</code> function and pass the first few lines that we want to be completed as a prefix, and an empty string as a suffix.</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=""><!-- HTML_TAG_START --><span class="hljs-meta">&gt;&gt;&gt; </span>prefix = <span class="hljs-string">&quot;&quot;&quot;from peft import LoraConfig, TaskType, get_peft_model
<span class="hljs-meta">... </span>from transformers import AutoModelForCausalLM
<span class="hljs-meta">... </span>peft_config = LoraConfig(
<span class="hljs-meta">... </span>&quot;&quot;&quot;</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>suffix = <span class="hljs-string">&quot;&quot;&quot;&quot;&quot;&quot;</span>
<span class="hljs-meta">... </span><span class="hljs-built_in">print</span>(get_code_completion(prefix, suffix))<!-- HTML_TAG_END --></pre></div> <pre data-svelte-h="svelte-11ixuz2">from peft import LoraConfig, TaskType, get_peft_model
from transformers import AutoModelForCausalLM
peft_config = LoraConfig(
task_type=TaskType.CAUSAL_LM,
r=8,
lora_alpha=32,
target_modules=[&quot;q_proj&quot;, &quot;v_proj&quot;],
lora_dropout=0.1,
bias=&quot;none&quot;,
modules_to_save=[&quot;q_proj&quot;, &quot;v_proj&quot;],
inference_mode=False,
)
model = AutoModelForCausalLM.from_pretrained(&quot;gpt2&quot;)
model = get_peft_model(model, peft_config)
model.print_trainable_parameters()
</pre> <p data-svelte-h="svelte-tkz9oe">As someone who has just used the PEFT library earlier in this notebook, you can see that the generated result for creating a <code>LoraConfig</code> is rather good!</p> <p data-svelte-h="svelte-1wna85g">If you go back to the cell where we instantiate the model for inference, and comment out the lines where we merge the fine-tuned weights, you can see what the original model would’ve generated for the exact same prefix:</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=""><!-- HTML_TAG_START --><span class="hljs-meta">&gt;&gt;&gt; </span>prefix = <span class="hljs-string">&quot;&quot;&quot;from peft import LoraConfig, TaskType, get_peft_model
<span class="hljs-meta">... </span>from transformers import AutoModelForCausalLM
<span class="hljs-meta">... </span>peft_config = LoraConfig(
<span class="hljs-meta">... </span>&quot;&quot;&quot;</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>suffix = <span class="hljs-string">&quot;&quot;&quot;&quot;&quot;&quot;</span>
<span class="hljs-meta">... </span><span class="hljs-built_in">print</span>(get_code_completion(prefix, suffix))<!-- HTML_TAG_END --></pre></div> <pre data-svelte-h="svelte-1ud779o">from peft import LoraConfig, TaskType, get_peft_model
from transformers import AutoModelForCausalLM
peft_config = LoraConfig(
model_name_or_path=&quot;facebook/wav2vec2-base-960h&quot;,
num_labels=1,
num_features=1,
num_hidden_layers=1,
num_attention_heads=1,
num_hidden_layers_per_attention_head=1,
num_attention_heads_per_hidden_layer=1,
hidden_size=1024,
hidden_dropout_prob=0.1,
hidden_act=&quot;gelu&quot;,
hidden_act_dropout_prob=0.1,
hidden
</pre> <p data-svelte-h="svelte-1dhv5aw">While it is Python syntax, you can see that the original model has no understanding of what a <code>LoraConfig</code> should be doing.</p> <p data-svelte-h="svelte-zjkw3y">To learn how this kind of fine-tuning compares to full fine-tuning, and how to use a model like this as your copilot in VS Code via Inference Endpoints, or locally, check out the <a href="https://huggingface.co/blog/personal-copilot" rel="nofollow">“Personal Copilot: Train Your Own Coding Assistant” blog post</a>. This notebook complements the original blog post.</p> <a class="!text-gray-400 !no-underline text-sm flex items-center not-prose mt-4" href="https://github.com/huggingface/cookbook/blob/main/notebooks/en/fine_tuning_code_llm_on_single_gpu.md" target="_blank"><span data-svelte-h="svelte-1kd6by1">&lt;</span> <span data-svelte-h="svelte-x0xyl0">&gt;</span> <span data-svelte-h="svelte-1dajgef"><span class="underline ml-1.5">Update</span> on GitHub</span></a> <p></p>
<script>
{
__sveltekit_1l2350x = {
assets: "/docs/cookbook/main/en",
base: "/docs/cookbook/main/en",
env: {}
};
const element = document.currentScript.parentElement;
const data = [null,null];
Promise.all([
import("/docs/cookbook/main/en/_app/immutable/entry/start.96b44205.js"),
import("/docs/cookbook/main/en/_app/immutable/entry/app.e92a3d99.js")
]).then(([kit, app]) => {
kit.start(app, element, {
node_ids: [0, 21],
data,
form: null,
error: null
});
});
}
</script>

Xet Storage Details

Size:
72.3 kB
·
Xet hash:
c7349a766803fa4871ef17c1483880335586aaa81fc2c7f2212f089bc7c5988e

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