In this notebook & tutorial, we’ll explore the process of fine-tuning Llama-3-8B.

You can also access the tutorial directly through the provided colab notebook.

For this tutorial, we will use QLoRA, which will fine-tune a LoRA adapter on top of a quantized LLM.

We will use the HuggingFaceH4/ultrachat_200k dataset which is a filtered version of the UltraChat dataset from Huggingface.

For model quantization, we will load the model in a 4-bit format using bitsandbytes.

Finally, when deploying the model on Inferless, you can anticipate the following outcomes.

LibraryInference TimeCold Start TimeTokens/Sec
vLLM1.63 sec13.30 sec78.65

Why finetuning?

Fine-tuning an LLM is a supervised learning process, and we will use Parameter Efficient Fine-Tuning (PEFT), which is an efficient form of instruction fine-tuning.

Let’s get started:

Installing the Required Libraries

You need the following libraries for fine-tuning.

!pip install -q -U bitsandbytes
!pip install -q -U transformers
!pip install -q -U peft
!pip install -q -U accelerate
!pip install -q -U datasets
!pip install -q -U trl

Dataset Preprocessing

From the HuggingFaceH4/ultrachat_200k dataset, we will sample 10000 text conversations for a quick run. We have formatted the data using ChatML as we want our model to follow a specific chat template (ChatML).

dataset_name = "HuggingFaceH4/ultrachat_200k"
dataset = load_dataset(dataset_name, split="train_sft")
dataset = dataset.shuffle(seed=42).select(range(10000))

def format_chat_template(row):
    chat = tokenizer.apply_chat_template(row["messages"], tokenize=False)
    return {"text":chat}

processed_dataset = dataset.map(
    format_chat_template,
    num_proc= os.cpu_count(),
)

dataset = processed_dataset.train_test_split(test_size=0.01)

Finetuning the Llama-3

Now load the tokenizer and the model then quantize and prepare the model for finetuning in 4bit using bitsandbytes. Load and initialize the tokenizer with Hugging Face Transformers AutoTokenizer.

For ChatML support, we will use the setup_chat_format() function in trl. It will set up the chat_template of the tokenizer, add special tokens to the tokenizer and resize the model’s embedding layer to accommodate the new tokens.

Prepare the model for QLoRA training using the prepare_model_for_kbit_training().

tokenizer = AutoTokenizer.from_pretrained(model_name,token=hf_token)

compute_dtype = getattr(torch, "float16")
bnb_config = BitsAndBytesConfig(
        load_in_4bit=True,
        bnb_4bit_quant_type="nf4",
        bnb_4bit_compute_dtype=compute_dtype,
        bnb_4bit_use_double_quant=True)
model = AutoModelForCausalLM.from_pretrained(
          model_name, quantization_config=bnb_config, device_map={"": 0},token=hf_token)

model, tokenizer = setup_chat_format(model, tokenizer)
model = prepare_model_for_kbit_training(model)

Define the LoRA configuration and the Training arguments required for finetuning the model. We will be used in the TRL’s SFTTrainer. The SFTTrainer is then created and used to start the fine-tuning process.

# Define LoRA configuration
peft_config = LoraConfig(
        lora_alpha=64,
        lora_dropout=0.05,
        r=16,
        bias="none",
        task_type="CAUSAL_LM",
        target_modules= ["q_proj", "k_proj", "v_proj", "o_proj",
                      "gate_proj", "up_proj", "down_proj",]
)

# Define Training Arguments
training_arguments = TrainingArguments(
        output_dir="./results_llama3_sft/",
        evaluation_strategy="steps",
        do_eval=True,
        optim="paged_adamw_8bit",
        per_device_train_batch_size=8,
        gradient_accumulation_steps=2,
        per_device_eval_batch_size=8,
        log_level="debug",
        save_steps=50,
        logging_steps=50,
        learning_rate=8e-6,
        eval_steps=10,
        # max_steps=None,
        num_train_epochs=1,
        warmup_steps=30,
        lr_scheduler_type="linear",
)

# Create the SFT Trainer
trainer = SFTTrainer(
        model=model,
        train_dataset=dataset['train'],
        eval_dataset=dataset['test'],
        peft_config=peft_config,
        dataset_text_field="text",
        max_seq_length=2024,
        tokenizer=tokenizer,
        args=training_arguments,
)

# Start the Training process
trainer.train()

After finishing the training, combine the adapter with the original model and upload it into the huggingface hub.

# Save the adapter
trainer.model.save_pretrained("final_checkpoint")
tokenizer.save_pretrained("final_checkpoint")

# Load the base model
model = AutoPeftModelForCausalLM.from_pretrained("final_checkpoint",token=hf_token)
tokenizer = AutoTokenizer.from_pretrained("final_checkpoint",token=hf_token)

# Merge the model with the adapter
model = model.merge_and_unload()

