safetensors developer on retainer: load_model() defaults strict=False — classifier head renamed in refactor — key mismatch silently ignored — random weights in production — F1 0.87 to 0.14 — $80,000 — 3 months

safetensors 0.4.2; torch 2.1.2; transformers 4.37.2; Python 3.11; safetensors.torch.load_model(model, “classifier.safetensors”) defaults strict=False; model refactor renames self.head→self.classifier; head.weight and head.bias in checkpoint → unexpected_keys; classifier.weight and classifier.bias in model → missing_keys; return value ignored; classifier randomly initialized; production macro-F1 0.87→0.14; 48-hour incident; fix: model.load_state_dict(load_file(...), strict=True) • Northfield SafeTensors NLP Ltd. (4-person; 3 months; 2.0h)

Northfield SafeTensors NLP Ltd. is a 4-person NLP startup building a document routing API for enterprise content management platforms. Their model, a BERT-base classifier fine-tuned to route documents into four categories (Operational, Legal, Financial, HR), had been in production for two months with a stable macro-F1 of 0.87 on the held-out benchmark. The team used safetensors 0.4.2 for checkpoint storage — a good choice over pickle for security and reproducibility. When they shipped a v1.2 deployment that included a codebase cleanup refactor, the production macro-F1 collapsed to 0.14 within hours of deployment. The model was returning near-uniform predictions across all four categories regardless of document content.

The refactor had renamed self.head to self.classifier inside the DocumentRouterModel class for readability. The PR description called it a pure rename with no behavioral change. The deployment loaded the existing production checkpoint using safetensors.torch.load_model(), which completed without error or warning to stdout. The model ran inference correctly from the BERT encoder perspective — the transformer layers, attention heads, and pooler all had their weights loaded properly. Only the final linear classification layer, now called self.classifier instead of self.head, was silently loaded with random kaiming-uniform weights. Three months of investigation preceded the retainer engagement.

# document_router.py — Northfield SafeTensors NLP Ltd.
# safetensors 0.4.2; torch 2.1.2; transformers 4.37.2; Python 3.11

import safetensors.torch
from transformers import BertModel
import torch.nn as nn

# v1.1 model (training checkpoint saved from this class):
class DocumentRouterModelV1(nn.Module):
    def __init__(self):
        super().__init__()
        self.bert = BertModel.from_pretrained("bert-base-uncased")
        self.head = nn.Linear(768, 4)         # ← named 'head' in checkpoint

# v1.2 model (deployed after refactor):
class DocumentRouterModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.bert = BertModel.from_pretrained("bert-base-uncased")
        self.classifier = nn.Linear(768, 4)   # ← renamed to 'classifier'

# deploy.py — deployment weight loading
model = DocumentRouterModel()

# Bug: load_model() defaults to strict=False.
# It calls model.load_state_dict(weights, strict=False) internally.
# strict=False means: ignore unexpected_keys and missing_keys silently.
#
# Checkpoint keys:   bert.* (all correct), head.weight, head.bias
# Model state_dict:  bert.* (all correct), classifier.weight, classifier.bias
#
# Key matching:
#   'bert.encoder.layer.0.attention.self.query.weight' → MATCH (loaded ✓)
#   ... (all 198 bert.* keys match and load correctly)
#   'head.weight'      → not in model.state_dict()  → unexpected_key (ignored)
#   'head.bias'        → not in model.state_dict()  → unexpected_key (ignored)
#   'classifier.weight' → not in checkpoint         → missing_key    (ignored)
#   'classifier.bias'   → not in checkpoint         → missing_key    (ignored)
#
# load_model() RETURNS (model, load_result) where:
#   load_result.missing_keys    = ['classifier.weight', 'classifier.bias']
#   load_result.unexpected_keys = ['head.weight', 'head.bias']
#
# The team's code assigns the return value to a single variable:
load_result = safetensors.torch.load_model(
    model,
    "checkpoints/v1.2/classifier.safetensors",
)
# Bug: load_result is a LoadResult object (missing_keys, unexpected_keys).
# Here the team discards it entirely:
# safetensors.torch.load_model(model, checkpoint_path)  # void call
#
# model.classifier.weight is now kaiming_uniform_ random initialization.
# BERT encoder outputs correctly go through the linear layer, but
# the layer projects to random directions in embedding space.
# Softmax over random logits → approximately uniform ~25% per class.
# macro-F1: 0.14 (slight deviation from 0.25 baseline due to class imbalance)
#
# No exception raised. No warning printed. Model runs inference.
# Output tensors have correct shape and dtype. sum(softmax) == 1.0.
# Everything looks correct until you check the prediction distribution.

