Using Tensorflow 2.0 and eager execution without Keras
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
TensorFlow 2.0 enables eager execution by default, allowing operations to execute immediately like normal Python code. While Keras is the recommended high-level API, TensorFlow 2.0 provides powerful low-level APIs for building models without Keras — using tf.Variable, tf.GradientTape, and tf.Module. This approach gives full control over the training loop, custom gradient computation, and model architecture, which is essential for research, custom layers, and non-standard training procedures.
Basic Tensor Operations in Eager Mode
In eager mode, every tf operation returns a concrete value immediately. You can inspect tensors, use Python control flow (if, for), and debug with standard Python tools.
Variables and GradientTape
tf.GradientTape records all operations involving tf.Variable inside its context. Calling tape.gradient(loss, variables) computes partial derivatives using reverse-mode autodiff.
Building a Model with tf.Module
tf.Module automatically tracks tf.Variable attributes in submodules. It provides .trainable_variables without manual bookkeeping.
Custom Training Loop
The custom training loop gives full control over batching, gradient computation, gradient clipping, learning rate scheduling, and logging — all in plain Python.
Using tf.function for Performance
@tf.function traces the Python function once and compiles it into an optimized TensorFlow graph. Subsequent calls execute the graph directly, bypassing Python overhead. This provides significant speedups for training and inference.
Saving and Loading Without Keras
Common Pitfalls
- Forgetting
tf.GradientTapecontext for gradient computation: Operations outside thewith tf.GradientTape()block are not recorded. If the forward pass happens outside the tape,tape.gradient()returnsNonefor all variables. Ensure the entire forward pass and loss computation are inside the tape context. - Using Python scalars instead of tensors in
@tf.function:@tf.functiontraces the function once per unique input signature. Passing Python integers or floats causes retracing on every call. Convert totf.constantor use tensor arguments to avoid performance degradation from repeated tracing. - Not calling the model before saving:
tf.Modulevariables are created lazily during the first forward pass. Saving a model that has never been called saves an empty checkpoint. Always run a dummy forward pass (model(tf.zeros([1, input_dim]))) before saving. - Modifying variables outside
tf.GradientTape: Direct variable assignment (w.assign(new_value)) outside the tape is not tracked for gradient computation. Use the tape to record operations that should contribute to gradients, and useoptimizer.apply_gradients()for parameter updates. - Assuming eager mode is always slower than graph mode: While eager execution has Python overhead per operation,
@tf.functioneliminates most of it by compiling to a graph. For training loops, wrapping the training step in@tf.functionprovides near-identical performance to TF1 graph mode.
Summary
- TF2 eager mode executes operations immediately without sessions or graphs
- Use
tf.Variablefor model parameters andtf.GradientTapefor automatic differentiation - Subclass
tf.Moduleto organize variables and build modular models - Write custom training loops with
GradientTape+optimizer.apply_gradients() - Use
@tf.functionto compile training steps into optimized graphs for production speed - Save models with
tf.train.Checkpoint(for training) ortf.saved_model.save(for serving)
Related reading
- Using Tensorflow Layers in Keras
- Using the shape of a tensor with dynamic shape in tensorflow operations
- Using WeightedRandomSampler in PyTorch
- Validation accuracy constant in Keras CNN for multiclass image classification
- Using tensorflow dataset with stratified sampling
- Using Tensorflow Huber loss in Keras
- Using tensorflow on Android NDK side directly Not using JAVA api
- Using TensorFlow through Jupyter Python 3
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.