FINETUNING LLMs
Finetuning is a process in which, we select a pretrained base/instruct model of a LLM, and tune the parameters to understand our training dataset. We Finetuned Llama3.1-8B and Llama3.2-3B on SEC 10k annual reports.
There are two ways to finetune a model –
- a) Full Finetuning
- b) PEFT.
The former, as its name suggests, would update all of the model’s parameters and layers, which can be time consuming and expensive, While the latter, only updates a subset of the model’s parameters, focusing on the most important parameters required for the new task.
Prerequisites
PEFT based fine tuning can be broadly classified into LORA, QLORA, Prefix Tuning, etc. The following process is trained using LORA. The prerequisites are listed below:
- Axolotl / SFT trainer / autotrain / peft
- Pytorch
- Transformers
- Instruct Dataset
- GPU with at least 40GB VRAM (for 16 bit precision)
There’s a lot to unpack there, but let’s take one step at a time.
So Parameter Efficient Fine Tuning (PEFT) is a fine-tuning technique, where most of the model’s pretrained parameters are frozen and only a set of trainable parameters (also called as adapters) are updated. This is different from full finetuning, where all the parameters are updated, which is more expensive and time-consuming. PEFT also safeguards the model’s pretrained weights largely, whereas in full fine-tuning it has a risk of catastrophic forgetting, where it fails to remember its training.
Low Rank Adaptation (LoRa) is a PEFT technique which performs rank decomposition on the updated weight matrices. Not diving too deep into its implementation details, we understand that, by only operating on a set of adapters, reduces the memory footprint of the model used and also reduces the training time. Using a precision and a quantization technique, aids us further by making the model even smaller.
Precision techniques help us load the model in fp16 (Floating point precision 16) or fp8 (Floating point precision 8), by decreasing the size of the model weights. For example, a model’s weight at full precision (fp32) would like this:
| 0.12459001 | -15.23984734 | 15.23984103 | -235.23230103 |
| 12.83740008 | 0.00084103 | -15.23984103 | -15.23984103 |
| -24.13984031 | -15.23984103 | 105.23984103 | 5.30084000 |
On a very low level, the machine might be storing each of these decimal points with 32 bit precision.
32 bit precision

So precision techniques convert this into lower precision by cutting down the space allocated for precision.
16 bit precision:

