AWS Builder Center

From Generic to Domain Expert: Building an Industry-Specific LLM with QLoRA on AWS SageMaker

A complete walkthrough of fine-tuning a 1.5B open-source model on proprietary domain content using QLoRA, SageMaker, and Amazon Bedrock applicable to any industry where valuable knowledge lives in internal documents, SOPs, or delivery methodologies. Covers data augmentation, the two-step LoRA merge, endpoint deployment, and LLM-as-Judge evaluation. Base model scores 1.2/5; fine-tuned model scores 4.2/5 on held-out questions it had never seen.

The Problem Every Enterprise Faces

Most organisations adopting LLMs hit the same wall quickly: the model knows nothing about their proprietary content. Internal methodologies, product documentation, compliance frameworks, delivery guides: none of it appears in the training data, so the model hallucinates confidently and fluently when asked about it. That is arguably worse than "I don't know," because wrong answers delivered with confidence are harder to catch than obvious gaps.
The standard response is Retrieval-Augmented Generation (RAG): embed your docs, retrieve relevant chunks at query time, stuff them into the context window. RAG works well when your knowledge is lookup-style, but it carries real costs: retrieval latency on every call, context window pressure from retrieved text that may not be relevant, fragility on multi-hop questions that require reasoning across several document sections, and the infrastructure overhead of a vector store, an embeddings pipeline, and a retrieval service.
For knowledge that is relatively fixed (a methodology whitepaper, a product spec, a regulatory framework), fine-tuning is often the better answer, because you pay the training cost once and every subsequent inference is fast, context-clean, and grounded in your material. This article walks through a complete pipeline that takes a 1.5B open-source model and injects proprietary domain knowledge into its weights using QLoRA on Amazon SageMaker. The same question scores 1.2/5 from the base model and 4.2/5 from the fine-tuned model, judged by Claude Opus via Amazon Bedrock.

Industry Applications

Before diving into the technical pipeline, here is where this pattern applies directly:
Industry
Proprietary Knowledge
Example Questions the Fine-Tuned Model Answers
Professional Services / Consulting
Delivery methodologies, engagement frameworks, internal best practices
"What are the five stages of our engagement framework?" / "How do we structure a fixed-price SOW?"
Financial Services
Internal credit policies, risk frameworks, compliance manuals
"What is the maximum LTV ratio for a commercial property loan in category B?"
Healthcare / Pharma
Clinical trial protocols, formulary guidelines, treatment pathways
"What are the contraindications for this drug combination in renal-impaired patients?"
Legal
Contract playbooks, clause libraries, firm-specific precedents
"What standard indemnity language does the firm use for SaaS agreements?"
Manufacturing
Equipment maintenance manuals, quality standards, safety SOPs
"What is the escalation procedure when a Tier 2 defect is detected on Line 4?"
Insurance
Underwriting guidelines, policy wordings, claims adjudication rules
"Under what conditions is business interruption cover excluded in our SME policy?"
Government / Defence
Internal regulations, classified process documentation, procurement rules
"What approval chain is required for a sole-source acquisition above $250,000?"
The common thread is dense, precise, proprietary knowledge that a general model cannot hallucinate its way through. Fine-tuning bakes it into the model's weights so it is available at every inference call without retrieval infrastructure.

What We Built

A five-script pipeline on AWS that:
  1. Prepares training data: converts source documents into structured Q&A pairs in Alpaca format
  1. Augments data via Bedrock: uses Claude Haiku to generate paraphrases, expanding 108 seed examples to 536 without introducing new facts
  1. Trains on SageMaker: launches a QLoRA fine-tuning job on  ml.g5.2xlarge  (A10G 24 GB), trains for 5 epochs (~40 minutes), and saves a merged fp16 model to S3
  1. Deploys two endpoints: one for the base model, one for the fine-tuned model, both on  ml.g4dn.2xlarge  (T4 16 GB)
  1. Evaluates with LLM-as-Judge: sends 20 held-out questions to both endpoints, scores answers 1–5 using Claude Opus via Bedrock
