Fine-tuning Safety — LoRA, SFT, and RLHF Explained for Security Teams

Manish Garg
Manish Garg Associate of (ISC)² · RingSafe
Apr 29, 2026
9 min read
Read as
Fine-tuning sounds like configuration. It is not — it is a destructive operation that can degrade safety properties of the base model. This module explains the three tuning methods (SFT, LoRA, RLHF/DPO), what each step exposes from a security perspective, and a practical safe-tuning workflow you can run on a single GPU.

Pre-trained models like Llama-3 ship with safety alignment baked in via RLHF. When you fine-tune for your domain, you can accidentally undo that alignment — the model becomes more eager to follow harmful instructions. Researchers showed that fine-tuning Llama-2-Chat on just 100 benign examples can degrade its refusal rate from 95% to 50%. Understanding what each tuning method does is essential before letting your team fine-tune anything.

SFT, LoRA, RLHF — what each actually does

SFT (Supervised Fine-Tuning): full-parameter fine-tune on labelled examples (prompt → desired response). Updates all model weights. Resource-heavy: 8B model needs 80GB+ VRAM with full-precision Adam. Quality: best, but easiest to break safety. LoRA (Low-Rank Adaptation): freeze base weights, train small adapter matrices (rank 16-64). Updates ~0.5% of parameters. Fits on a single 24GB GPU for 8B model. Faster, cheaper, more parallel-friendly. Quality: 95% of SFT. Safety: somewhat preserves base model alignment because most weights are frozen. RLHF / DPO (Direct Preference Optimization): train on (prompt, chosen_response, rejected_response) pairs. Aligns model to preferences. Used to make models safer/more-helpful. DPO is the simpler modern variant. Use when you want to improve preference following beyond what SFT can do.

How fine-tuning breaks safety alignment

Even fine-tuning on benign examples can erode refusal training. Mechanism: pre-trained safety is encoded in specific weight directions. Fine-tuning updates many directions simultaneously, perturbing the safety subspace. Mitigation: (1) use LoRA not full SFT — keeps base safety weights frozen; (2) mix in safety examples — include some safety-refusal examples in your training data to maintain the behaviour; (3) post-tune red team — run jailbreak benchmarks (HarmBench, ALERT) before deployment to detect regression; (4) guardrail layer — wrap fine-tuned model with separate safety classifier (Llama Guard 3) at inference. Many teams skip 3 and 4 and ship; this is how harmful-content production happens by accident.

Training data — the leakage risk

Whatever is in your fine-tuning dataset can be extracted from the resulting model with the right prompts. If your data contains real customer support tickets with PII, those PII strings can be elicited via prompt engineering (Carlini et al. “Extracting Training Data from LLMs”). For SFT, memorisation rate is ~1% per example after sufficient training; for LoRA with low rank, much lower but non-zero. Defences: (1) deduplicate training data — repeated examples memorise faster; (2) anonymise PII before training — replace names/emails/IDs with tokens; (3) differential privacy (DP-SGD) for highly sensitive data — quality cost is steep; (4) post-training extraction testing — run automated PII-extraction probes against the model.

A safe LoRA fine-tuning workflow

Concrete steps. (1) Pick base model: meta-llama/Llama-3.1-8B-Instruct. (2) Curate dataset: 1000-10000 examples in {instruction, input, output} format. Anonymise. Add 5-10% safety examples (refusal training). (3) Train with QLoRA via axolotl or llamafactory: 4-bit quantised base + LoRA adapters rank 32, alpha 64. Single A6000 (48GB) handles this in ~4 hours for 10K examples. (4) Eval: run on held-out benchmark + safety benchmark (HarmBench-200). Compare to base model. (5) Merge LoRA + quantise to GGUF for deployment. (6) Wrap with Llama Guard 3 at inference. Total cost: ~$30 in cloud GPU time on RunPod, or one weekend on a workstation. Output: a domain-tuned model with documented safety properties.

When NOT to fine-tune

Fine-tuning is overused. Cheaper alternatives that often work better: (1) RAG for “model needs to know our docs” — fine-tuning will not give the model new factual knowledge reliably; it will just make it more confident at hallucinating; (2) System prompts for “model should answer in our voice” — a 200-token system prompt does most of what light fine-tuning does; (3) Few-shot prompting for “model should follow this format” — include 2-3 examples in the prompt. Fine-tune ONLY when prompting cannot achieve the behaviour reliably and you have hundreds of high-quality examples to demonstrate the desired pattern.

