torchtune developer on retainer: load_state_dict(strict=False) silently ignores all 128 LoRA adapter keys — torchtune key naming incompatible with HuggingFace LlamaForCausalLM — inference runs on untrained base model — $80,000 — 3 months
torchtune 0.1.0; torch 2.2.0; Python 3.11; CUDA 12.2; 2× A100 40GB; LoRA fine-tuning Llama-2-7B-hf; save_checkpoint() adapter keys layers.0.attn.q_proj.lora_a.weight; HuggingFace model keys model.layers.0.self_attn.q_proj.weight; zero overlap; load_state_dict(strict=False) silently ignores all 128 LoRA keys; base model unchanged; 10 training epochs wasted; fix: check incompatible_keys.unexpected_keys; use model.merge_lora_params() • Westfield TorchTune Training Ltd. (3-person; 3 months; 1.5h)
Westfield TorchTune Training Ltd. is a 3-person customer support chatbot startup that fine-tuned Llama-2-7B-hf on 240,000 customer support dialogue turns using torchtune’s lora_finetune_single_device recipe. The fine-tuning configuration used lora_rank=8, lora_alpha=16, and LoRA applied to q_proj and v_proj in all 32 transformer layers. Each training epoch took 8 GPU-hours on 2× A100 40GB; they ran 10 epochs over 2 weeks. At the end of each epoch, torchtune’s save_checkpoint() wrote adapter_model.bin (128 LoRA delta weight tensors) and adapter_config.json to ./output/epoch_N/. For inference, the team loaded a fresh AutoModelForCausalLM.from_pretrained(“meta-llama/Llama-2-7b-hf”) model and called load_state_dict(torch.load(“adapter_model.bin”), strict=False). The function returned successfully. The model produced responses. Customer support quality was poor after epoch 1 — not much better than a plain Llama-2-7B, but the team attributed this to the model needing more training. After epoch 10, quality was still poor. After 2 weeks, they concluded the data needed to be cleaned and began a data audit.
The root cause: torchtune 0.1.0 uses a key naming convention entirely different from HuggingFace’s. torchtune’s LoRA model stores adapter weights at keys like layers.0.attn.q_proj.lora_a.weight. HuggingFace’s LlamaForCausalLM stores base weights at keys like model.layers.0.self_attn.q_proj.weight. The two namespaces have zero intersection. When load_state_dict(strict=False) is called with the torchtune adapter checkpoint on the HuggingFace model, it finds 128 “unexpected” keys (all torchtune LoRA keys — the HuggingFace model has no attribute path matching them) and 291 “missing” keys (all HuggingFace model weights — not in the adapter-only checkpoint). With strict=False, both categories are silently ignored. No error. No warning. The return value — an IncompatibleKeys named tuple with unexpected_keys and missing_keys — is not inspected. The HuggingFace model is loaded with zero LoRA delta applied, indistinguishable from a fresh AutoModelForCausalLM.from_pretrained(“meta-llama/Llama-2-7b-hf”) call.
# inference_deploy.py — Westfield TorchTune Training Ltd.
# torchtune 0.1.0; torch 2.2.0; Python 3.11
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
base_model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-2-7b-hf",
torch_dtype=torch.float16,
device_map="auto",
)
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
# Load torchtune LoRA checkpoint (epoch 10 — 80 GPU-hours of training)
adapter_weights = torch.load("./output/epoch_10/adapter_model.bin", map_location="cpu")
# adapter_weights key sample (torchtune 0.1.0 naming convention):
# "layers.0.attn.q_proj.lora_a.weight" shape: [8, 4096] (rank=8, in_features=4096)
# "layers.0.attn.q_proj.lora_b.weight" shape: [4096, 8] (out_features=4096, rank=8)
# "layers.0.attn.v_proj.lora_a.weight" shape: [8, 4096]
# "layers.0.attn.v_proj.lora_b.weight" shape: [1024, 8] (GQA: v_proj out=1024)
# ...
# 32 layers × 2 modules (q_proj, v_proj) × 2 matrices (lora_a, lora_b) = 128 keys
# HuggingFace LlamaForCausalLM key sample:
# "model.layers.0.self_attn.q_proj.weight" shape: [4096, 4096]
# "model.layers.0.self_attn.v_proj.weight" shape: [1024, 4096]
# "model.embed_tokens.weight" shape: [32000, 4096]
# "lm_head.weight" shape: [32000, 4096]
# ... (291 keys total)
# Bug: zero namespace overlap between torchtune keys ("layers.X.attn...")
# and HuggingFace keys ("model.layers.X.self_attn...")
incompatible_keys = base_model.load_state_dict(adapter_weights, strict=False)
# Returns: IncompatibleKeys(
# missing_keys=[
# "model.layers.0.self_attn.q_proj.weight", # all 291 HuggingFace weights
# "model.layers.0.self_attn.v_proj.weight", # not found in adapter_weights
# ...
# ],
# unexpected_keys=[
# "layers.0.attn.q_proj.lora_a.weight", # all 128 torchtune LoRA keys
# "layers.0.attn.q_proj.lora_b.weight", # not matched in base_model
# ...
# ]
# )
#
# Team never inspects incompatible_keys — just calls load_state_dict() and continues
# strict=False: ALL unexpected_keys silently dropped, ALL missing_keys silently allowed
#
# print(len(incompatible_keys.unexpected_keys)) → 128 (all LoRA keys discarded)
# print(len(incompatible_keys.missing_keys)) → 291 (all base weights missing from adapter)
#
# base_model.state_dict() == AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
# Zero LoRA delta applied. 80 GPU-hours of fine-tuning never deployed.
During the retainer triage, one diagnostic revealed the problem immediately: printing incompatible_keys.unexpected_keys[:3] showed [“layers.0.attn.q_proj.lora_a.weight”, “layers.0.attn.q_proj.lora_b.weight”, “layers.0.attn.v_proj.lora_a.weight”] — torchtune keys that the HuggingFace model had no path for. A second diagnostic confirmed the base model was unchanged: extracting the first token prediction distribution over the vocabulary before and after load_state_dict() showed bit-for-bit identical logits. The HuggingFace model never received the LoRA delta. The fix requires either converting the torchtune checkpoint to HuggingFace format using torchtune’s convert_weights.py utility, or switching to the PEFT library which uses HuggingFace-compatible key naming throughout.
Fix: check incompatible_keys and use the right loader
# Fixed inference — Westfield TorchTune Training Ltd.
# Option 1: Convert torchtune checkpoint → HuggingFace format
# Step 1: During training, merge LoRA weights into base before saving
# (torchtune 0.1.0: add to custom training script after final epoch)
model.merge_lora_params() # W_merged = W_base + W_B @ W_A * (alpha / rank)
# Save merged model using torchtune's convert_weights utility:
# python scripts/convert_weights.py \
# --checkpoint-type LLAMA2 \
# --input-path ./output/epoch_10/ \
# --output-path ./output/hf/ \
# --model-size 7B
# Output: ./output/hf/ (HuggingFace-format config.json + model.safetensors)
# Step 2: Load merged model normally
merged_model = AutoModelForCausalLM.from_pretrained(
"./output/hf/",
torch_dtype=torch.float16,
device_map="auto",
)
# Loads cleanly — HuggingFace keys throughout
# Option 2: Switch to PEFT (HuggingFace-compatible LoRA from the start)
from peft import PeftModel, get_peft_model, LoraConfig
lora_config = LoraConfig(
r=8, lora_alpha=16,
target_modules=["q_proj", "v_proj"],
task_type="CAUSAL_LM",
)
peft_model = get_peft_model(base_model, lora_config)
# PEFT keys: "base_model.model.model.layers.0.self_attn.q_proj.lora_A.weight"
# PEFT's save_pretrained()/from_pretrained() handle key mapping consistently
# Option 3: Universal guard — add to every checkpoint load in production
def safe_load(model, weights_path, strict=False):
weights = torch.load(weights_path, map_location="cpu")
incompatible = model.load_state_dict(weights, strict=strict)
assert len(incompatible.unexpected_keys) == 0, (
f"load_state_dict: {len(incompatible.unexpected_keys)} unexpected keys — "
f"first 3: {incompatible.unexpected_keys[:3]}\n"
"Key naming mismatch between checkpoint and model architecture."
)
assert len(incompatible.missing_keys) == 0, (
f"load_state_dict: {len(incompatible.missing_keys)} missing keys — "
f"first 3: {incompatible.missing_keys[:3]}\n"
"Checkpoint does not contain all model weights."
)
return model
# Results after fix:
# Customer support quality: 4.1/5 (vs 3.1/5 base Llama-2-7B-hf)
# incompatible_keys.unexpected_keys: [] (0 keys)
# incompatible_keys.missing_keys: [] (0 keys)
# Load assertion: passes
#
# 3 engineers × 3 months × $8,889/month = $80,000
Related retainer posts
- safetensors developer on retainer — safetensors;
load_model()defaultsstrict=False; classifier head renamedself.head→self.classifier;head.weight→unexpected_keys; random classifier weights in production; F1 0.87→0.14; 2.0h - accelerate developer on retainer — accelerate;
gather()returns 1,024 entries for 1,003-sample dataset; 21 duplicate padding samples inflate macro-F1 0.763 to 0.771; shipped below quality target; fix:gather_for_metrics(); 1.5h - flash-attn developer on retainer — flash-attn;
padding_side=“right”(default) with FlashAttention-2; shorter sequences attend to padding-token KV entries in batch generation; quality 2.8/5 vs 4.4/5; 3 weeks; 1.5h
Track retainer hours without a client portal
HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.
See pricing →