Tekko

Language

Get in Touch →

Usually respond within 24 hours

Back to BlogAI & ML

Fine-Tuning Phi-3: A Guide to Efficient SLMs with Unsloth and QLoRA

7 min read
Machine LearningPhi-3UnslothFine-TuningLLMOps
Fine-Tuning Phi-3: A Guide to Efficient SLMs with Unsloth and QLoRA

The paradigm of Large Language Models (LLMs) is shifting. While massive models like GPT-4 and Claude 3.5 Sonnet continue to dominate general-purpose benchmarks, technical teams are increasingly discovering that bigger isn't always better for domain-specific task automation. For many enterprise applications—ranging from automated code review to specialized customer support—Small Language Models (SLMs) like Microsoft’s Phi-3 offer a more sustainable path toward production-grade AI.

However, out-of-the-box SLMs often lack the specific nuance required for niche industrial tasks. This is where fine-tuning comes in. By leveraging Unsloth and Quantized Low-Rank Adaptation (QLoRA), we can optimize Phi-3 to perform at a level that rivals much larger models while maintaining a footprint small enough to run on consumer-grade hardware or low-cost cloud instances.

Why Small Language Models (SLMs) for Task Automation?

In a production environment, three constraints typically dictate architectural choices: latency, cost, and privacy.

  1. Latency: A 70B parameter model requires significant time for token generation. For interactive applications like CLI tools or real-time assistants, the 3.8B parameters of Phi-3 Mini provide near-instantaneous responses.
  2. Cost: Running inference on H100 clusters is expensive. SLMs can run on a single A10 or even a T4 GPU, reducing operational expenditures by an order of magnitude.
  3. Privacy: SLMs are small enough to be deployed on-premises or within a VPC without needing complex distributed infrastructure, ensuring sensitive data never leaves your controlled environment.

Phi-3 is particularly interesting because it was trained on "textbook-quality" data. It punches significantly above its weight class in logic and reasoning, making it the ideal base for fine-tuning on structured, domain-specific tasks.

The Efficiency Stack: QLoRA and Unsloth

Fine-tuning a model, even a small one, used to require significant VRAM. Standard fine-tuning updates every single weight in the model, which is computationally prohibitive for most teams.

QLoRA: The Memory Saver

QLoRA (Quantized Low-Rank Adaptation) changes the game by doing two things: it quantizes the base model to 4-bit precision (reducing memory usage by ~75%) and then adds a small set of trainable "adapter" layers. During training, the 4-bit weights remain frozen, and only the lightweight adapters are updated. This allows us to fine-tune a 3.8B model on a GPU with as little as 12GB of VRAM.

Unsloth: The Performance Multiplier

While QLoRA makes fine-tuning possible, Unsloth makes it fast. Unsloth is an open-source framework that provides manually optimized OpenAI Triton kernels for the backpropagation process. In practical terms, Unsloth can make fine-tuning 2x faster and reduce memory usage by an additional 70% compared to the standard Hugging Face trl or peft implementations. For a senior engineer, this means faster iteration cycles and lower compute bills.

Real-World Use Case: Automating API Documentation Support

Imagine you are building an internal tool that helps developers query a massive, proprietary API surface. A general model might hallucinate endpoints or use outdated syntax. By fine-tuning Phi-3 on your internal documentation and past GitHub issues, you create a model that "understands" your specific ecosystem.

Step 1: Data Preparation

Fine-tuning success is 80% data quality. For instruction tuning, we typically use the Alpaca format or the ShareGPT format. Let’s look at a sample for our API assistant:

[ { "instruction": "How do I rotate the API key for the 'PaymentGateway' service?", "input": "Service version: v2.4", "output": "To rotate the API key for PaymentGateway v2.4, use the CLI command: `internal-cli auth rotate --service payment_gateway`. Ensure you update your environment variables within 30 minutes to avoid downtime." } ]

You need roughly 500 to 2,000 high-quality examples like this to see a significant improvement in domain specificity.

Step 2: Implementation with Unsloth

Setting up the training script with Unsloth is surprisingly concise. Here is how we initialize the model and apply the LoRA adapters:

from unsloth import FastLanguageModel import torch # 1. Load the model and tokenizer model, tokenizer = FastLanguageModel.from_pretrained( model_name = "unsloth/Phi-3-mini-4k-instruct", max_seq_length = 2048, load_in_4bit = True, ) # 2. Add LoRA adapters model = FastLanguageModel.get_peft_model( model, r = 16, # Rank: higher means more capacity but more memory target_modules = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"], lora_alpha = 16, lora_dropout = 0, bias = "none", use_gradient_checkpointing = "unsloth", random_state = 3407, )

The target_modules list is crucial. By targeting all linear layers (as recommended by the QLoRA paper), we maximize the model's ability to learn new knowledge while keeping the parameter count low.

Step 3: The Training Loop

Using the Hugging Face SFTTrainer (Supervised Fine-tuning Trainer), we can execute the training. Unsloth integrates seamlessly with the existing ecosystem:

from trl import SFTTrainer from transformers import TrainingArguments trainer = SFTTrainer( model = model, train_dataset = dataset, dataset_text_field = "text", max_seq_length = 2048, args = TrainingArguments( per_device_train_batch_size = 2, gradient_accumulation_steps = 4, warmup_steps = 5, max_steps = 60, # Adjust based on dataset size learning_rate = 2e-4, fp16 = not torch.cuda.is_bf16_supported(), bf16 = torch.cuda.is_bf16_supported(), logging_steps = 1, optim = "adamw_8bit", weight_decay = 0.01, lr_scheduler_type = "linear", seed = 3407, output_dir = "outputs", ), ) trainer.train()

One of the biggest advantages here is the adamw_8bit optimizer. Combined with Unsloth’s kernels, it allows us to train on a single NVIDIA T4 (the free tier on Google Colab) with zero issues.

Evaluating the Results

How do you know if your fine-tuned Phi-3 is actually better? In a professional setting, relying on "vibes" isn't enough.

  1. Loss Curves: Ensure the training loss is steadily decreasing without hitting zero (which indicates overfitting).
  2. Benchmark Tasks: Run the model against a held-out set of questions. Compare the accuracy of the API commands generated by the base Phi-3 versus your fine-tuned version.
  3. Human Eval: For task automation, have a subject matter expert (SME) grade 50 responses on a scale of 1-5. This is often more valuable than any automated metric like ROUGE or METEOR.

Deployment: GGUF and Ollama

Once the model is trained, the goal is to get it into the hands of users. Unsloth makes it easy to export the model to the GGUF format, which is the standard for local inference via tools like Llama.cpp or Ollama.

model.save_pretrained_gguf("model", tokenizer, quantization_method = "q4_k_m")

By exporting to GGUF, you can run your specialized Phi-3 model on a standard MacBook Pro M2/M3 with incredible speed. This opens up the possibility of shipping "Local AI" features in your software, where the model lives entirely on the user's machine, providing total data privacy and zero latency.

Common Pitfalls to Avoid

  • Overfitting on Small Datasets: If you have only 100 examples, don't train for 10 epochs. The model will memorize the data rather than learning the underlying logic. Use a low rank (r=8) and fewer steps.
  • Inconsistent Prompt Templates: Phi-3 uses a specific <|user|> and <|assistant|> format. If your training data doesn't match the format the model expects, inference will be chaotic.
  • Ignoring Tokenization: Ensure your domain-specific terms (like internal function names) aren't being aggressively split into meaningless sub-tokens. If they are, you might need to add them to the tokenizer's vocabulary.

Conclusion: Your Action Plan

Fine-tuning SLMs is no longer a research project reserved for PhDs; it is a viable engineering tool for the modern software stack. To get started, follow these actionable steps:

  1. Identify a narrow task: Don't try to make Phi-3 "smarter" generally. Pick a task like "SQL query generation for our schema" or "Jira ticket classification."
  2. Curate 500 examples: Focus on variety and correctness. One wrong example in a small dataset can significantly degrade performance.
  3. Use the Unsloth Notebooks: Start with Unsloth’s provided Google Colab templates. They are pre-configured with the necessary dependencies and are the fastest way to get a Proof of Concept (PoC) running.
  4. Export and Quantize: Don't ship the raw weights. Quantize to 4-bit or 6-bit GGUF for the best balance of speed and intelligence.

By moving away from massive, expensive APIs and toward specialized, fine-tuned SLMs, you gain control over your AI's performance, cost, and data—a triple win for any engineering organization.