# Upload the model to huggingface hub
model.push_to_hub("inferless-llama-3-8B", token=hf_token)
tokenizer.push_to_hub("inferless-llama-3-8B",token=hf_token)

Let’s deploy the finetuned model on Inferless

Defining Dependencies

We are using the vLLM library, which boosts the inference speed of the LLM.

Constructing the GitHub/GitLab Template

Now quickly construct the GitHub/GitLab template, this process is mandatory and make sure you don’t add any file named model.py.

Llama-3/
├── app.py
├── inferless-runtime-config.yaml
├── inferless.yaml
└── input_schema.py

You can also add other files to this directory.

Create the class for inference

In the app.py we will define the class and import all the required functions

  1. def initialize: In this function, you will initialize your model and define any variable that you want to use during inference.

  2. def infer: This function gets called for every request that you send. Here you can define all the steps that are required for the inference. You can also pass custom values for inference and pass it through inputs(dict) parameter.

  3. def finalize: This function cleans up all the allocated memory.

from vllm import LLM, SamplingParams
from transformers import AutoTokenizer

class InferlessPythonModel:
    def initialize(self):
        model_id = "rbgo/inferless-llama-3-8B"  # Specify the model repository ID of our finetuned model
        # Define sampling parameters for model generation
        self.sampling_params = SamplingParams(temperature=0.7, top_p=0.95, max_tokens=128)
        # Initialize the LLM object
        self.llm = LLM(model=model_id)
        self.tokenizer = AutoTokenizer.from_pretrained(model_id)
        
    def infer(self,inputs):
        prompts = inputs["prompt"]  # Extract the prompt from the input
        chat_format = [{"role": "user", "content": prompts}]
        text = self.tokenizer.apply_chat_template(chat_format,tokenize=False,add_generation_prompt=True)
        result = self.llm.generate(text, self.sampling_params)
        # Extract the generated text from the result
        result_output = [output.outputs[0].text for output in result]

        # Return a dictionary containing the result
        return {'generated_text': result_output[0]}

    def finalize(self):
        pass

Create the Input Schema

We have to create a input_schema.py in your GitHub/Gitlab repository this will help us create the Input parameters. You can checkout our documentation on Input / Output Schema.

For this tutorial, we have defined a parameter prompt which is required during the API call. Now lets create the input_schema.py.

INPUT_SCHEMA = {
    "prompt": {
        'datatype': 'STRING',
        'required': True,
        'shape': [1],
        'example': ["What is AI?"]
    }
}

Creating the Custom Runtime

This is a mandatory step where we allow the users to upload their custom runtime through inferless-runtime-config.yaml.

build:
  cuda_version: "12.1.1"
  system_packages:
    - "libssl-dev"
  python_packages:
    - "torch==2.2.1"
    - "vllm==0.4.1"
    - "transformers==4.40.1"

Deploying the model on Inferless

Inferless supports multiple ways of importing your model. For this tutorial, we will use GitHub.

Import the Model through GitHub

Click on theRepo(Custom code) and then click on the Add provider to connect to your GitHub account. Once your account integration is completed, click on your Github account and continue.

Provide the Model details

Enter the name of the model and pass the GitHub repository URL.

Configure the machine

In this 4th step, the user has to configure the inference setup. On the Inferless platform, we support all the GPUs. For this tutorial, we recommend using A100 GPU. Select A100 from the drop-down menu in the GPU Type.

You also have the flexibility to select from different machine types. Opting for a dedicated machine type will grant you access to an entire GPU while choosing the shared option allocates 50% of the VRAM. In this tutorial, we will opt for the dedicated machine type.

Choose the Minimum and Maximum replicas that you would need for your model:

  • Min replica: The number of inference workers to keep on at all times.

  • Max replica: The maximum number of inference workers to allow at any point in time.

If you wish to enable Automatic rebuild for your model setup, toggle the switch. Note that setting up a web-hook is necessary for this feature. Click here for more details.

In the Advance configuration, we have the option to select the custom runtime. First, click on the Add runtime to upload the inferless-runtime-config.yaml file, give any name and save it. Choose the runtime from the drop-down menu and then click on continue.

Review and Deploy

In this final stage, carefully review all modifications. Once you’ve examined all changes, proceed to deploy the model by clicking the Submit button.

Voilà, your model is now deployed!

Method B: Deploying the model on Inferless CLI

Inferless allows you to deploy your model using Inferless-CLI. Follow the steps to deploy using Inferless CLI.

Initialization of the model

Create the app.py and inferless-runtime-config.yaml, move the files to the working directory. Run the following command to initialize your model:

inferless init

Upload the custom runtime

Once you have created the inferless-runtime-config.yaml file, you can run the following command:

inferless runtime upload

Upon entering this command, you will be prompted to provide the configuration file name. Enter the name and ensure to update it in the inferless.yaml file. Now you are ready for the deployment.

Deploy the Model

Execute the following command to deploy your model. Once deployed, you can track the build logs on the Inferless platform:

inferless deploy