> ## Documentation Index
> Fetch the complete documentation index at: https://docs.inferless.com/llms.txt
> Use this file to discover all available pages before exploring further.

# How to Finetune and Inference Llama-3

> Llama 3 is an auto-regressive language model, leveraging a refined transformer architecture. The Llama 3 models were trained on 8x more data on over 15 trillion tokens. It has a context length of 8K tokens and increases the vocabulary size of the tokenizer to 128,256 (from 32K tokens in the previous version).

In this notebook & tutorial, we'll explore the process of fine-tuning [Llama-3-8B](https://huggingface.co/meta-llama/Meta-Llama-3-8B).

You can also access the tutorial directly through the provided [colab notebook](https://colab.research.google.com/drive/1Rw-zLEuKnnx-eE15HEqaF_ADq9NK1OGb?usp=sharing).

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`](https://huggingface.co/datasets/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](https://github.com/TimDettmers/bitsandbytes).

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

| Library | Inference Time | Cold Start Time | Tokens/Sec |
| ------- | -------------- | --------------- | ---------- |
| vLLM    | 1.63 sec       | 13.30 sec       | 78.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`](https://huggingface.co/datasets/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](https://huggingface.co/docs/transformers/chat%5Ftemplating)).

```python theme={null}
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](https://github.com/TimDettmers/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()`.

```python theme={null}
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.

```python theme={null}
# 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](https://github.com/vllm-project/vllm), 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](https://github.com/inferless/Llama-3/blob/main/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.

```python theme={null}
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`](https://github.com/inferless/Llama-3/blob/main/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](https://docs.inferless.com/model-import/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`.

```JSON theme={null}
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](https://github.com/inferless/Llama-3/blob/main/inferless-runtime-config.yaml).

```python theme={null}
build:
  cuda_version: "12.1.1"
  system_packages:
    - "libssl-dev"
  python_packages:
    - "torch==2.2.1"
    - "vllm==0.4.1"
    - "transformers==4.40.1"
```

## Test your model with Remote Run

You can use the `inferless remote-run`([installation guide here](https://docs.inferless.com/model-import/cli-import#cli-import)) command to test your model or any custom Python script in a remote GPU environment directly from your local machine. Make sure that you use `Python3.10` for seamless experience.

### Step 1: Add the Decorators and local entry point

To enable **Remote Run**, simply do the following:

1. Import the `inferless` library and initialize `Cls(gpu="A100")`. The available GPU options are `T4`, `A10` and `A100`.
2. Decorated the `initialize` and `infer` functions with `@app.load` and `@app.infer` respectively.
3. Create the Local Entry Point by decorating a function (for example, `my_local_entry`) with `@inferless.local_entry_point`.
   Within this function, instantiate your model class, convert any incoming parameters into a `RequestObjects` object, and invoke the model's `infer` method.

```python theme={null}
from vllm import LLM, SamplingParams
from transformers import AutoTokenizer
import inferless
from pydantic import BaseModel, Field
from typing import Optional


@inferless.request
class RequestObjects(BaseModel):
    prompt: str = Field(default="Implement a function to check if a given number is a prime number.")
    temperature: Optional[float] = 0.7
    top_p: Optional[float] = 0.1
    repetition_penalty: Optional[float] = 1.18
    top_k: Optional[int] = 40
    max_tokens: Optional[int] = 256
    
@inferless.response
class ResponseObjects(BaseModel):
    generated_text: str = Field(default='Test output')

app = inferless.Cls(gpu="A100")

class InferlessPythonModel:
    @app.load
    def initialize(self):
        model_id = "rbgo/inferless-llama-3-8B"
        # Initialize the LLM object
        self.llm = LLM(model=model_id)
        self.tokenizer = AutoTokenizer.from_pretrained(model_id)
    
    @app.infer
    def infer(self, request: RequestObjects) -> ResponseObjects:
        sampling_params = SamplingParams(temperature=request.temperature,top_p=request.top_p,
                                         repetition_penalty=request.repetition_penalty,
                                         top_k=request.top_k,max_tokens=request.max_tokens
                                        )
        chat_format = [{"role": "user", "content": request.prompt}]
        input_text = self.tokenizer.apply_chat_template(chat_format,tokenize=False,add_generation_prompt=True)
        result = self.llm.generate(input_text, sampling_params)
        # Extract the generated text from the result
        result_output = [output.outputs[0].text for output in result]

        generateObject = ResponseObjects(generated_text = result_output[0])        
        return generateObject

    def finalize(self):
        self.llm = None

@inferless.local_entry_point
def my_local_entry(dynamic_params):
    request_objects = RequestObjects(**dynamic_params)
    model_instance = InferlessPythonModel()

    return model_instance.infer(request_objects)
```

### Step 2: Run with Remote GPU

From your local terminal, navigate to the folder containing your `app.py` and your `inferless-runtime-config.yaml` and run:

```bash theme={null}
inferless remote-run app.py -c inferless-runtime-config.yaml --prompt "Explain Deep Learning."
```

You can pass the other input parameters in the same way (e.g., `--temperature`, `--max_tokens`, etc.) as long as your code expects them in the `inputs` dictionary.

## Method A: Deploying the model on Inferless Platform

Inferless supports multiple ways of [importing your model](https://docs.inferless.com/model-import/file-structure-req/file-structure-requirements). For this tutorial, we will use GitHub.

### Step 1: Login to the inferless dashboard can click on Import model button

Navigate to your desired workspace in Inferless and Click on `Add a custom model` button that you see on the top right. An import wizard will open up.

### Step 2: Follow the UI to complete the model  Import

* Select the GitHub/GitLab Integration option to connect your source code repository with the deployment environment.
* Navigate to the specific GitHub repository that contains your model's code. Here, you will need to identify and enter the name of the model you wish to import.
* Choose the appropriate type of machine that suits your model's requirements. Additionally, specify the minimum and maximum number of replicas to define the scalability range for deploying your model.
* Optionally, you have the option to enable automatic build and deployment. This feature triggers a new deployment automatically whenever there is a new code push to your repository.
* If your model requires additional software packages, configure the Custom Runtime settings by including necessary pip or apt packages. Also, set up environment variables such as  Inference Timeout, Container Concurrency, and Scale Down Timeout to tailor the runtime environment according to your needs.
* Wait for the validation process to complete, ensuring that all settings are correct and functional. Once validation is successful, click on the "Import" button to finalize the import of your model.
  <img src="https://mintcdn.com/inferless-68/g8bkqnienvwe_7dP/images/import.jpg?fit=max&auto=format&n=g8bkqnienvwe_7dP&q=85&s=4537c9473a49fb2b1ba4c9fa609c745c" alt="" width="2654" height="3737" data-path="images/import.jpg" />

### Step 3: Wait for the model build to complete usually takes \~5-10 minutes

### Step 4: Use the APIs to call the model

Once the model is in 'Active' status you can click on the 'API' page to call the model

### Here is the Demo:

<img src="https://mintcdn.com/inferless-68/txuhsMKn8Dl42Mmp/gif/llama-3-demo.gif?s=a2a8dd6b221916392a66cacc7e830ffb" alt="" width="1190" height="691" data-path="gif/llama-3-demo.gif" />

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

### Clone the repository of the model

Let's begin by cloning the model repository:

```bash theme={null}
git clone https://github.com/inferless/Llama-3.git
```

### Deploy the Model

To deploy the model using Inferless CLI, execute the following command:

```bash theme={null}
inferless deploy --gpu A100 --runtime inferless-runtime-config.yaml
```

**Explanation of the Command:**

* `--gpu A100`: Specifies the GPU type for deployment. Available options include `A10`, `A100`, and `T4`.
* `--runtime inferless-runtime-config.yaml`: Defines the runtime configuration file. If not specified, the default Inferless runtime is used.
  <img src="https://mintcdn.com/inferless-68/yfvi5Br0pyuIRFZe/images/cli-image.png?fit=max&auto=format&n=yfvi5Br0pyuIRFZe&q=85&s=ece6380dfb2adcb0b8eba363bb6a2473" alt="" width="2040" height="506" data-path="images/cli-image.png" />