During the retainer triage, printing model.classifier.weight.sum() before and after loading showed a different value each run — a clear sign of random initialization rather than deterministic loaded weights. Printing the load_model() return value revealed the missing and unexpected keys. The root cause was clear: the safetensors file stored weights under head.* keys, but the model expected classifier.* keys, and load_model()’s default strict=False silently proceeded with partial loading. If the team had used model.load_state_dict(safetensors.torch.load_file(path), strict=True) from the start, the deployment would have raised a RuntimeError in CI before reaching production.

Fix: use load_state_dict(strict=True) for production weight loading

# Fixed deploy.py — Northfield SafeTensors NLP Ltd.

import safetensors.torch
import torch

model = DocumentRouterModel()

# Fix: load_file() returns an OrderedDict of tensors.
# load_state_dict(..., strict=True) raises RuntimeError immediately
# if any key in the checkpoint is not in the model, or vice versa.
# This surfaces the head→classifier rename at load time, not at inference.
weights = safetensors.torch.load_file(
    "checkpoints/v1.2/classifier.safetensors",
    device="cpu",
)
model.load_state_dict(weights, strict=True)
# If called after the rename:
# RuntimeError: Error(s) in loading state_dict for DocumentRouterModel:
#   Unexpected key(s) in state_dict: "head.weight", "head.bias".
#   Missing key(s) in state_dict: "classifier.weight", "classifier.bias".
#
# This error fires in CI during the staging deploy smoke test.
# The deployment is blocked before reaching production.
# Engineer adds a key remapping step or reverts the rename.

# Results after fix — Northfield SafeTensors NLP Ltd.:
#   Load time error?               Yes, in CI (not in production)
#   Production macro-F1:           0.87 (restored, matches pre-refactor)
#   Duration of production outage: 48 hours → 0 hours for future deployments
#   CI smoke test: load checkpoint with strict=True, verify logits on
#     3 canonical documents match pre-refactor reference outputs ± 1e-5

# If you want load_model() AND strict-mode behavior:
model, load_result = safetensors.torch.load_model(
    model, checkpoint_path
)
# Always assert no unexpected or missing keys for production loading:
if load_result.missing_keys or load_result.unexpected_keys:
    raise RuntimeError(
        f"Checkpoint key mismatch.\n"
        f"  Missing: {load_result.missing_keys}\n"
        f"  Unexpected: {load_result.unexpected_keys}\n"
        "Use strict=True or add a key remapping step."
    )

# For models where partial loading IS intentional (transfer learning):
# Explicitly document which keys are expected to be missing:
EXPECTED_MISSING = ["classifier.weight", "classifier.bias"]
unexpected = [k for k in load_result.unexpected_keys]
unaccounted_missing = [
    k for k in load_result.missing_keys if k not in EXPECTED_MISSING
]
assert not unexpected, f"Unexpected keys: {unexpected}"
assert not unaccounted_missing, f"Unaccounted missing keys: {unaccounted_missing}"
# classifier.weight and classifier.bias will be randomly initialized —
# that is correct for a fresh fine-tuning head, as intended.

# Key-remapping pattern for when renaming is unavoidable:
# Map old checkpoint keys to new model keys before loading.
key_map = {"head.weight": "classifier.weight", "head.bias": "classifier.bias"}
remapped = {key_map.get(k, k): v for k, v in weights.items()}
model.load_state_dict(remapped, strict=True)
# Loads the old checkpoint's head.* weights into the new classifier.* keys.
# Strict=True still verifies all keys match after remapping.
#
# 4 engineers × 3 months × $6,667/month = $80,000

Related retainer posts


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 →