The demo uses the  AI-DLC (AI-Driven Development Lifecycle)  methodology as the knowledge source — a publicly documented AWS ProServe framework, also covered in this  AWS Machine Learning blog post  and the  AI-DLC whitepaper . The base model hallucinated on every question about it, but after fine-tuning it recalls specific facts, named individuals, statistics, and process details with high accuracy.
Results:
METRIC BASE FINE-TUNED DELTA
llm_judge_score_avg 1.200 4.200 +3.000

Architecture

SOURCE DOCUMENTS (whitepaper, blog posts)
│
▼ [1] Prepare data
108 seed Q&A pairs (Alpaca format, JSONL)
│
▼ [2] Augment → Amazon Bedrock Claude Haiku
536 training examples + 20 held-out eval examples
│
▼ [3] Train
Amazon SageMaker Training Job (ml.g5.2xlarge, A10G 24 GB)
├── Base model downloaded from HuggingFace Hub → loaded in 4-bit NF4 (QLoRA)
├── LoRA adapters injected via PEFT (r=16, 7 target modules, ~2M trainable params)
├── SFTTrainer: 5 epochs, response-only loss, cosine LR schedule
└── Two-step merge: save adapter → free 4-bit → reload fp16 → merge_and_unload
│
▼ Merged model saved to S3 (~3 GB, standalone fp16)
│
▼ [4] Deploy
Two SageMaker Endpoints (ml.g4dn.2xlarge, T4 16 GB)
├── qlora-domain-base ← Qwen2.5-1.5B-Instruct, HuggingFace Hub
└── qlora-domain-finetuned ← merged model from S3
│
▼ [5] Evaluate
20 eval questions → both endpoints → Amazon Bedrock Claude Opus (LLM-as-Judge)
│
▼
Score: Base 1.2/5 → Fine-tuned 4.2/5 (+250% improvement)

The AWS + HuggingFace Stack

This pipeline sits at the intersection of two ecosystems, AWS and HuggingFace, and uses each for what it does best.

The AWS Side

Amazon SageMaker is the compute layer. Training jobs spin up a GPU instance, run your script, and shut it down. You pay only for the runtime, with no instance management, no SSH, and no manual Docker setup. The real hidden value is the Deep Learning Containers (DLC): pre-built Docker images with CUDA drivers, PyTorch, and HuggingFace libraries already correctly installed and tested together. Getting BitsAndBytes, PEFT, TRL, and the right CUDA version all working on a fresh GPU instance is notoriously painful, and DLC eliminates that entirely. SageMaker also provides managed real-time endpoints (one  deploy()  call gives you a live HTTPS API with health checks and CloudWatch logging) and native S3 integration where training data flows in and model artifacts flow out transparently.
Amazon Bedrock is the managed model API layer, providing access to Claude and other foundation models via a simple API call with no GPU instances, no model deployment, and per-token pricing. In this pipeline it plays two roles: Claude Haiku generates paraphrases of training examples during augmentation, and Claude Opus judges model answers against reference answers during evaluation. Bedrock uses the same AWS credentials and IAM roles as SageMaker, so there is no separate API key and everything stays within your AWS environment.

The HuggingFace Side

HuggingFace provides the open-source ML libraries that do the actual fine-tuning work. Four libraries are involved, each with a distinct responsibility.
 transformers  is the foundation, providing  AutoModelForCausalLM  (which loads any causal language model from HuggingFace Hub) and  AutoTokenizer  (which converts text to token IDs and back). Every model in the HuggingFace ecosystem loads through this unified API regardless of architecture, which is why swapping  Qwen/Qwen2.5-1.5B-Instruct  for a different model requires changing one line.
 peft  (Parameter-Efficient Fine-Tuning) provides  LoraConfig  to define the adapter structure and  PeftModel  to wrap a base model with LoRA adapters. The  merge_and_unload()  method that folds adapters back into the base weights lives in this library.
 trl  (Transformer Reinforcement Learning) provides  SFTTrainer , the training orchestrator, and  DataCollatorForCompletionOnlyLM , which handles response-only loss masking. TRL is built on top of  transformers  and  peft , wiring them together so you do not have to call  prepare_model_for_kbit_training()  and  get_peft_model()  manually.
 bitsandbytes  provides  BitsAndBytesConfig , the 4-bit NF4 quantisation that makes QLoRA possible, as well as the  paged_adamw_32bit  optimizer that offloads optimizer states to CPU RAM during training to prevent GPU out-of-memory crashes.
