Framework training and inference
A model is not its framework
A deep learning framework provides tensors, operations, automatic differentiation, layers and training utilities. The model is the mathematical mapping and learned parameters, not the library used to implement it. Frameworks can implement the same model differently, so compare shape conventions, data types, device placement, loss reduction and initialization before comparing outputs. Tensors are multidimensional arrays; automatic differentiation records suitable operations and computes derivatives. A module or layer groups computations and parameters. The following API descriptions are conceptual workflows, not runnable framework code; exact package versions and backend compatibility need verification before a real lab.
PyTorch and Keras training workflows
In a typical PyTorch workflow, construct an nn.Module, tensors and an optimizer; set model.train(), clear accumulated gradients, compute a forward pass and loss, call loss.backward(), then optimizer.step(). For validation use model.eval() to change mode-dependent behavior such as dropout and batch normalization, and use torch.no_grad() or torch.inference_mode() when appropriate to avoid building a gradient graph. Evaluation mode alone does not disable gradients. Restore training mode before resuming training. Keras provides layers and models and commonly uses compile() to configure loss, optimizer and metrics, fit() to train, evaluate() to measure against labeled data, and predict() to produce outputs. Training and inference can also differ through a layer’s training argument. Keras and PyTorch APIs are not interchangeable; Keras supports different backends, whose versions and capabilities need checking. No library is executed here.
Transfer learning: freeze a feature extractor
A pretrained model has parameters learned from an earlier task or dataset. Transfer learning reuses some of that representation for a new task; a common first experiment freezes the feature extractor and trains a small task-specific head. The example replaces a pretrained network with a fixed mathematical mapping z=2x so the boundary is visible. The head predicts wz; squared loss gradient for w is 2*(w*z-y)*z, averaged over training rows. With x=1, y=6, w=1 and rate 0.125, the gradient is -16, so the head becomes 3.0. Predictions are 6.0 for x=1 and 12.0 for x=2. The feature map stays unchanged. The second prediction is not evidence of generalization without a known held-out target. This is a toy scalar head update, not a pretrained model or framework implementation. Fine-tuning unfreezes selected weights and uses a controlled training schedule; check which parameters are trainable and how stateful layers behave. In Keras recompile after changing trainability when using the built-in training workflow. Verify model licenses, provenance and target-domain suitability before reusing weights.
def frozen_feature(x): return 2 * x
def head_step(rows, weight, rate): if not rows: raise ValueError("Need training examples") grad = sum(2 * (weight*frozen_feature(x)-y)*frozen_feature(x) for x, y in rows) / len(rows) return weight - rate * grad
def predict(x, weight): return weight * frozen_feature(x)
weight = head_step([(1, 6)], 1, 0.125)print(weight, predict(1, weight))print(predict(2, weight))Inference, devices and memory
During inference, use a fixed checkpoint and the preprocessing that was fitted during training; evaluate on separate labeled data if performance needs measuring. CPU can suffice for small models. Accelerators may improve throughput but introduce transfer, dtype and compatibility considerations. A tensor with shape [2,3,8,8] holds 384 elements. At four bytes each its raw storage is 1536 bytes; at two bytes each it is 768. The function below calculates ideal dense element storage only for nonnegative integer dimensions and positive integer element size. An empty shape denotes a scalar; a zero dimension yields zero elements. Actual memory also includes parameters, gradients, optimizer state, temporary activations, allocator overhead and framework/device-specific buffers. Half precision may change numerical behavior and is not automatically safe or faster.
def tensor_bytes(shape, bytes_per_value): if bytes_per_value <= 0 or any(d < 0 for d in shape): raise ValueError("Invalid shape or element size") count = 1 for dim in shape: count *= dim return count * bytes_per_value
print(tensor_bytes([2, 3, 8, 8], 4))print(tensor_bytes([2, 3, 8, 8], 2))Common mistakes and practice
Do not compare validation metrics with dropout active in one implementation and inactive in another, train on the test set, assume frozen weights imply frozen batch-normalization statistics, or estimate total GPU requirements from one input tensor. Before selecting a real framework environment, record exact interpreter, framework and backend versions, CPU/GPU, dtype, compatible drivers, model and dataset licenses, seed and resource limits. Practice: calculate raw bytes for shape [4,8] with four-byte elements (128), then explain why actual training memory can exceed this. In the project compare a fixed-feature baseline to a candidate learned system and keep a separate held-out evaluation plan.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Framework training and inference quiz
Check architecture and workflow decisions.
What does PyTorch model.eval() do without a separate gradient-mode context?
Which Keras method is typically used to score a model on labeled data?
In the fixed-feature example, which parameter changes in training?
What is the ideal raw element storage for a dense tensor of shape [2,5] and four bytes per element, excluding overhead?
Why should a frozen feature extractor still be evaluated on held-out target-domain data?