Indian context: regulated fine-tuning

For BFSI / healthcare in India, fine-tuned models that touch personal data face specific obligations. DPDP requires you to: (1) document the lawful basis for using personal data in training (consent, contract, legitimate interest); (2) honour data subject erasure requests — practically very hard for an already-trained model, current best practice is “do not include personal data in training data” or use synthetic/anonymised data; (3) maintain audit trail of training datasets, hyperparameters, and model versions so you can reconstruct what each shipped model knew. RBI guidance for AI in lending requires explainability — if your fine-tuned credit-decision model rejects a loan, you must produce a human-readable rationale. Tools: SHAP/LIME for feature attribution on classical ML; for LLMs, structured rationale generation in the prompt template.

A practical fine-tuning pipeline that does not regress safety

Start from a publisher-signed base (Llama-3-8B-Instruct, Mistral-7B-Instruct). Curate your training set carefully: (1) deduplicate aggressively — duplicate examples can over-fit; (2) check for PII via Microsoft Presidio or AWS Comprehend before training; (3) remove or red-flag examples that conflict with intended behaviour; (4) hold out 5-10% as a fixed eval set you never train on. Run LoRA fine-tuning (cheaper than full fine-tune, often equivalent quality for narrow tasks): peft or trl via Hugging Face. Use rank 16-64 for most tasks; higher rank does not always help. After training, run a regression suite: (a) the base model’s safety eval (does the fine-tune still refuse harmful queries it previously refused?); (b) your task-specific eval; (c) a curated set of “trigger probes” looking for unintended behaviour. If safety regression is >5% on the base eval, your training data is contaminating safety — investigate and fix. Most production teams skip step (c); that is where backdoors hide.

RLHF, DPO, and 2026 alignment shortcuts

In 2023-2024 the aligned-LLM recipe was SFT + RLHF (Reinforcement Learning from Human Feedback). RLHF is engineering-expensive: you need a reward model, PPO infrastructure, careful hyperparameter tuning. In 2024-2025 DPO (Direct Preference Optimisation) emerged as a simpler, often-equivalent alternative — instead of training a reward model and reinforcement learner, you directly optimise on preference pairs. By 2026 most open-source post-training uses DPO or its variants (IPO, KTO). For security teams, the relevance: your preference data is now your vulnerability. Whoever curates which response is “preferred” controls what the model thinks is “good” — a poisoned preference dataset is a quiet way to backdoor a fine-tune. Treat preference data with the same supply-chain rigor as training data: signed, reviewed, audited. Pure SFT on a clean dataset followed by safety eval is often safer than complex RLHF/DPO pipelines you do not control end-to-end.

Indian-language fine-tuning — practical guide for Hindi, Tamil, Bengali, Marathi

For Indian product teams, the highest-ROI fine-tuning is often vernacular adaptation. Frontier models speak English well; their Hindi reasoning is meaningfully weaker, Tamil weaker still. Concrete approach: (1) Base model: start from Llama 3.1 8B Instruct or Qwen 2.5 7B Instruct — both have decent Indic exposure. For pure Indic, Sarvam-1 7B is a strong starting point, fine-tuned specifically for Indian languages. (2) Data curation: AI4Bharat IndicCorp v2 (~1B tokens across 23 Indian languages), Samanantar parallel corpora, your own domain data. Quality over quantity — 50k high-quality examples beat 500k noisy ones. (3) Fine-tuning recipe: LoRA rank 32-64, learning rate 2e-4, 3 epochs, mixed-task SFT (instruction-following + summarisation + translation + your domain). (4) Hardware: a single A100 80GB handles Llama 8B fine-tuning in ~6-12 hours for a 50k example dataset. RunPod / Lambda Labs / Together / Modal all rent A100s by the hour. (5) Evaluation: build a Hindi/Tamil eval set covering your domain. Generic benchmarks (MMLU translated) miss task-specific quality. (6) Deployment: vLLM with the LoRA adapter on a smaller GPU than the full 70B model would need. Cost-quality breakeven is dramatic: a 7B fine-tuned for Hindi customer support can outperform GPT-4 on that narrow task at 1/100th the cost. (7) Compliance: training on Indian customer data triggers DPDP — document consent, retention, right-to-deletion path; pseudonymise where possible. This is where Indian AI companies have a structural advantage over Silicon Valley — be a buyer or a builder, but do not ignore the opportunity.