HuggingFace Hub is the model registry.  Qwen/Qwen2.5-1.5B-Instruct  downloads from here at the start of the SageMaker training job, and the base model inference endpoint does the same at container startup via the  HF_MODEL_ID  environment variable.

Dependencies

Local machine ( requirements.txt ) — installed to run the orchestration scripts:
sagemaker>=2.220.0 # SDK to submit jobs, deploy endpoints, manage S3
boto3>=1.34.0 # AWS API client (Bedrock calls, SageMaker describe, etc.)
transformers>=4.44.0 # AutoTokenizer for local data validation
datasets>=2.20.0 # Load and process JSONL training data
peft>=0.12.0 # LoraConfig definition
trl>=0.10.0 # SFTConfig definition
matplotlib>=3.8.0 # Evaluation chart generation
SageMaker training instance ( scripts/requirements.txt ) — installed inside the DLC container. The DLC already ships with torch and transformers, so only the fine-tuning-specific libraries are needed:
peft>=0.12.0 # LoRA injection and adapter management
trl>=0.10.0,<0.15.0 # SFTTrainer with pinned upper bound for stability
bitsandbytes>=0.43.0 # NF4 4-bit quantisation (QLoRA)
accelerate>=0.33.0 # Distributed training utilities used by SFTTrainer
The version pin on  trl<0.15.0  matters because TRL's API changed between 0.10 and 0.15, and pinning avoids a breaking change that would only surface when the training job starts on the remote instance, which is a painful place to debug.

Why QLoRA: The Key Technology Choice

Full fine-tuning of a 1.5B model means computing gradients for all 1.5 billion parameters, which requires roughly 21 GB just for optimizer states. That is well beyond the 24 GB available on the training instance.
LoRA (Low-Rank Adaptation) solves the parameter problem by freezing the full weight matrix  W  and injecting two small trainable matrices  A  and  B  alongside each layer:
output = W × input + (B × A) × input × (alpha/r)
↑ frozen ↑ trainable
For a 1024×1024 weight matrix, LoRA with  r=16  trains only  2 × 1024 × 16 = 32,768  parameters instead of  1,048,576 , a 32× reduction.
QLoRA solves the memory problem separately. Even when frozen,  W  must live in GPU memory because every forward pass reads through it, and in fp16 that is ~3 GB for a 1.5B model. QLoRA loads  W  in 4-bit NF4 (NormalFloat4), shrinking it to ~750 MB while keeping the LoRA adapters in fp16. Critically, 4-bit is a loading flag applied at runtime, not a file format. The model on HuggingFace is always stored as fp16, and when you pass  quantization_config=bnb_config , the weights are downloaded as fp16 and compressed to 4-bit as they enter GPU memory:
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4", # optimised for bell-curve weight distributions
bnb_4bit_compute_dtype=torch.bfloat16,
bnb_4bit_use_double_quant=True, # quantise the quantisation constants too
)

model = AutoModelForCausalLM.from_pretrained(
"Qwen/Qwen2.5-1.5B-Instruct",
quantization_config=bnb_config, # apply QLoRA at load time
device_map="auto",
trust_remote_code=True,
)
GPU memory breakdown during training on  ml.g5.2xlarge :
Component
Memory
1.5B model in 4-bit (QLoRA)
~750 MB
LoRA adapter weights (fp16)
~50 MB
Activations
~4 GB
Gradients (LoRA only)
~100 MB
Paged optimizer states
~200 MB
Peak total
~5 GB (fits comfortably in 24 GB)

Step 1: Training Data in Alpaca Format

Every training example follows the Alpaca format:
{
"instruction": "What are the three phases of AI-DLC?",
"input": "",
"output": "The three phases are: (1) Inception — uses Mob Elaboration to convert Intents into Units; (2) Construction — uses Mob Construction to transform Units into tested Deployment Units; (3) Operations — uses AI for deployment, observability, and incident management."
}
The  input  field is deliberately empty, which forces the model to recall facts from its weights rather than extracting them from a provided passage. This is the harder skill, and the more valuable one for knowledge-dense domains.
The prompt template at training and inference time:
### Instruction:
What are the three phases of AI-DLC?

