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 =
    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(
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(
        target_modules= ["q_proj", "k_proj", "v_proj", "o_proj",
                      "gate_proj", "up_proj", "down_proj",]

# Define Training Arguments
training_arguments = TrainingArguments(
        # max_steps=None,

# Create the SFT Trainer
trainer = SFTTrainer(

# Start the Training process

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

# Save the adapter

# 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)

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

├── inferless-runtime-config.yaml
├── inferless.yaml

You can also add other files to this directory.

Create the class for inference

In the 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):

Create the Input Schema

We have to create a 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

    "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.

  cuda_version: "12.1.1"
    - "libssl-dev"
    - "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 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