So converting the weight matrix to 16 bit would look something like this:
| 0.1246 | -15.2398 | 15.2398 | -235.2323 |
| 12.8374 | 0.0008 | -15.2398 | -15.2398 |
| -24.1398 | -15.2398 | 105.2398 | 5.3008 |
Model quantization is also another deep learning optimization technique that reduces the size and memory footprint of a neural network model. It does this by converting the model’s weights and activations from floating-point numbers to lower-precision formats, like 8-bit or 16-bit integers. It also converts to integer formats like int16 or int8.
Libraries like Axolotl, SFT-trainer simplify the process of running a fine-tuning operation by abstracting a lot of the implementation details, but on a higher level, it works by the principles we discussed earlier.
We used Modal-labs to Fine-tune Llama3.1-8b-Instruct on the SEC 10k annual report of multiple companies.
Why Modal?
Modal is a next-generation platform designed to simplify the deployment and scaling of applications for data, AI, and machine learning. By building a custom infrastructure—including a proprietary file system, container runtime, and image builder—Modal provides developers with a seamless, high-performance environment to iterate and ship faster.
Modal supports a wide range of use cases such as Generative AI inference, LLM fine-tuning, computational biotech, and media processing. With minimal code, developers can scale workloads from zero to thousands of CPUs or GPUs, all through a fully usage-based pricing model, ensuring cost efficiency and flexibility.
We used Modal to fine-tune and deploy an inference to test the model’s output.
Installation
Behind the scenes Modal-labs makes use of axolotl, but we could replace it with any of the other available finetuning operators, we listed above.
Axolotl makes it possible for us to finetune a large model from cli (command line interface) by executing a train file, which makes use of a config file and a prepared dataset. Find more details here .
Official Modal Guide: https://github.com/modal-labs/llm-finetuning
Modal Setup
The official Modal-Labs guide has a step by step guide, to fine-tune a LLM and deploy and (or) download it to a local machine (personal laptop or desktop). We tried to lay out the steps that worked for us, in building the Extractor and also fine-tuning steps.
The first step is to create a virtual environment, for all our prerequisites.
a. The First step would be to create a root directory, within which we would do our project setup.
mkdir FineTuneLlama && cd FineTuneLlama
b. This step creates a python virtual environment called modalEnv, and all our further steps would be run within the virtual environment.
python -m venv modalEnv
c. The Final step would be to activate the virtual environment
Linux and Mac:
source modalEnv/bin/activate
Windows:
modalEnv/bin/activate
a. Installing Modal
pip install modal
b. Modal python setup
python -m modal setup
The Setup above initializes a browser call, which requests for Modal account authentication, and sets up the secret key and also sets up the project. This allows us to use all the modal commands from our machine. More on this can be found here.
Also ensure that you have created a HuggingFace secret key variable, which stores the huggingface api key. The secrets can be accessed from the UI of your modal Dashboard.
Cloning the Fine-tuning Project
a. Clone the pre-configured Github repository provided by Modal
git clone https://github.com/modal-labs/llm-finetuning.git && cd llm-finetuning
If you have followed till this step, you might find yourselves in a repository, with the following structure.
.
├── LICENSE
├── README.md
├── ci
│ ├── check_inference.py
│ ├── check_loss.py
│ └── prep_for_ci.py
├── config
│ ├── codellama.yml
│ ├── llama-3.yml
│ ├── mistral-memorize.yml
│ ├── mistral.yml
│ ├── mixtral.yml
│ ├── mixtral_out_of_box.yml
│ └── pythia.yml
├── data
│ ├── modal_docs.jsonl
│ ├── samsum.jsonl
│ ├── sqlqa.jsonl
│ └── sqlqa.subsample.jsonl
├── mixtral_error.txt
└── src
├── __init__.py
├── common.py
├── inference.py
└── train.py
This directory structure resembles the axolotl’s structure. Key things to understand
- Config: Contains the configuration yml files, which can be modified, to set the llm, we want to finetune, dataset path, lora settings, gradient values, etc.
- Data: This is where our dataset is going to be placed, it must be in any one of the standard templates, else the custom template must be provided in the config file.
Training
Once these 2 files have been configured, we can run the training script, which would handle the rest.
modal run --detach src.train --config=config/llama-3.yml --data=data/sharegpt.jsonl
The modal run command initiates the training, and we see that both config file, and dataset is provided in the command.
Inference
modal run -q src.inference --run-name axo-2024-10-22-02-26-58-553b < query.txt
Once the fine-tuning process is complete, the run_id can be extracted from the logs for subsequent steps. Using this identifier, inference can be executed through Modal, which initializes a temporary instance to deploy and test the model endpoint. The user prompt for testing can be provided by saving it in a file named query.txt and passing it as input. Alternatively, the query can be supplied directly as a command-line parameter.
Deployment
Deploying a model with Modal is a straightforward process, closely resembling the steps for running an inference. However, deployment involves setting up a persistent server that can be monitored and scaled as needed. To begin, you create a deployment.py file, which contains the code for configuring and serving the model. The linked guide provides detailed instructions on integrating FastAPI and vLLM to enable high-performance inference. The deployment generates a secure endpoint protected by JWT authentication, ensuring access is restricted to authorized users.
modal deploy deployment.py
Exporting the model
In highly regulated industries, there may be a need to host the model in a different environment. In such situations, Modal provides the ability to download the entire model file and deploy in any cloud environment. In the section below, I am sharing the details for deploying the model on a laptop and serving it via Ollama.
Saving the Models to your laptop/desktop
In order to persist the models in our local system, or push it to a cloud service provider, we could follow the following steps:
modal volume list
modal volume ls example-runs-vol
modal volume ls example-runs-vol <run-id>
modal volume get example-runs-vol <run-id>/outputs/lora-out/merged
The commands provided above help us to list all the runs, and get or fetch a particular run_id and the model it generated.
The model is available in the merged folder inside lora-out.
For eg:
To download the modal to local:
modal volume get example-runs-vol axo-2024-10-29-23-04-37-85af/outputs/lora-out/merged localModel
The above code will download a model from the modal’s server to a folder named localModel.
Convert to Ollama:
After downloading the finetuned model, we can then convert them into Ollama compatible inference points by following steps:
a. Fetch the llama.cpp.git file from ggerganov’s github repository. This repository helps us convert the model which we fine-tuned into gguf (Generated Unified Format ) format. It’s a binary file format for storing and loading large language models. The Ollama model can be created directly from a gguf model.
git clone https://github.com/ggerganov/llama.cpp.git
pip install -r llama.cpp/requirements.txt
b. Convert the finetuned model into gguf format
python llama.cpp/convert_hf_to_gguf.py ../localModel/merged/ --outfile Finetuner.gguf --outtype auto
Outtype can be one of (‘q8_0’, ‘auto’, ‘f16’, ‘f32’, ‘q4_0’)
The gguf file, once captured, can now be used to create a Ollama model.
sudo snap install ollama
ollama list
ollama create finetunedLlama -f Modelfile
MODELFILE EXAMPLE
FROM "llamaFinetunerQ8.gguf"
PARAMETER temperature 0.7
PARAMETER num_ctx 4096
PARAMETER num_predict -1
Finally, we have a deployable Ollama model called finetunedLlama, we can run/serve this using:
Run CLI:
ollama run finetunedLlama
Serve as an API:
ollama serve finetunedLlama