### Response:
The three phases are...

Data Augmentation via Bedrock

108 seed examples are not enough for reliable recall in a 1.5B model because each key fact needs to appear approximately 5–8 times in different phrasings to be encoded reliably into the weights. The augmentation pipeline calls Claude Haiku with a strict prompt to generate those paraphrases:
AUGMENT_PROMPT = """You are a training-data generator for a fine-tuned LLM that must learn AI-DLC
(AI-Driven Development Lifecycle) — a specific software methodology authored by Raja SP at AWS.

Your job: given one Q&A pair about AI-DLC, produce {n} PARAPHRASED variants.

STRICT RULES:
1. Every answer must contain ONLY facts from the original answer — do not add, invent, or embellish any detail
2. Do not introduce any fact not present in the original (no new names, numbers, tools, or concepts)
3. Rephrase the question in a different way (different wording, different angle, but same meaning)
4. Keep all proper nouns exact: Raja SP, APEX, Kiro, Mob Elaboration, Mob Construction,
LexisNexis, FlowSource, CodeSpell, AIForce, Unicorn Gym, ProServe, $2.41 trillion, 60%, 4-6 weeks
5. Keep all numbers exact: percentages, dollar figures, counts, durations
6. Output ONLY a JSON array, no commentary

Original question: {question}
Original answer: {answer}

Return a JSON array of {n} objects, each with "instruction" and "output" string fields."""
The strict rules are non-negotiable. Without them, Claude helpfully "improves" answers by adding context, which then trains the model on invented facts. Haiku is 20× cheaper than Opus and fast enough for this task; the strict prompt compensates for its lower reasoning precision.
Result: 108 seed examples → 536 training examples (5 phrasings per fact on average).

Step 2: SageMaker Training Job

The training launcher runs on your local machine. It does not train anything directly. It:
  1. Uploads training data to S3
  1. Submits a SageMaker training job with a HuggingFace DLC container
  1. Streams logs back to your terminal
estimator = HuggingFace(
entry_point="train.py",
source_dir="scripts/",
role=role,
transformers_version="4.56.2", # pre-built DLC — no CUDA driver setup
pytorch_version="2.8.0",
py_version="py312",
instance_type="ml.g5.2xlarge", # A10G 24 GB
instance_count=1,
hyperparameters={
"model_id": "Qwen/Qwen2.5-1.5B-Instruct",
"epochs": 5,
"lora_r": 16,
"lora_alpha": 32,
"use_qlora": "true",
"merge_weights": "true",
},
)

estimator.fit(inputs={"train": train_s3}, wait=True)
The Deep Learning Container (DLC) is the hidden value here: a pre-built, pre-tested Docker image with CUDA drivers, PyTorch, HuggingFace, and BitsAndBytes already correctly installed. Environment setup that would otherwise take hours is already done.

Step 3: The Training Script

The training script runs inside the SageMaker GPU instance, not on your machine. The complete QLoRA + LoRA + SFTTrainer pattern:
# 1. Load base model in 4-bit (QLoRA)
model = AutoModelForCausalLM.from_pretrained(
args.model_id,
quantization_config=bnb_config, # 4-bit NF4
device_map="auto",
trust_remote_code=True,
)

# 2. LoRA configuration
lora_config = LoraConfig(
r=16,
lora_alpha=32,
lora_dropout=0.05,
bias="none",
task_type=TaskType.CAUSAL_LM,
target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj"],
)

# 3. Response-only loss — don't train on question tokens
collator = DataCollatorForCompletionOnlyLM("### Response:\n", tokenizer=tokenizer)

# 4. Train — SFTTrainer wires up QLoRA + PEFT internally
trainer = SFTTrainer(
model=model,
args=sft_config,
train_dataset=dataset,
peft_config=lora_config, # SFTTrainer handles get_peft_model internally
processing_class=tokenizer,
formatting_func=format_instruction,
data_collator=collator,
)
trainer.train()
 DataCollatorForCompletionOnlyLM  is the detail most tutorials miss. It finds the  "### Response:\n"  marker and masks loss to  -100  for every token before it. Every gradient update is focused on learning the answer, not the question.

