Savvita LLM Fine-Tuning Pipeline Framework
Design and execute a complete, stage-correct LLM fine-tuning strategy — from selecting the right training stage to implementing parameter-efficient techniques — for any domain-specific AI use case.
// TL;DR
The Savvita LLM Fine-Tuning Pipeline Framework is a decision framework for adapting pre-trained large language models to specific domains, tasks, or alignment goals. It maps every fine-tuning project onto three sequential stages — Unsupervised Pre-Training, Supervised Fine-Tuning (SFT), and Preference-Based Alignment — then guides you through choosing the right parameter-level technique (LoRA, QLoRA, DoRA) and data-level format (plain text vs. instruction pairs vs. chosen/rejected). Use it whenever you need to decide which stage to enter, which PEFT method fits your GPU budget, and how to sequence multiple fine-tuning stages to build a domain-specific, safe, conversational model.
// When should you use the Savvita LLM Fine-Tuning Pipeline Framework?
Use this skill whenever you need to adapt a pre-trained large language model to a specific domain, task, or alignment requirement, or when you need to decide which fine-tuning stage and technique best matches your data, compute, and output goals.
// What do you need before starting an LLM fine-tuning project?
- Target domain or use caserequired
What industry, task, or capability the model needs to serve (e.g., pharma QA, legal chatbot, code assistant). - Data type and formatrequired
Whether the available data is plain text (PDF, TXT), instruction/QA pairs, or preference-ranked responses (chosen/rejected). - Starting modelrequired
The base or instruct LLM to be fine-tuned (e.g., LLaMA 3, Mistral 7B, TinyLlama). Identify whether it is a base model or already instruction-tuned. - Compute constraintsrequired
Available GPU memory, number of GPUs, and whether a free or paid runtime is available (e.g., single T4, A100, multi-GPU cluster). - Desired output behaviourrequired
Whether the end goal is domain knowledge injection, conversational ability, structured QA, or human-aligned safe responses.
// What core principles guide stage-correct LLM fine-tuning?
Three-Stage LLM Training Pipeline
Every production LLM follows three sequential stages: Unsupervised Pre-Training → Supervised Fine-Tuning (SFT) → Preference-Based Alignment. Knowing which stage you are entering determines every downstream decision about data format, technique, and tooling.
Parameter-Level vs. Data-Level Thinking
SFT decisions must be made on two independent axes simultaneously: the parameter level (full fine-tuning vs. PEFT techniques like LoRA, QLoRA, DoRA) and the data level (non-instructional vs. instructional data format). Conflating these axes leads to mismatched pipelines.
Full Fine-Tuning Avoidance Rule
Full fine-tuning trains all weights and biases and requires huge GPU memory plus a multi-GPU setup. For any resource-constrained scenario, always default to PEFT techniques rather than full fine-tuning.
Non-Instructional vs. Instructional Finetuning
Non-instructional finetuning (domain adoption) uses plain text and trains the model to predict the next token — injecting domain knowledge without teaching conversational behaviour. Instructional finetuning uses instruction-and-response pairs to make the model chat-enabled. These are sequential, not interchangeable.
Self-Supervised Data Preparation
For non-instructional finetuning, plain text (PDF, TXT) must be chunked and formatted so that every token is simultaneously the input and the shifted label — mirroring the next-token-prediction objective used in unsupervised pre-training.
Preference Alignment as the Final Polish
After SFT, the model generates responses but may not be polite, safe, or aligned with human values. Preference-Based Alignment (using DPO or RLHF/PPO) retrains the model on chosen/rejected response pairs to close this gap.
LoRA as the PEFT Baseline
LoRA (Low-Rank Adaptation) is the foundational PEFT technique. All other techniques — QLoRA, DoRA, IA3, adapter layers, prefix tuning — either extend or modify LoRA. When in doubt, start with LoRA; use QLoRA when loading quantised models for memory-efficient training.
Base Model Identification Rule
A model named without 'instruct', 'chat', or similar suffix (e.g., LLaMA-3.1-8B, Mistral-7B) is a base model — safe to use as the starting point for the full three-stage pipeline. Models with 'instruct' or 'chat' suffixes have already undergone SFT and possibly alignment.
// How do you fine-tune an LLM step by step with this framework?
- 1
Identify which training stage you are entering
Map your goal to one of the three stages: (1) Unsupervised Pre-Training — build a base model from scratch (almost never done outside large organisations with massive infrastructure); (2) SFT — adapt or instruction-tune an existing base model; (3) Preference-Based Alignment — align an already SFT-tuned model to human feedback. Most practitioners start at Stage 2 or 3.
- 2
Select and audit your base model
Pick a model from Hugging Face matching your compute constraints (smaller models like TinyLlama 1.1B for single free GPU; larger models like LLaMA 3 8B for paid/multi-GPU). Confirm it is a base model if you intend to run the full SFT pipeline. Check the model card for context window size — this determines your chunking strategy.
- 3
Audit your data and assign it to a data-level category
Classify your data as: (a) Plain text (PDF, TXT, web crawl) → Non-Instructional Finetuning; (b) Instruction-and-response or QA pairs → Instructional Finetuning; (c) Prompt + chosen + rejected response triples → Preference Alignment. If you have plain text but want a chatbot, you must pass through non-instructional finetuning first, then create or source instructional data for the next stage.
- 4
Choose your parameter-level strategy (PEFT technique)
For single GPU or limited memory: use LoRA or QLoRA (QLoRA when loading a quantised model). For experimental or research settings: consider DoRA, IA3, adapter layers, or prefix tuning. Avoid full fine-tuning unless you have multi-GPU infrastructure and very large domain datasets. Set LoRA hyperparameters: rank (r), alpha, target modules.
- 5
Prepare and preprocess the dataset for your chosen stage
Non-Instructional: Extract plain text from source (use pymupdf/fitz for PDFs), clean and chunk by paragraph, semantic boundary, or token length (respecting the model's context window). Convert to Hugging Face Dataset format with a single 'text' column. Set labels = input_ids (for causal language modelling / next-token prediction). Instructional: Format as instruction + response pairs; apply the model's chat template. Preference Alignment: Ensure dataset has 'prompt', 'chosen', and 'rejected' columns.
- 6
Configure tokenisation with truncation, padding, and max-length
Always set truncation=True and padding=True with a fixed max_length matching your chunk strategy and model context window. Assign pad_token = eos_token if pad_token is None. For causal LM, set labels = input_ids so the model trains on next-token prediction across the entire sequence.
- 7
Install and configure the correct framework and libraries
Core stack: transformers, datasets, accelerate (for multi-GPU; install even on single GPU for dependencies), bitsandbytes (for quantised/QLoRA loading), peft (for LoRA configuration and PEFT adapters), trl (Transformer Reinforcement Learning — required for SFT Trainer and DPO Trainer). For PDF loading: pymupdf (fitz). Optional high-performance frameworks: Unsloth (faster LoRA training), Axolotl, LLaMA Factory — all produce compatible outputs.
- 8
Load the model and apply the PEFT configuration
Load the base model using AutoModelForCausalLM. If using QLoRA, load with BitsAndBytesConfig (lower precision / 4-bit or 8-bit). Apply LoraConfig via the peft library, specifying rank, alpha, dropout, and target modules. Wrap the model with get_peft_model().
- 9
Define training arguments and launch training
Use TrainingArguments (from transformers) or SFTTrainer (from trl) for instructional finetuning; use DPOTrainer (from trl) for preference alignment. Key hyperparameters: output_dir, num_train_epochs, per_device_train_batch_size, learning_rate, logging_steps, save_steps. Use DataCollatorForLanguageModeling for non-instructional finetuning. Run training and monitor loss.
- 10
Sequence multiple fine-tuning stages if needed
The recommended production sequence for a domain-specific conversational model: (1) Start with base model → Non-Instructional Finetuning on domain plain text → domain-expert base model. (2) Continue with Instructional Finetuning on domain QA pairs → domain chatbot. (3) Apply DPO on chosen/rejected pairs → aligned, safe, helpful domain chatbot. Each stage takes the output model of the previous stage as its starting point.
- 11
Validate and iterate
After each stage, test the model with representative prompts. Non-instructional output will be continuous text, not structured answers — this is expected. Only after instructional finetuning should the model follow instructions. Only after preference alignment should the model be consistently polite, safe, and human-value-aligned.
// What do real LLM fine-tuning projects look like using this framework?
A pharmaceutical company has a large corpus of internal research documents (PDFs) and wants to build an internal QA chatbot that answers domain-specific questions accurately and professionally.
Stage 1 — Non-Instructional Finetuning: Extract and chunk all PDF text, format as a Hugging Face Dataset with a 'text' column, and fine-tune a base LLM (e.g., LLaMA 3 8B) using LoRA/QLoRA with causal language modelling (labels = input_ids) to inject pharma domain knowledge. Stage 2 — Instructional Finetuning: Create or source QA pairs from the same domain corpus, format as instruction/response pairs, and run SFT using the trl SFTTrainer on the Stage 1 model. Stage 3 — DPO Alignment: Collect or generate chosen/rejected response pairs reflecting the company's preferred tone and safety standards, then run DPOTrainer to align the model.
An individual developer wants to fine-tune an open-source model for a coding assistant on a single consumer GPU with limited VRAM.
Select a quantised base model (e.g., Mistral 7B in 4-bit) and apply QLoRA via BitsAndBytesConfig + LoraConfig from peft. Source an existing instructional finetuning dataset from Hugging Face (e.g., a code instruction dataset with instruction/response columns). Run SFTTrainer from trl with a small per_device_train_batch_size. Skip non-instructional finetuning since the base model already has sufficient general coding knowledge. Optionally apply DPO using a chosen/rejected preference dataset if safety and helpfulness alignment is needed.
A company wants to understand whether to train from scratch or fine-tune an existing model.
Apply the Three-Stage LLM Training Pipeline principle: training from scratch (Unsupervised Pre-Training) requires massive internet-scale data, huge GPU infrastructure, and multi-GPU clusters — only feasible for large organisations like Meta, Google, or Mistral. For any company without this infrastructure, pick an open-weight base model (LLaMA, Mistral, DeepSeek) and enter at Stage 2 (SFT) or Stage 3 (Preference Alignment), depending on whether the chosen model is already instruction-tuned.
// What mistakes should you avoid when fine-tuning an LLM?
- Confusing a base model with an instruct/chat model — always check the model name and card before choosing your starting stage; using an already-instruction-tuned model as if it were a base model wastes compute and corrupts the pipeline.
- Skipping the non-instructional finetuning stage when domain knowledge is critical — jumping directly to instructional finetuning on QA pairs without first injecting domain knowledge produces a chatty model with shallow domain understanding.
- Attempting full fine-tuning on a single consumer GPU — full fine-tuning trains all weights and biases and requires huge GPU memory plus multi-GPU setup; always use LoRA or QLoRA instead.
- Using the wrong data format for the stage — plain text fed into an instructional finetuning pipeline, or QA pairs fed into a non-instructional pipeline, will produce a model that does not behave as expected.
- Not setting pad_token = eos_token when the tokeniser has no pad token — this causes padding errors during batched training.
- Ignoring chunk size relative to the model's context window — chunks longer than the model's max token limit will be silently truncated, losing information; chunks that are too short are inefficient.
- Treating DPO/RLHF as optional polish — if the end product is a user-facing assistant, skipping preference alignment produces a model that may be technically capable but unsafe, impolite, or misaligned with user expectations.
- Assuming one framework fits all — Hugging Face Transformers, Unsloth, Axolotl, and LLaMA Factory have different performance profiles and trade-offs; benchmark on your specific model and hardware before committing to one.
// What are the key terms in LLM fine-tuning explained?
- Unsupervised Pre-Training
- The first stage of the LLM training pipeline, also called self-supervised learning, where the model is trained on massive internet-scale text to predict the next token. This stage develops the model's general language understanding and produces a base model.
- SFT (Supervised Fine-Tuning)
- The second stage of the LLM training pipeline, encompassing both non-instructional and instructional finetuning. Operates on two axes: parameter level (full vs. PEFT) and data level (plain text vs. instruction-response pairs).
- Non-Instructional Finetuning
- SFT using plain text data (PDF, TXT, web crawl) formatted for next-token prediction. The goal is domain adoption — injecting domain-specific knowledge into the model — not teaching conversational or instruction-following behaviour.
- Instructional Finetuning
- SFT using data formatted as instruction-and-response (or input-output, question-answer) pairs. The goal is to make the model chat-enabled and capable of following human instructions — converting a base model into a conversational AI or chatbot.
- Preference-Based Alignment
- The third stage of the LLM training pipeline, also called alignment with human feedback. Retrains an SFT model on human-ranked response pairs (chosen/rejected) to make it polite, safe, helpful, and aligned with human values.
- RLHF (Reinforcement Learning from Human Feedback)
- A preference alignment technique that uses the PPO (Proximal Policy Optimization) reinforcement learning algorithm to align model responses with human preferences. Used by OpenAI for ChatGPT.
- DPO (Direct Preference Optimization)
- A supervised preference alignment technique that trains directly on chosen/rejected response pairs without requiring a separate reward model or reinforcement learning loop. The currently preferred technique for preference alignment.
- PPO (Proximal Policy Optimization)
- The reinforcement learning algorithm underlying RLHF. Stands for Proximal Policy Optimization.
- PEFT (Parameter Efficient Fine-Tuning)
- A family of techniques that train only a subset of model parameters (not all weights and biases), enabling fine-tuning on a single GPU with smaller memory. Umbrella term for LoRA, QLoRA, DoRA, adapter layers, IA3, bitfit, and prefix tuning.
- Full Fine-Tuning
- Training all parameters (weights and biases) of a model. Requires huge GPU memory and typically a multi-GPU setup. Generally avoided in favour of PEFT techniques.
- LoRA (Low-Rank Adaptation)
- The foundational PEFT technique. Inserts trainable low-rank decomposition matrices into the transformer's existing layers instead of updating all weights. The base for most other PEFT variants.
- QLoRA (Quantised LoRA)
- LoRA applied on top of a quantised (lower-precision) model. Enables memory-efficient loading and training of large models on limited hardware. The Q represents quantisation.
- DoRA (Weight Decomposition Low-Rank Adaptation)
- A PEFT technique that decomposes weight matrices before applying low-rank adaptation. An extension of LoRA.
- IA3 (Infused Adapter by Inhibiting and Amplifying Inner Activations)
- A PEFT technique that improves upon LoRA by infusing learned vectors that inhibit or amplify inner activations of the transformer. Part of the Hugging Face PEFT library.
- Adapter Layers
- A PEFT technique that appends small trainable layers to existing transformer blocks, inspired by LoRA.
- Prefix Tuning
- A PEFT technique that prepends trainable prefix tokens to the input sequence, conditioning the model's behaviour without modifying its weights.
- Base Model
- A model that has undergone only unsupervised pre-training. It has general language and world knowledge but cannot reliably follow instructions or hold conversations. Identified in model names by the absence of 'instruct', 'chat', or similar suffixes.
- Next Token Prediction
- The core training objective of both unsupervised pre-training and non-instructional finetuning. The model learns to predict the next token given all previous tokens in a sequence. Also called causal language modelling.
- TRL (Transformer Reinforcement Learning)
- A Hugging Face library providing SFTTrainer and DPOTrainer, required for implementing both instructional finetuning and preference alignment in the Hugging Face ecosystem.
- bitsandbytes
- A library (by Tim Dettmers, hosted under Hugging Face) used to load quantised models in lower precision (4-bit or 8-bit) for memory-efficient training, enabling QLoRA.
- Chosen / Rejected
- The two mandatory columns in every preference alignment dataset. 'Chosen' is the response rated positively by humans; 'rejected' is the response rated negatively. DPO trains the model to prefer chosen over rejected responses.
// FREQUENTLY ASKED QUESTIONS
What is the Savvita LLM Fine-Tuning Pipeline Framework?
It's a decision framework that maps any LLM fine-tuning project onto three sequential stages — Unsupervised Pre-Training, Supervised Fine-Tuning (SFT), and Preference-Based Alignment. It then helps you choose the right parameter-level technique (LoRA, QLoRA, DoRA) and data-level format (plain text, instruction pairs, or chosen/rejected pairs) so your pipeline matches your data, compute, and output goals.
What are the three stages of LLM training?
The three stages are Unsupervised Pre-Training (train a base model from scratch on internet-scale text via next-token prediction), Supervised Fine-Tuning (adapt or instruction-tune a base model), and Preference-Based Alignment (align an SFT model to human values using DPO or RLHF). Most practitioners start at Stage 2 or 3 because Stage 1 requires massive infrastructure.
How do I decide between full fine-tuning and PEFT?
Default to PEFT (LoRA or QLoRA) for any resource-constrained scenario. Full fine-tuning trains all weights and biases, requiring huge GPU memory and a multi-GPU setup. Only choose full fine-tuning if you have multi-GPU infrastructure and a very large domain dataset. On a single consumer GPU, always use LoRA, or QLoRA when loading a quantised model.
How do I fine-tune an LLM on a single GPU?
Pick a small or quantised base model (e.g., TinyLlama 1.1B or Mistral 7B in 4-bit), load it with BitsAndBytesConfig, and apply QLoRA via LoraConfig from the peft library. Use trl's SFTTrainer for instructional data with a small per_device_train_batch_size. Set pad_token = eos_token if the tokeniser lacks one, and enable truncation and padding at a fixed max_length.
How does this framework compare to just prompting a base model?
Prompting relies on a model's existing knowledge and instruction-following ability, which base models lack. This framework injects domain knowledge (non-instructional finetuning), teaches conversational behaviour (instructional finetuning), and aligns tone and safety (DPO/RLHF). Fine-tuning produces persistent, domain-expert behaviour that prompting alone cannot reliably deliver for specialised use cases.
When should I use non-instructional versus instructional finetuning?
Use non-instructional finetuning first when you have plain text (PDFs, TXT) and need to inject domain knowledge via next-token prediction. Use instructional finetuning afterward, with instruction/response pairs, to make the model chat-enabled. They are sequential, not interchangeable — skipping domain injection produces a chatty model with shallow domain understanding.
What is the difference between DPO and RLHF?
Both are preference-alignment techniques using chosen/rejected response pairs. RLHF uses the PPO reinforcement learning algorithm plus a separate reward model (used by OpenAI for ChatGPT). DPO (Direct Preference Optimization) trains directly on the pairs without a reward model or RL loop, making it simpler and currently the preferred technique for most practitioners.
How do I know if a model is a base model or already instruction-tuned?
Check the model name and card. A model without 'instruct', 'chat', or similar suffix (e.g., LLaMA-3.1-8B, Mistral-7B) is a base model, safe for the full three-stage pipeline. Names with 'instruct' or 'chat' suffixes have already undergone SFT and possibly alignment — treating them as base models wastes compute and corrupts the pipeline.
When should I apply preference alignment like DPO?
Apply DPO (or RLHF) after SFT whenever your end product is a user-facing assistant. After SFT, a model can follow instructions but may be impolite, unsafe, or misaligned with user expectations. Preference alignment retrains it on chosen/rejected pairs to make responses consistently polite, safe, helpful, and human-value-aligned. Skip it only for internal, non-user-facing tools.
What results can I expect after running the full pipeline?
After non-instructional finetuning, output is continuous domain text (not structured answers) — this is expected. After instructional finetuning, the model follows instructions and holds conversations. After DPO alignment, it is consistently polite, safe, and helpful. The end product is a domain-expert conversational assistant that reflects your corpus knowledge and preferred tone.
Which libraries do I need to fine-tune an LLM with this framework?
The core stack is transformers, datasets, accelerate, bitsandbytes (for QLoRA/quantisation), peft (for LoRA configs), and trl (for SFTTrainer and DPOTrainer). Use pymupdf (fitz) to extract PDF text. Optional high-performance frameworks include Unsloth, Axolotl, and LLaMA Factory, all of which produce compatible outputs.
What is LoRA and why is it the PEFT baseline?
LoRA (Low-Rank Adaptation) inserts trainable low-rank matrices into a transformer's existing layers instead of updating all weights, drastically reducing memory needs. It's the foundational PEFT technique — QLoRA, DoRA, IA3, adapter layers, and prefix tuning all extend or modify it. When in doubt, start with LoRA; use QLoRA when loading a quantised model.