Deep Learning · Production
Saving, Loading and Deploying Deep Models
Training produces useful parameters; deployment turns them into a repeatable decision inside a real system. We will distinguish training checkpoints from inference artifacts, save and load PyTorch state safely, prove predictions survive reload/export, define an API contract, calculate latency and model size trade-offs, plan canary rollout and rollback, and monitor both service health and delayed model quality.
A Weight File Is Not the Complete Model
Imagine a crack detector whose file loads without error but receives RGB channels in the wrong order. The learned weights are intact, yet predictions are wrong. Or imagine logits [2.1,0.4] evaluated as [normal, crack] but served with reversed labels. Serialization succeeded; deployment failed.
A reliable artifact records the model architecture/configuration, learned parameters and buffers, exact preprocessing/tokenizer, output interpretation, relevant dependency versions and validated metrics. Give the bundle an immutable version or content hash.
A deployable model is a versioned bundle—not one weight file
Architecture
layers, shapes, forward logic
Learned state
weights + buffers
Preprocessing
resize, normalize, tokenizer
Output contract
class order, thresholds, units
Metadata
versions, metrics, intended use
prediction
Checkpoint and Inference Artifact Serve Different Purposes
| Contents | Resume-training checkpoint | Inference artifact |
|---|---|---|
| Model parameters and buffers | Required | Required |
| Architecture/configuration | Required to rebuild | Required or captured by export |
| Optimizer state | Required for faithful resume | Not needed |
| Scheduler/scaler state | Required if used | Not needed |
| Epoch/step and random state | Useful/required for reproducibility | Build metadata only |
| Pre/postprocessing + labels | Strongly recommended | Required |
| Validation decision/metrics | Required provenance | Required provenance |
Optimizer state includes momentum/adaptive statistics. Loading only model weights can resume from similar predictions but not from the same training dynamics.
Save State Dictionaries and Rebuild Deliberately
In PyTorch, a state dictionary maps names to tensors for parameters and persistent buffers. Saving it decouples learned state from Python object layout better than pickling an entire model, but the architecture code/configuration is still needed to load it.
import json
import torch
# Save learned state and a separate, human-readable contract.
torch.save(model.state_dict(), "crack_detector_v7.pt")
with open("crack_detector_v7.json", "w", encoding="utf-8") as file:
json.dump({
"architecture": "SmallCNN-v3",
"classes": ["normal", "crack"],
"input_shape": [3, 224, 224],
"normalization": {"mean": mean, "std": std},
"decision_threshold": 0.72,
}, file, indent=2)
# Recreate the exact architecture, then load tensors strictly.
loaded = SmallCNN(num_classes=2)
state = torch.load(
"crack_detector_v7.pt",
map_location="cpu",
weights_only=True,
)
loaded.load_state_dict(state, strict=True)
loaded.eval() # disables dropout; BatchNorm uses stored statistics
with torch.inference_mode():
logits = loaded(preprocessed_batch)
probabilities = logits.softmax(dim=1)Which values come from the system?
Two classes and their order come from the labelled task. Shape [3,224,224] comes from the model contract: RGB channels and chosen spatial size. Mean/std come from validated preprocessing. Threshold 0.72 is a developer-selected operating point from validation trade-offs—not a weight learned automatically.
What loading and inference do
strict=True rejects missing or unexpected state names. map_location selects the loading device. eval() changes dropout and BatchNorm behavior; inference_mode avoids gradient storage. The model produces logits and softmax normalizes across the two class positions.
Serialized models are input files, so trust matters
Do not load arbitrary untrusted checkpoints. Use safer weight-only loading where supported, verify artifact provenance/checksums, restrict access, scan dependencies and test in an isolated environment.
Prove That Saving and Export Did Not Change Predictions
A successful file write or export only proves that an artifact exists. Build a small golden set containing normal, boundary and awkward inputs; store expected preprocessing outputs and model outputs within tolerances.
Numerical equivalence example
Use illustrative outputs from the same input: native logits [2.0000,0.5000] and exported-runtime logits [1.9998,0.5001]. In a real test both vectors are measured, while tolerance 0.001 is chosen in advance from acceptable numerical and decision risk.
Subtract pairwise
|2.0000−1.9998|=0.0002
|0.5000−0.5001|=0.0001
Take worst case
max(0.0002,0.0001)
=0.0002
Compare with rule
0.0002≤0.001
pass
Interpretation: this input passes the chosen numerical tolerance and keeps the same predicted class. Repeat across representative shapes/batches and evaluate end metrics; one vector is not sufficient validation.
Choose a Runtime for the Target Environment
| Artifact/runtime path | Best fit | Advantage | Trade-off to test |
|---|---|---|---|
| Framework state dictionary | Training resume and native-framework inference | Flexible and easy to inspect | Requires model code and compatible framework |
| Framework export | Stable graph/artifact within the framework ecosystem | Can capture executable computation | Dynamic control flow and operator support need testing |
| ONNX | Cross-platform/runtime inference | Multiple languages and hardware providers | Export support and numerical parity vary by operator |
| Device-specific runtime | Mobile, browser or accelerator deployment | Potential size/latency/energy gains | Conversion, quantization and device QA add work |
| Remote model service | Centralized model behind an API | Simple clients; controlled updates | Network latency, privacy, availability and cost |
ONNX is an interchange format, not proof of speed or correctness. Export with representative inputs, validate model conformance, compare outputs with the source framework and benchmark on the exact device and execution provider.
From Validated Artifact to Live Traffic
Deployment is a controlled path from offline model to monitored service
Validate
quality + slices
Package
model contract
Equivalence
old vs exported
Load test
p50/p95 + throughput
Canary
small live traffic
Monitor
drift + outcomes
Rollback
known-good version
An inference API makes every transformation explicit
Request
image bytes
Validate
type + size
Preprocess
tensor [1,3,H,W]
Model
logits
Postprocess
softmax + threshold
Response
label + version
A Small Inference Endpoint
Load the model once when the service starts, not on every request. Validate input before decoding it, use the same transform as evaluation, run inference without gradient recording, and return the model version so a prediction can be traced.
from fastapi import FastAPI, HTTPException, UploadFile
import torch
app = FastAPI()
MODEL_VERSION = "crack-detector-v7"
contract = load_validated_contract("crack_detector_v7.json")
CLASSES = contract["classes"] # saved order: ["normal", "crack"]
DECISION_THRESHOLD = float(contract["decision_threshold"])
NORMAL_CLASS_ID = CLASSES.index("normal")
CRACK_CLASS_ID = CLASSES.index("crack")
model = load_validated_model().eval() # once at process startup
@app.post("/predict")
async def predict(file: UploadFile):
raw = await file.read()
if len(raw) > 5_000_000:
raise HTTPException(413, "image is too large")
image = decode_and_validate_rgb_image(raw)
batch = preprocess(image).unsqueeze(0)
with torch.inference_mode():
probabilities = model(batch).softmax(dim=1)[0]
crack_probability = float(probabilities[CRACK_CLASS_ID])
class_id = (
CRACK_CLASS_ID
if crack_probability >= DECISION_THRESHOLD
else NORMAL_CLASS_ID
)
return {
"model_version": MODEL_VERSION,
"label": CLASSES[class_id],
"confidence": float(probabilities[class_id]),
}Trace one request through the endpoint
Five million bytes is an explicitly chosen abuse/resource limit. Decoding checks that bytes form a valid RGB image; preprocessing applies the saved contract; unsqueeze(0) creates a batch dimension of 1. The saved class order fixes the normal and crack indices. Softmax produces a crack probability, and the saved validation threshold 0.72 selects crack only when that probability reaches the operating point; otherwise the response is normal. Confidence is the probability of the selected class, and the immutable version links the response to its artifact.
A production API also needs authentication/authorization, bounded concurrency, timeouts, health/readiness checks, structured error handling, privacy-safe logging and abuse/resource controls.
Latency, Throughput and Batching Measure Different Things
Latency is measured time for one request, often reported at p50 and p95/p99. Throughput is calculated completed items per second. Batching can improve device utilization and throughput while making an individual request wait for a batch.
Eight images: individual versus batch
Assume illustrative benchmark measurements of 20 ms for one image and 45 ms for one batch of eight. Real values must come from load tests on the target device.
One at a time
20 ms × 8 = 160 ms total
throughput ≈ 8/0.160
=50 images/s
One batch of eight
45 ms total
throughput ≈ 8/0.045
≈178 images/s
Interpretation: divide completed items by elapsed seconds: the example batch gives about 3.6× throughput, but its requests take at least 45 ms plus queue time. Choose batch windows from the service-level latency target, not maximum throughput alone.
Compression Trades Size and Speed Against Quality
Quantization stores or computes with lower-precision values; pruning removes selected parameters/structures; distillation trains a smaller student from a larger teacher. Hardware and runtime determine whether theoretical reductions become real latency gains.
Weight-memory estimate
100 million FP32 weights × 4 bytes ≈ 400 MB
100 million INT8 weights × 1 byte ≈ 100 MB
That is roughly 4× less raw weight storage. Actual artifact/runtime memory also includes metadata, activations, workspace, scales/zero-points and framework overhead. Re-evaluate accuracy and latency after conversion.
Roll Out So Failure Is Contained
Shadow
New model receives copied traffic but does not control outcomes. Compare safely, while protecting logged data.
Canary
Route a small controlled traffic share to the new version. Watch guardrail and quality proxies.
Rollback
Automatically or manually route back to a known-good version when defined thresholds fail.
For high-impact decisions, define abstention and human-review paths. A model should not be forced to decide when inputs are invalid, out of scope or confidence/calibration rules require escalation.
Monitor the System After Launch
Monitoring needs four layers of evidence
Service
latency, errors, saturation
Is the system available?
Inputs
shape, ranges, missingness, drift
Is traffic still familiar?
Outputs
class mix, confidence, abstentions
Has model behavior shifted?
Outcomes
delayed labels, false alarms, business cost
Is it still useful and safe?
Set alerts from expected ranges and operational costs, not arbitrary dashboards. Version dashboards by model and data pipeline; otherwise a stable average can hide one faulty version, region, device or subgroup.
Common Deployment Failures
| Symptom | Likely cause | Diagnostic |
|---|---|---|
| Same input gives changing predictions | Model left in training mode; dropout/BatchNorm behavior | Call eval(), use inference mode and repeat identical request |
| Offline good, service bad | Preprocessing or label mapping mismatch | Compare tensors/logits at every boundary on golden examples |
| Load reports missing/unexpected keys | Architecture/version differs from checkpoint | Use strict loading; compare config and parameter names; do not hide with strict=False |
| First requests are very slow | Lazy initialization, compilation or cold model download | Load and warm up before readiness; include cold-start tests |
| Median fine, users time out | High tail latency or queue saturation | Measure p95/p99 under realistic concurrency and payloads |
| GPU out of memory under load | Too many workers/batches or unbounded inputs | Bound size/concurrency, profile peak memory and capacity-test |
| Output mix shifts after a release | Version/preprocessing change or input drift | Segment metrics by model version and input source; canary/rollback |
| No one can reproduce a prediction | Missing artifact, code, data-contract or feature version | Log safe trace IDs and immutable version metadata |
The Deployment Contract
- Save the model state plus the exact architecture, preprocessing, labels, thresholds and provenance.
- Use evaluation mode and gradient-free inference; load only trusted, verified artifacts.
- Compare source and loaded/exported predictions on a representative golden set.
- Choose runtime and compression by measured target-device accuracy, memory and latency.
- Validate every request and return/record the model version that produced the result.
- Load-test throughput and p95/p99 latency, then release by shadow/canary with rollback ready.
- Monitor service, inputs, outputs and delayed outcomes while protecting privacy.