The Two-Step Merge

After training, the 4-bit model cannot be deployed directly because inference containers expect a standard HuggingFace model. The merge folds the adapter back into the base weights:
W_merged = W_original + B × A × (alpha / r)
This requires  W_original  in fp16, not 4-bit, because you cannot do clean arithmetic when one operand is 4-bit. The solution:
# Step A: extract adapter to disk (adapters are always fp16)
trainer.model.save_pretrained(adapter_dir)
del trainer, model
gc.collect(); torch.cuda.empty_cache()

# Step B: reload base in FULL fp16 (no BitsAndBytesConfig)
base = AutoModelForCausalLM.from_pretrained(
model_id, torch_dtype=torch.float16, device_map="auto"
)

# Merge: W_new = W_fp16 + B×A — clean fp16 arithmetic
merged = PeftModel.from_pretrained(base, adapter_dir).merge_and_unload()
merged.save_pretrained(model_dir, safe_serialization=True)
The merged model is a standard fp16 HuggingFace model (~3 GB). No PEFT, no adapters, no quantization. The AI-DLC knowledge is baked into the weights permanently.

Step 4: Deploy Two Endpoints

Two identical SageMaker endpoints, one for the base model and one for the fine-tuned model. Having both live simultaneously makes the delta immediately visible.
# Base model — downloads from HuggingFace Hub when the container starts
hub_model = HuggingFaceModel(
env={
"HF_MODEL_ID": "Qwen/Qwen2.5-1.5B-Instruct",
"HF_TASK": "text-generation",
"HF_HUB_ENABLE_HF_TRANSFER": "1",
},
role=role,
transformers_version="4.48.0", # inference DLC — separate registry from training
pytorch_version="2.3.0",
py_version="py311",
sagemaker_session=session,
)
hub_model.deploy(
initial_instance_count=1,
instance_type="ml.g4dn.2xlarge", # T4 16 GB — sufficient for a 3 GB fp16 model
endpoint_name="qlora-domain-base",
)

# Fine-tuned model — loads the merged fp16 model from S3
ft_model = HuggingFaceModel(
model_data=model_s3_uri, # s3://bucket/.../model.tar.gz from training job
role=role,
transformers_version="4.48.0",
pytorch_version="2.3.0",
py_version="py311",
env={"HF_TASK": "text-generation"},
sagemaker_session=session,
)
ft_model.deploy(
initial_instance_count=1,
instance_type="ml.g4dn.2xlarge",
endpoint_name="qlora-domain-finetuned",
)
Note the DLC version difference: training uses  transformers 4.56.2  (latest training image) and inference uses  4.48.0 . These come from separate image registries, and the newest training version is not always available as an inference image.

Step 5: LLM-as-Judge Evaluation

Standard metrics like BLEU and ROUGE count n-gram overlap and systematically underrate correct paraphrases. A model that says "Bolts replace Sprints and run in hours or days" instead of "A Bolt is AI-DLC's replacement for a Scrum Sprint, measured in hours or days" is correct, but BLEU disagrees. LLM-as-Judge asks Claude Opus to evaluate whether the answer is factually correct, in the same way a human domain expert would.
JUDGE_PROMPT = """Score the RESPONSE 1–5 against the REFERENCE.
5 - Fully correct, all key facts present
4 - Mostly correct, minor omissions
3 - Partially correct, misses key details
2 - Mostly wrong, one relevant element
1 - Completely wrong or hallucinated

Return ONLY JSON: {{"score": <1-5>, "reason": "<one sentence>"}}

QUESTION: {question}
REFERENCE: {reference}
RESPONSE: {response}"""

response = bedrock.invoke_model(
modelId="us.anthropic.claude-opus-4-6-v1",
body=json.dumps({
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 200,
"temperature": 0, # deterministic — same answer, same score every time
"messages": [{"role": "user", "content": prompt}],
}),
)
 temperature=0  for the judge ensures reproducible scores rather than creative interpretation.
