Notebooks
H
Hugging Face
Fine Tuning Code Llm On Single Gpu

Fine Tuning Code Llm On Single Gpu

hf-cookbookennotebooks

Fine-tuning a Code LLM on Custom Code on a single GPU

Authored by: Maria Khalusova

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.

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.

Dataset

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 smangrul/hf-stack-v1. It contains repo id, file path, and file content.

Model

We'll finetune bigcode/starcoderbase-1b, 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:

[ ]

To get started, let's install all the necessary libraries. As you can see, in addition to transformers and datasets, we'll be using peft, bitsandbytes, and flash-attn to optimize the training.

By employing parameter-efficient training techniques, we can run this notebook on a single A100 High-RAM GPU.

[ ]

Let's define some variables now. Feel free to play with these.

[ ]
[ ]

Prepare the data

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.

We'll reserve the first 4000 examples as the validation set, and everything else will be the training data.

[ ]

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.

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 (nb_examples) 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.

[ ]
100%|██████████| 400/400 [00:10<00:00, 39.87it/s] 
The character to token ratio of the dataset is: 2.43

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.

Optional FIM transformations

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 "Efficient Training of Language Models to Fill in the Middle" paper 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 fim_rate to 0.

[ ]

Let's define the ConstantLengthDataset, 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 fim_rate).

Once defined, we can create instances of the ConstantLengthDataset from both training and validation data.

[ ]

Prepare the model

Now that the data is prepared, it's time to load the model! We're going to load the quantized version of the model.

This will allow us to reduce memory usage, as quantization represents data with fewer bits. We'll use the bitsandbytes library to quantize the model, as it has a nice integration with transformers. All we need to do is define a bitsandbytes config, and then use it when loading the model.

There are different variants of 4bit quantization, but generally, we recommend using NF4 quantization for better performance (bnb_4bit_quant_type="nf4").

The bnb_4bit_use_double_quant option adds a second quantization after the first one to save an additional 0.4 bits per parameter.

To learn more about quantization, check out the "Making LLMs even more accessible with bitsandbytes, 4-bit quantization and QLoRA" blog post.

Once defined, pass the config to the from_pretrained method to load the quantized version of the model.

[ ]

When using a quantized model for training, you need to call the prepare_model_for_kbit_training() function to preprocess the quantized model for training.

[ ]

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.

To train a model using LoRA technique, we need to wrap the base model as a PeftModel. This involves definign LoRA configuration with LoraConfig, and wrapping the original model with get_peft_model() using the LoraConfig.

To learn more about LoRA and its parameters, refer to PEFT documentation.

[ ]
trainable params: 5,554,176 || all params: 1,142,761,472 || trainable%: 0.4860310866343243

As you can see, by applying LoRA technique we will now need to train less than 1% of the parameters.

Train the model

Now that we have prepared the data, and optimized the model, we are ready to bring everything together to start the training.

To instantiate a Trainer, you need to define the training configuration. The most important is the TrainingArguments, which is a class that contains all the attributes to configure the training.

These are similar to any other kind of model training you may run, so we won't go into detail here.

[ ]

As a final step, instantiate the Trainer and call the train method.

[ ]
Training...
TrainOutput(global_step=2000, training_loss=4.885598585128784, metrics={'train_runtime': 15380.3075, 'train_samples_per_second': 2.081, 'train_steps_per_second': 0.13, 'train_tokens_per_second': 4261.033, 'total_flos': 4.0317260660736e+17, 'train_loss': 4.885598585128784, 'epoch': 1.0})

Finally, you can push the fine-tuned model to your Hub repository to share with your team.

[ ]

Inference

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.

[ ]

Now we can use the merged model for inference. For convenience, we'll define a get_code_completion - feel free to experiment with text generation parameters!

[ ]

Now all we need to do to get code completion is call the get_code_complete function and pass the first few lines that we want to be completed as a prefix, and an empty string as a suffix.

[ ]
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=["q_proj", "v_proj"],
    lora_dropout=0.1,
    bias="none",
    modules_to_save=["q_proj", "v_proj"],
    inference_mode=False,
)
model = AutoModelForCausalLM.from_pretrained("gpt2")
model = get_peft_model(model, peft_config)
model.print_trainable_parameters()

As someone who has just used the PEFT library earlier in this notebook, you can see that the generated result for creating a LoraConfig is rather good!

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:

[ ]
from peft import LoraConfig, TaskType, get_peft_model
from transformers import AutoModelForCausalLM
peft_config = LoraConfig(
    model_name_or_path="facebook/wav2vec2-base-960h",
    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="gelu",
    hidden_act_dropout_prob=0.1,
    hidden

While it is Python syntax, you can see that the original model has no understanding of what a LoraConfig should be doing.

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 "Personal Copilot: Train Your Own Coding Assistant" blog post. This notebook complements the original blog post.