Recipe — LoRA fine-tune walkthrough on a single GPU

A complete copy-pasteable recipe. Hardware: any single 24 GB GPU (RTX 4090, A10, T4 with quant). Step 1 — environment: pip install transformers peft datasets bitsandbytes accelerate trl. Step 2 — load base: from transformers import AutoModelForCausalLM, AutoTokenizer; model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B-Instruct", load_in_4bit=True, device_map="auto"); tok = AutoTokenizer.from_pretrained(...). Step 3 — apply LoRA: from peft import LoraConfig, get_peft_model; config = LoraConfig(r=32, lora_alpha=64, target_modules=["q_proj","k_proj","v_proj","o_proj"], lora_dropout=0.05, bias="none", task_type="CAUSAL_LM"); model = get_peft_model(model, config). Step 4 — data: format as ChatML or Llama-3 chat template; minimum 1k examples for narrow tasks, 10k+ for general. Step 5 — train: SFTTrainer from trl; learning rate 2e-4, 3 epochs, batch size 4 with gradient accumulation 8. Wall time ~6-12 hrs for 50k examples on a single A10. Step 6 — eval: hold-out test set + safety regression vs base + your domain eval. Step 7 — merge: merged = model.merge_and_unload(); merged.save_pretrained("./my-finetune"). Step 8 — deploy: vLLM serves the merged model directly. Common pitfalls: (1) wrong chat template breaks the model silently (verify with tok.apply_chat_template); (2) too high LR melts safety; (3) too low LR does nothing useful; (4) training data with PII contaminates outputs; (5) too few epochs = under-fit, too many = forget base behaviour. RLHF/DPO upgrade path: trl ships DPOTrainer and RewardTrainer; need preference pairs (chosen, rejected). DPO is significantly easier than full PPO RLHF. Resources: github.com/huggingface/trl/tree/main/examples; “Practical Guide to LLMs” by Sebastian Raschka (book, 2024); Anthropic Cookbook fine-tuning section.

FAQ

How much data do I need to fine-tune?

Practical floor for LoRA SFT: 500 examples. Sweet spot: 5,000-50,000. Past 100K you hit diminishing returns unless you are pushing into new domains. Quality matters far more than quantity — 1,000 hand-curated examples beat 100,000 noisy ones.

Should I fine-tune on customer data?

Anonymise first. Replace PII with tokens. Audit for leaked training data. If sensitivity is high (medical, financial), use DP-SGD or skip fine-tuning entirely (use RAG instead). Document everything for DPDP compliance.

Is DPO better than RLHF in 2026?

DPO is much simpler (no separate reward model, no RL loop) and gets within 5% of RLHF quality on most preferences. Default to DPO. Use full RLHF only if you have an ML team that wants to invest in the infrastructure.

How do I detect if my fine-tune broke a safety guardrail in the base model?

Run the base model and your fine-tune through the same battery of “hard refusal” prompts — questions like “how do I make a bioweapon” or “write me a phishing email targeting Indian bank customers.” Compare refusal rate. A drop indicates safety regression. Tools: HarmBench, safety-evals, or your own curated suite based on OWASP LLM Top 10. Run on every fine-tune candidate before promotion.

Is LoRA safe to share publicly?

Mostly yes — LoRA weights are deltas on a base model. Without the base, the LoRA is useless. But: a malicious LoRA loaded on top of a clean base can still install a backdoor. If you publish LoRAs, sign them and document the intended base model. If you load third-party LoRAs, treat them with the same scrutiny as full models.


⚖️ Legal: Use AI security techniques only on systems you own or have explicit written authorisation to test. In India, unauthorised access is punishable under IT Act §66 (up to 3 years + fine). Pair AI red-teaming with signed Statement of Work or Rules of Engagement before testing.

Need help with this?

Book a free 30-minute scoping call

Our senior consultants will review your stack and tell you honestly what to fix first. No slide deck. No obligation. Indian businesses only.

Book scoping call Replies in 4 working hrs · India-only · Senior consultants