Why Opus for judging, Haiku for augmentation: The judge score is your metric. Haiku might let a partially-wrong answer pass, while Opus reasons carefully about whether specific facts (the 60% figure, the specific person's name, the exact dollar amount) are present. For 40 total judge calls, the cost difference is negligible.

Results

METRIC BASE FINE-TUNED DELTA
llm_judge_score_avg 1.200 4.200 +3.000 (+250%)
Sample outputs on the same question:
Question: "What is APEX and what did it build?"
Base model (1/5):
APEX is a cloud computing platform developed by Salesforce that allows developers to build custom applications integrated with Salesforce CRM. It uses a Java-like syntax and runs on Salesforce's servers...
Fine-tuned model (5/5):
APEX stands for Agentic AI ProServe Experiences. It is the pathfinder team within AWS Professional Services that built the ProServe Delivery Agent — a multi-agent system implementing AI-DLC across the complete delivery lifecycle.
The base model confidently retrieved the wrong APEX entirely (Salesforce's programming language). The fine-tuned model correctly identified the internal AWS team and its output.

Evaluation Deep Dive

The LLM-as-Judge Scoring Rubric

Every answer is scored 1–5 against a reference:
Score
Label
What It Means
5
Fully correct
All key facts present, no significant omissions
4
Mostly correct
Minor omissions or slight imprecision, core content right
3
Partially correct
Gets the general concept, misses specific details
2
Mostly wrong
One or two relevant elements, rest is incorrect or hallucinated
1
Completely wrong
Hallucinated, unrelated, or factually incorrect throughout
The rubric is deliberately anchored to facts, not style. A short, direct answer scores the same as a verbose one if it contains the same facts. An eloquent answer with wrong facts scores 1.

Evaluation Dataset Design

The 20 evaluation questions are a held-out set, never seen during training in any form. They cover three categories of difficulty:
Category
Description
Example
Direct recall
Single-fact lookup
"Who created AI-DLC?"
Enumeration
Recall a complete list
"What are the 10 key principles of AI-DLC?"
Causal / relational
Why or how, requires connecting multiple facts
"Why can't you just add AI on top of Agile?"
Enumeration questions are the hardest for small models because they require recalling all N items, not just recognising any one. A model that recalls 7 of 10 principles scores a 3 or 4, not a 5.

Training Signal: Reading the Loss Curve

During training, the loss curve is your primary health indicator. Loss measures how wrong the model's predictions are, and lower is better.
{'loss': 2.31, 'epoch': 0.10} ← random guessing at the start
{'loss': 1.42, 'epoch': 0.50} ← picking up format and structure
{'loss': 0.84, 'epoch': 1.00} ← learning common facts
{'loss': 0.52, 'epoch': 2.00} ← most facts encoded
{'loss': 0.35, 'epoch': 3.00} ← solidifying knowledge
{'loss': 0.21, 'epoch': 5.00} ← well trained
Warning signs:
  • Loss plateaus above 1.0 after epoch 1 → data quality issue or learning rate too low
  • Loss drops to near zero then eval score doesn't improve → overfitting (reduce epochs or add more training variety)
  • Loss spikes erratically ( grad_norm  > 50) → training instability, reduce learning rate
The  grad_norm  metric tells you the size of each weight update. A healthy value is 0.5–5.0. Spikes above 50 indicate the model is being pushed too hard in one direction, which is a sign of bad data or a learning rate that is too high.

Per-Question Score Distribution

Base model:
Score 1 (completely wrong): 16 / 20 questions (80%)
Score 2 (mostly wrong): 3 / 20 questions (15%)
Score 3 (partially correct): 1 / 20 questions (5%)
Score 4–5 (correct): 0 / 20 questions (0%)

Average: 1.20 / 5
Fine-tuned model:
Score 5 (fully correct): 8 / 20 questions (40%)
Score 4 (mostly correct): 7 / 20 questions (35%)
Score 3 (partially correct): 4 / 20 questions (20%)
Score 1–2 (wrong): 1 / 20 questions (5%)

Average: 4.20 / 5
The questions scoring 3 or below share a pattern: they require recalling complete enumerated lists (all 10 principles, all 5 practices, all 3 phases in full detail). A 1.5B model trained on 536 examples reliably recalls individual facts but sometimes omits items from long lists. The fix is targeted: add more training examples that specifically drill the full lists.

Side-by-Side: Base vs Fine-Tuned

Q: "What billing model did ProServe adopt and why?"
Base model (1/5):
ProServe typically uses a time-and-materials billing model, where customers are charged based on the number of hours consultants work and the materials used in the project...
Fine-tuned model (4/5):
ProServe moved to fixed-price engagements tied to production-deployed business outcomes. This aligns incentives with customer success and is viable because AI-native delivery makes timelines predictable.
The base model described the old model as if it were current. The fine-tuned model correctly identified the shift to fixed-price and the reason behind it.
Q: "What are the five core practices of AI-native delivery?"
Base model (2/5):
The five core practices of AI-native delivery include: continuous integration and deployment, automated testing, infrastructure as code, monitoring and observability, and security by design...
Fine-tuned model (4/5):
  1. Slow down to speed up. 2. Invest heavily in agent context. 3. Feed agents instead of babysitting them. 4. Use specs as the source of truth. 5. Shift testing left.
The base model generated a plausible-sounding generic DevOps list. The fine-tuned model recalled the actual proprietary list, including the specific phrasing "slow down to speed up" and "feed agents instead of babysitting them."
The fine-tuned model moved from 80% completely wrong to 75% scoring 4 or 5, on a 1.5B parameter model trained on 536 examples in under an hour.

Adapting This to Your Domain

Step 1: Swap the knowledge source

Write seed Q&A pairs in Alpaca format for your domain. Aim for:
Goal
Seed examples
Proof of concept
50–80 seeds → augment to ~300
Reliable demo
100–150 seeds → augment to ~500
Production quality
200+ seeds → augment to ~1000

Step 2: Update  config.py 

BASE_MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct" # or 3B, 7B — same pipeline
INSTANCE_TYPE = "ml.g5.2xlarge" # sufficient for up to 7B with QLoRA

Step 3: Run the pipeline

The pipeline is five sequential stages. Each stage is independent, so you can re-run any stage without repeating earlier ones:
  1. Prepare data: parse source documents, write seed Q&A pairs in Alpaca format, run augmentation via Bedrock Claude Haiku
  1. Train: upload data to S3, submit SageMaker training job, stream logs back to your terminal
  1. Deploy: deploy two endpoints (base model from HuggingFace Hub, fine-tuned model from the S3 artifact)
  1. Evaluate: send all eval questions to both endpoints, judge answers via Bedrock Claude Opus, write results JSON and chart
  1. Spot check: query the fine-tuned endpoint question by question, show answer and judge score for each
  1. Cleanup: delete both endpoints to stop billing when done

Models that work with zero code changes

Just change  BASE_MODEL_ID  in  config.py :
Model
Size
Notes
 Qwen/Qwen2.5-1.5B-Instruct 
1.5B
Proven — used in this article
 Qwen/Qwen2.5-3B-Instruct 
3B
Best next step — same instances
 Qwen/Qwen2.5-7B-Instruct 
7B
Strong — fits on  ml.g5.2xlarge 
 google/gemma-2-2b-it 
2B
Good alternative
 microsoft/Phi-3.5-mini-instruct 
3.8B
Excellent for its size
 mistralai/Mistral-7B-Instruct-v0.3 
7B
Strong instruction following

When Fine-Tuning Beats RAG

This pipeline is the right choice when:
  • Knowledge is fixed: a methodology, regulatory framework, or product spec that does not change daily
  • Precision matters: the model needs to recall specific names, numbers, and procedures, not just approximate the topic
  • Latency is critical: no retrieval step, no vector store call, no context stuffing
  • Multi-hop reasoning is needed: the model can reason across facts it has internalised rather than matching query to retrieved chunks
  • Deployment simplicity matters: one model endpoint, no retrieval infrastructure
RAG is better when:
  • Knowledge changes frequently (daily or weekly updates)
  • The knowledge corpus is very large (millions of documents)
  • You need to cite specific source passages
  • You cannot afford training compute
For many enterprise use cases, particularly professional services, internal tooling, and regulated industries, the knowledge is stable enough that fine-tuning's one-time cost is worth the inference-time simplicity.

Lessons Learned

These are the non-obvious things that only become clear after running the pipeline end to end.
1. Data quantity matters more than model size for factual recall
108 seed examples was not enough. The model partially learned the content but couldn't reliably surface specific facts. Expanding to 536 examples with paraphrasing pushed the score from 2.15/5 to 4.2/5. Adding more data gave far larger gains than any hyperparameter change. If your score is low, fix the data before touching anything else.
2. LLM-as-Judge is simpler and more meaningful than BERTScore or ROUGE for factual recall tasks
ROUGE and BLEU count n-gram overlap and penalise correct paraphrases. BERTScore is semantically smarter but requires downloading a large model locally and adds infrastructure. Claude Opus via Bedrock scores answers the way a domain expert would: does it contain the right facts? For proprietary knowledge evaluation, this is the right tool. No local model download, no embedding pipeline, no threshold tuning.
3. The two-step LoRA merge is non-obvious but necessary
The merge cannot happen on the 4-bit quantised model because  W_original + B×A  requires matching precision, and 4-bit arithmetic produces garbage. The correct sequence is: save adapter to disk, delete the 4-bit model from GPU memory, reload the base in full fp16, then merge. The deployed artifact has no PEFT dependency at runtime and is a standard HuggingFace model that any inference container can serve.
4. Exact match stays 0.0 even when the model is correct
This is not a failure. Generative models paraphrase, and a model answering "AI-DLC was authored by Raja SP at AWS" instead of the exact reference wording is correct. Exact match is the wrong metric for any generative task. Do not use it to measure recall quality.
5. Augmentation prompts must be strict: unconstrained augmentation poisons your training data
Without explicit rules, Claude helpfully fills in details: changing "60%" to "significantly", inventing new proper nouns, adding plausible-sounding context that is not in the source. Every invented fact the augmentation model introduces gets learned by the fine-tuned model as ground truth. The fix is a strict prompt that explicitly names every proper noun and number that must be preserved verbatim, and forbids adding any fact not in the original.

What's Next

Immediate improvements:
  1. Identify weak questions: query both endpoints on each eval question individually, find questions scoring 1–2, add 8–10 focused training examples for each failing fact
  1. Increase to 7 epochs: the dataset size supports it and loss was still decreasing at epoch 5
  1. Upgrade to 3B: same pipeline, same instances, likely pushes score to 4.3–4.5
Production path:
  1. Versioning: save model artifacts with a timestamp, enable rollback
  1. Automated retraining: trigger the pipeline when source documents update via an S3 event or EventBridge rule
  1. Confidence filtering: flag outputs containing hedging language ("I think", "possibly", "I'm not sure") for human review
  1. Expanding evals: more eval questions, more question types (fill-in-the-blank, true/false, multi-hop), coverage across all documented facts

Key Takeaways

  1. Data quantity matters more than model size: 108 examples was not enough. 536 with augmentation hit 4.2/5 on a 1.5B model. Fix data before touching hyperparameters or upgrading model size.
  1. The merge must happen in fp16: QLoRA is a training-time loading flag, not a file format. The model on HuggingFace is always fp16. The merge reloads the base in fp16 because  W_original + B×A  requires matching precision. The deployed model has no PEFT dependency.
  1. LLM-as-Judge scales to any domain: Claude Opus scores answers the way a domain expert would, without needing ground-truth labels or metric thresholds. Use  temperature=0  for reproducible scores.
  1. Exact match is not a useful metric for generative models: paraphrasing is correct behaviour, not failure. It will always be 0.0. Ignore it.
  1. Strict augmentation prompts are not optional: unconstrained augmentation introduces hallucinations into training data. Explicitly list every proper noun and number that must be preserved. The model learns whatever you teach it.
  1. This pipeline is domain-agnostic: swap the source documents, write new seed Q&A pairs, change one model ID in config. The SageMaker infrastructure, QLoRA training, merge logic, and Bedrock evaluation are identical for any knowledge domain: runbooks, compliance docs, product specs, internal methodologies.
Stack used (all current as of 2026): QLoRA · PEFT · TRL SFTTrainer · BitsAndBytes NF4 double quantization · paged_adamw_32bit · SageMaker HuggingFace DLC · safetensors · Amazon Bedrock (Claude Haiku 4.5 for augmentation, Claude Opus 4.6 for evaluation)
Sources
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article