TensorFlow interview questions with worked answers
Strong TensorFlow answers trace what executes eagerly, what becomes a cached graph, which variables are watched and updated, and how data shape and reduction choices change the objective. Explain the exact boundary between training state and inference output, state the denominator in a weighted loss, and distinguish a seed from a guarantee of bitwise repeatability. When showing an artifact, say whether it is intended to resume training or serve inference and what trust checks remain outside the file format.
For: Mid-level to senior machine-learning and platform engineers working on TensorFlow-backed model training or serving.
Guide scope and versions
TensorFlow 2.20.0 with Keras 3.11.3 on the TensorFlow backend. Examples use import tensorflow as tf and from tensorflow import keras, with TF_USE_LEGACY_KERAS unset. All 12 published examples were executed on CPU with this pinned runtime.
Question 1 of 12
What does GradientTape record, and why can a gradient be None?
A tf.GradientTape records differentiable TensorFlow operations involving watched sources while the tape is active. Trainable variables are watched automatically by default; ordinary tensors are not. Ask the tape for the derivative of a scalar loss with respect to the source that actually contributed to that loss. A None gradient means there is no recorded differentiable path for that source, not that TensorFlow silently computed a zero update.
The tape observes operations executed inside its context. A Python computation, NumPy conversion, or .numpy() round trip can move a value outside the differentiable graph. A non-variable tensor needs an explicit tape.watch(x) if its derivative is required. Conversely, a trainable tf.Variable is watched automatically unless automatic watching is disabled. Persistent tapes retain intermediates so they can answer more than one gradient query, which costs memory; delete them or prefer a normal single-use tape for one derivative.
For a batch, reduce per-example loss to the scalar objective you intend before calling gradient. TensorFlow sums gradients for non-scalar targets, so asking for a vector loss can mean a sum of per-item derivatives rather than an average. A defensive custom loop checks each requested gradient for None and reports the variable name. Replacing every missing gradient with zero can hide a disconnected head, an accidentally stopped tensor, or a variable that was never built before the tape ran.
Python, TensorFlow 2.20 API · Worked example
import tensorflow as tf
w = tf.Variable(3.0)
x = tf.constant(2.0)
with tf.GradientTape() as tape:
loss = (w * x - 1.0) ** 2
grad_w = tape.gradient(loss, w)
with tf.GradientTape() as tape:
tape.watch(x)
loss = (w * x - 1.0) ** 2
grad_x = tape.gradient(loss, x)
with tf.GradientTape() as tape:
loss = (w * x - 1.0) ** 2
unwatched_grad_x = tape.gradient(loss, x)
assert float(grad_w.numpy()) == 20.0
assert float(grad_x.numpy()) == 30.0
assert unwatched_grad_x is None
print({"grad_w": float(grad_w.numpy()), "grad_x": float(grad_x.numpy()),
"unwatched_grad_x": unwatched_grad_x})
The snippet asserts the symbolic derivatives evaluate to 20 for w and 30 for explicitly watched x. It also records None for the ordinary, unwatched constant source, proving the distinction between an absent gradient path and a numeric zero. The assertions pass in the published example.
Executed on CPU with TensorFlow 2.20.0 and Keras 3.11.3.
Follow-up: How do you make a missing gradient visible in a training loop?
Pair each gradient with its variable, log or raise on None according to the model contract, and name the disconnected variable. Filter missing entries only when disconnection is an intentional part of the architecture. Also check that the variable was created and used inside the recorded computation.
Why did a Python counter inside tf.function increment only once?
tf.function traces Python code to build a TensorFlow graph, then invokes a cached graph for compatible inputs. Ordinary Python side effects such as appending to a list or incrementing a Python integer happen while tracing, not every time the graph runs. Use TensorFlow state such as tf.Variable.assign_add or graph operations such as tf.print when state or output must occur on each execution.
A decorated function is a polymorphic wrapper that may cache separate concrete graphs for different input types, shapes, or Python-valued arguments. A first call can trace, and a later compatible call can reuse the graph without rerunning the Python body. This makes a Python global read especially misleading: changing the global later does not necessarily retrace the function, so the graph may retain the value captured during tracing. Avoid building model behavior around Python mutations inside the decorated function.
Give stable tensor inputs a TensorSpec input signature when it fits the workload to constrain retracing. Create model variables before repeated graph execution, for example by building the layer or making an initial call before compiling the step. Variable creation on later traces is restricted because graph execution needs stable resource ownership. During debugging, run eagerly first, then decorate after the state and tensor contracts are clear.
The fixed scalar TensorSpec means both compatible calls reuse one trace, so the Python trace counter is one while the TensorFlow variable increments on both graph executions and ends at two. Assertions check both returned values and both state counts. The asserted output confirms one trace and two graph executions.
Executed on CPU with TensorFlow 2.20.0 and Keras 3.11.3.
Follow-up: How would you diagnose repeated tracing on changing batch sizes?
Inspect the concrete input signatures and tensor shapes, use a signature with a flexible batch dimension such as [None, features] if valid, and check whether Python arguments are changing. Then measure trace count and graph behavior separately from step runtime. Do not force a broad signature if the model truly requires fixed dimensions.
How can two compatible-looking loss tensors create a wrong objective?
TensorFlow broadcasting makes some shape mismatches legal, which can turn a per-example objective into a pairwise matrix without raising an error. For example, subtracting targets shaped [B] from predictions shaped [B, 1] broadcasts to [B, B]. Agree on named shape contracts at model boundaries and assert them before combining labels, logits, masks, and weights.
Suppose a regression batch has four labels and four predictions. A vector [4] aligns against the last axis of [4, 1]; those dimensions broadcast to [4, 4]. Reducing that matrix then counts every prediction-target pair, not just four aligned pairs. The code is numerically valid and may produce a smooth-looking loss, which makes this more dangerous than a clean shape exception. Reshape labels to [B, 1] or predictions to [B] according to the model's documented output contract.
The same discipline applies to dtype and mask dimensions. Integer class labels should not accidentally be treated as floating regression targets, and a token mask should align with the unreduced token loss before reduction. Put tf.debugging.assert_shapes, explicit casts, and boundary tests near the producer-consumer seam. A shape check should describe the semantic dimensions, not merely make a failing operation run.
The example asserts the subtraction broadcasts [4, 1] and [4] to [4, 4], while explicitly expanding labels produces aligned [4, 1] zeros. It prints both shapes and the aligned sum after checking them. The tensor inputs are defined by the published code itself.
Executed on CPU with TensorFlow 2.20.0 and Keras 3.11.3.
Follow-up: What would you assert in a regression model that returns one value per row?
Specify whether outputs are [B] or [B, 1], then assert that exact rank and batch dimension on predictions and labels before loss computation. Add a batch-size-one test so an unconstrained squeeze cannot silently change the contract.
What is the difference between training=False and layer.trainable=False?
training selects call-time behavior, such as whether Dropout masks activations or BatchNormalization uses batch statistics. layer.trainable controls which weights are eligible for optimization. They are separate controls. In Keras, the set of trainable variables used by fit() is determined at compile() time, so changing a layer's trainable flag after compilation requires recompiling for the new choice to take effect.
An inference call commonly passes training=False, which disables training-specific behavior while leaving gradients mathematically possible if a tape records the call. Conversely, training=True selects training behavior but does not itself mean that gradient recording is active. A frozen BatchNormalization layer also has special interaction with its training argument: Keras documents that marking the layer non-trainable makes it run in inference mode. Explain which behavior you need for each layer rather than treating the word training as a master switch.
Transfer learning often freezes a base model, compiles and trains a new head, then unfreezes selected layers. After changing .trainable, recompile so the optimizer sees the intended variable set. Check the actual trainable_variables list and verify moving-statistic behavior when BatchNormalization is present. If you call the base model with training=False during fine-tuning, that is a deliberate inference-mode choice for its internal stateful layers, not a general replacement for selecting trainable weights.
The code builds a synthetic two-layer model and performs one update while the base layer is frozen, then recompiles after unfreezing and performs another update. Assertions verify the base kernel stays fixed in phase one and changes in phase two. A seeded Dropout layer is also checked for identity in inference mode and masking in training mode; it does not promise a particular random mask.
Executed on CPU with TensorFlow 2.20.0 and Keras 3.11.3.
Follow-up: How do you prove that a fine-tuning phase is updating only the intended layers?
After toggling flags and recompiling, inspect the exact trainable variable names and count, then run a controlled batch and compare selected weights before and after. Separately inspect BatchNormalization moving statistics if the base is called in training mode.
Why does changing the order of cache and repeat change dataset behavior?
A tf.data.Dataset pipeline is a sequence of transformations, and their order changes which values are cached, shuffled, repeated, and batched. cache() retains the elements that reach it; a downstream consumer such as take() can stop iteration before the cache has traversed its full source, so the cache may never be finalized. Put transformations in an order that matches the intended epoch and augmentation semantics, and account for the cache's memory or storage cost.
For finite deterministic input, shuffle(buffer).repeat() reshuffles each traversal through the repeat, while repeat().shuffle(buffer) shuffles across the repeated stream. A buffer smaller than the dataset is a bounded shuffle, not a uniform permutation over all elements. If random augmentation occurs before a cache, its first realization may be stored and reused; placing augmentation after the cache allows it to vary on later traversals. Those are distinct data distributions, not just performance differences.
A partial cache is a common truncation bug: placing cache() before a finite downstream take() on an infinite or repeated source stops traversal before the cache exhausts that source. Cache a finite source only when it fits the chosen memory/disk budget, and make epoch cardinality explicit. For large data, shuffle compact paths or records before expensive decode if that preserves the desired randomness, then parallelize map and prefetch based on profiling. Do not claim cache is always faster if it causes memory pressure or stale preprocessing.
The published synchronous map counters verify the cache boundary directly without a parallel map pool reading ahead. A downstream take(3) consumes only three of six source elements, so iterating twice runs the counted map six times and the cache never completes. In the control pipeline the finite three-element take is upstream of the cache; after the first complete pass, the second pass reuses the cache and the counter remains three. The exact item sequences and counter values are asserted in the snippet.
Executed on CPU with TensorFlow 2.20.0 and Keras 3.11.3.
Follow-up: What pipeline would you choose for deterministic expensive decoding plus fresh augmentation each epoch?
Cache the finite decoded examples only if the cache fits the resource budget, then apply fresh random augmentation downstream, shuffle at the intended epoch boundary, batch, and prefetch. Confirm cardinality and randomness with a small explicit test; distributed input sharding may change the final order.
How should a token-level loss be normalized when batches contain padding?
For a masked token objective, multiply each token loss by its validity mask and divide by the number or total weight of valid tokens, not by the padded sequence width unless that is explicitly the desired objective. The denominator defines how much each example contributes. Keras loss objects have their own reduction rules, so inspect the selected reduction and use an explicit formula when the metric or training objective requires a different denominator.
Suppose a batch contains two sequences padded to four positions, with lengths two and four. There are six valid tokens and eight tensor positions. Dividing the masked sum by eight scales the objective by padding fraction; dividing by six gives the average per valid token. Averaging per-sequence means would instead give each sequence equal weight, which is a different objective again. State the desired weighting before writing the reduction.
Keras supports sample weights, but shape alignment and reduction mode matter. A loss may first reduce a feature axis to one loss per sample or timestep; weights must then broadcast to that resulting shape. Reduction choices such as sum_over_batch_size and mean_with_sample_weight do not mean the same thing when weights sum to less than the batch size. For ragged or distributed batches, define whether the denominator is local, global, or per sequence, and aggregate numerators and denominators consistently across replicas.
Python, TensorFlow tensor algebra · Worked example
The example computes a masked numerator of 22, divides by six valid tokens to obtain 11/3, and separately shows division across all eight padded tensor positions gives 22/8. tf.debugging.assert_near checks both outcomes from the published tensors.
Executed on CPU with TensorFlow 2.20.0 and Keras 3.11.3.
Follow-up: How would you combine masked losses across replicas with different valid-token counts?
Aggregate the masked loss numerator and valid-token denominator across replicas, then divide once, with safe handling for a zero denominator. Averaging replica-local means gives replicas equal weight even when their valid-token counts differ.
When does averaging microbatch gradients change the full-batch objective?
Averaging already-averaged microbatch gradients equally reproduces the full-batch mean only when the microbatches have equal effective weight. If the last microbatch is smaller, or a mask gives different valid counts, equal averaging overweights that small group. Accumulate gradients of summed losses and divide by the total example or valid-element count, or scale each microbatch mean by its count over the intended total before applying the update.
For a batch split into two pieces with sizes three and one, the full mean is (sum_1 + sum_2)/4. Averaging the two local means gives (sum_1/3 + sum_2)/2, assigning the single-item piece half the weight instead of one quarter. The same issue appears in gradient accumulation across variable-length sequence chunks if the code averages local token means rather than weighting by valid-token counts.
The gradient of a sum is the sum of gradients, so a custom loop can accumulate per-example loss sums and gradients, then divide by the known global count before clipping and applying the optimizer. If using distributed training, account for whether the strategy sums or averages replica gradients so the scaling is applied exactly once. Optimizer schedules and regularization losses can also make multiple small optimizer steps differ from one large step even after loss weighting is correct; gradient accumulation matches a batch gradient only when the optimizer update is delayed until the aggregate is ready.
Python, scalar gradient arithmetic · Worked example
TensorFlow differentiates the full four-example mean and each unequal microbatch mean. Assertions verify the full-batch gradient is 3, equal averaging of the three-item and one-item means is 5, and weighting those means by counts recovers 3. This executes the gradient calculation rather than only evaluating hand-written arithmetic.
Executed on CPU with TensorFlow 2.20.0 and Keras 3.11.3.
Follow-up: Would gradient accumulation make BatchNormalization identical to a larger batch?
No. BatchNormalization observes each microbatch's statistics and updates moving state across those calls. Gradient aggregation alone does not reconstruct statistics over the combined batch. Use a normalization method or explicit statistics policy compatible with the desired equivalence.
What should a custom train_step do when some gradients are None?
A custom train_step should make its gradient contract explicit. Pair gradients with their variables, detect None, and decide whether each missing path is expected. A disconnected gradient often indicates an unused head, stopped tensor, or variable absent from the loss path. Silently filtering all missing gradients can hide a model bug or leave an optimizer with no update at all.
The Keras custom-training pattern is to run the forward call and loss computation under a tape, query gradients against the model's intended trainable-variable list, and pass valid pairs to the optimizer. Before applying, report missing variable names and enforce a minimum set of required gradients. Multi-task models may intentionally have task-specific variables that are disconnected for a particular batch; that case should be represented in the contract rather than being treated as universally harmless.
Also include regularization losses where appropriate, typically via self.losses, and update metrics with their intended sample weights. A model can return a finite scalar loss while one branch has no gradient because the output is detached or not included in the objective. Test a tiny known batch by checking which variables change, not only that train_step returns a loss. Under mixed precision, pass scaled-loss gradients through the loss-scaling optimizer correctly; custom code must preserve that protocol.
Python, Keras 3 custom training pattern · Worked example
import tensorflow as tf
from tensorflow import keras
class DisconnectedDemo(keras.Model):
def __init__(self):
super().__init__()
self.used = keras.layers.Dense(1, use_bias=False, name="used")
self.unused = keras.layers.Dense(1, use_bias=False, name="unused")
self.unused.build((None, 1))
self.optimizer = keras.optimizers.Adam()
def call(self, x, training=False):
return self.used(x)
def checked_step(self, x, y):
with tf.GradientTape() as tape:
prediction = self(x, training=True)
loss = tf.reduce_mean(tf.square(prediction - y))
variables = self.trainable_variables
grads = tape.gradient(loss, variables)
missing = [getattr(v, "path", v.name) for g, v in zip(grads, variables) if g is None]
if missing:
raise ValueError(f"Required gradients are disconnected: {missing}")
self.optimizer.apply(grads, variables)
return loss
model = DisconnectedDemo()
x = tf.constant([[1.0], [2.0]], dtype=tf.float32)
y = tf.constant([[0.0], [0.0]], dtype=tf.float32)
model(x)
try:
model.checked_step(x, y)
except ValueError as exc:
assert "Required gradients are disconnected" in str(exc)
assert "unused" in str(exc).lower()
print({"expected_error": str(exc)})
else:
raise AssertionError("the unused trainable layer must be reported as disconnected")
A standalone Keras model builds both a used and unused trainable Dense layer. Its custom checked step differentiates the loss, names missing gradients, and raises before optimizer application. The example catches only that expected ValueError and asserts it identifies the disconnected layer, so an unrelated failure does not count as success.
Executed on CPU with TensorFlow 2.20.0 and Keras 3.11.3.
Follow-up: How do you test intentional task-specific disconnection?
Define the variables expected to update for each task, assert all required gradients are present, and assert excluded task heads remain unchanged. Record the active task and missing-variable set in diagnostics so a new disconnection is observable.
Where should loss scaling and gradient clipping happen in Keras 3?
With LossScaleOptimizer, scale the loss while the tape records it, take gradients of that scaled loss, then pass those scaled gradients to the loss-scale optimizer's apply method. In Keras 3.11.3, that wrapper checks finiteness and unscales gradients inside its apply path before forwarding them to the inner optimizer. Do not manually unscale first and then let the wrapper unscale again.
Low-precision gradients can underflow, so loss scaling multiplies the loss by a scale before differentiation. The resulting gradients are larger by that scale; the wrapper later divides them and adjusts the scale when non-finite gradients appear. Tagged Keras 3.11.3 source implements scale_loss and unscales in the finite-gradient apply path. When compiling with auto_scale_loss=True and a mixed_float16 policy, Keras can wrap the optimizer automatically; custom steps need to know which optimizer object they hold.
Gradient clipping must use the unscaled values when the threshold is stated in ordinary gradient units. Keras 3.11.3 LossScaleOptimizer.apply unscales finite gradients before calling the inner optimizer's apply; the tagged base optimizer then applies global_clipnorm in its update path. Therefore configure Adam(global_clipnorm=1.0) as the inner optimizer and pass scaled gradients to the wrapper. Do not manually divide or clip the scaled gradients first. Do not copy older examples using get_scaled_loss into this pinned Keras version.
Python, Keras 3.11.3 optimizer API · Worked example
import tensorflow as tf
from tensorflow import keras
base_optimizer = keras.optimizers.SGD(learning_rate=0.1, global_clipnorm=1.0)
optimizer = keras.mixed_precision.LossScaleOptimizer(
base_optimizer, initial_scale=8.0, dynamic_growth_steps=1000)
w = tf.Variable(2.0, dtype=tf.float32)
with tf.GradientTape() as tape:
loss = (w * 2.0 - 1.0) ** 2
scaled_loss = optimizer.scale_loss(loss)
scaled_grads = tape.gradient(scaled_loss, [w])
optimizer.apply(scaled_grads, [w])
assert abs(float(w.numpy()) - 1.9) < 1e-6
small_w = tf.Variable(0.5, dtype=tf.float32)
small_base_optimizer = keras.optimizers.SGD(learning_rate=0.1, global_clipnorm=1.0)
small_optimizer = keras.mixed_precision.LossScaleOptimizer(
small_base_optimizer, initial_scale=8.0, dynamic_growth_steps=1000)
with tf.GradientTape() as tape:
small_loss = small_w * 0.25
small_scaled_loss = small_optimizer.scale_loss(small_loss)
small_scaled_grads = tape.gradient(small_scaled_loss, [small_w])
small_optimizer.apply(small_scaled_grads, [small_w])
# Raw gradient 0.25 is below the threshold; scaled gradient 2.0 is above it.
# Correct unscale-before-clip leaves it at 0.25 and updates 0.5 to 0.475.
assert abs(float(small_w.numpy()) - 0.475) < 1e-6
assert int(optimizer.iterations.numpy()) == 1
assert int(small_optimizer.iterations.numpy()) == 1
print({"large_gradient_weight": float(w.numpy()),
"below_threshold_weight": float(small_w.numpy()),
"large_optimizer_iterations": int(optimizer.iterations.numpy()),
"small_optimizer_iterations": int(small_optimizer.iterations.numpy()),
"inner_global_clipnorm": base_optimizer.global_clipnorm})
The first scalar has raw gradient 12, so after unscale the inner global norm clip reduces it to 1 and updates the weight from 2.0 to 1.9. The second uses a separate optimizer instance because Keras builds an optimizer against its variable set on first apply. Its raw gradient is 0.25, below the threshold, while the scale-8 gradient is 2.0. Correct unscale-before-clip leaves it at 0.25 and updates 0.5 to 0.475; skipping unscale and clipping the scaled gradient would instead produce 0.4. Clipping the scaled gradient first and then unscaling would produce 0.4875. The asserted correct update rejects both mistakes. The isolated CPU example tests the loss-scaling and clipping protocol with float32 scalar math; it does not claim float16 kernel or accelerator coverage.
Executed on CPU with TensorFlow 2.20.0 and Keras 3.11.3.
Follow-up: How would you confirm that a custom train_step uses automatic loss scaling exactly once?
Identify whether compile(auto_scale_loss=True) wrapped the optimizer or whether the custom step constructs the wrapper itself. Inspect the actual optimizer type and follow the tagged API's scaling and apply path. Add a small overflow test in a real pinned runtime, and verify skipped updates and scale adjustment without asserting hardware-independent bit patterns.
Does setting a random seed make TensorFlow training reproducible?
A fixed seed makes many random choices repeatable under a fixed software and execution setup, but it is not a blanket guarantee of bitwise-identical training across devices, TensorFlow versions, kernels, distributed configurations, or input pipelines. Set Python, NumPy, and TensorFlow seeds together, and enable TensorFlow op determinism when the supported operations and performance tradeoff fit the experiment. Record the environment and data order as part of the result.
Keras provides keras.utils.set_random_seed to seed Python, NumPy, and the backend framework. TensorFlow's deterministic-op setting asks supported operations to use deterministic implementations; it can reduce performance and may raise when a required deterministic implementation is unavailable. These controls address distinct randomness sources. They do not freeze external data, nondeterministic custom operations, asynchronous input arrival, or behavior that changes between library versions.
Reproducibility also requires a stable train/validation split, preprocessing fitted only on training data, consistent dataset sharding and shuffle seeds, and a defined checkpoint boundary. Even if each update is deterministic, changing batch composition changes the sequence of updates. For distributed jobs, document worker count, replica reduction, and restart behavior. State whether the goal is exact bitwise replay, statistically comparable evaluation, or repeatable debugging; those targets require different evidence.
Python, TensorFlow 2.20 / Keras 3 API · Worked example
import tensorflow as tf
from tensorflow import keras
keras.utils.set_random_seed(812)
tf.config.experimental.enable_op_determinism()
def make_dataset():
return tf.data.Dataset.range(8).shuffle(
8, seed=812, reshuffle_each_iteration=True)
train_ds = make_dataset()
first_epoch = [int(x) for x in train_ds.as_numpy_iterator()]
second_epoch = [int(x) for x in train_ds.as_numpy_iterator()]
replayed_first_epoch = [int(x) for x in make_dataset().as_numpy_iterator()]
assert sorted(first_epoch) == list(range(8))
assert sorted(second_epoch) == list(range(8))
assert first_epoch != second_epoch
assert first_epoch == replayed_first_epoch
print({"first_epoch": first_epoch, "second_epoch": second_epoch,
"fresh_pipeline_first_epoch": replayed_first_epoch})
The example builds a seeded shuffle pipeline over eight known integers. It asserts each epoch contains every value, reshuffling changes the second epoch, and a fresh pipeline with the same seed reproduces the first epoch. This is a local CPU check of the pinned setup, not a cross-device or cross-version determinism claim.
Executed on CPU with TensorFlow 2.20.0 and Keras 3.11.3.
Follow-up: What would you promise in a production model card after enabling deterministic ops?
Describe the tested TensorFlow version, hardware and deterministic setting, then state the measured repeatability scope. Avoid promising cross-device bitwise identity unless it has been verified for the full pipeline. Preserve the data and checkpoint metadata needed to reproduce the evaluation.
When should you use a .keras file, a training checkpoint, or model.export()?
Use the native .keras format to save and reload a Keras model, including configuration, weights, compile information, and optimizer state when present. That preserves Keras-owned training state, but it does not automatically restore an external dataset iterator, sampler position, or random-generator state. Use tf.train.Checkpoint or an explicit training-state scheme for other tracked TensorFlow state, and define a separate recovery contract for external input and RNG state. Use model.export() to produce a TensorFlow SavedModel for inference deployment. An inference export is not a promise that the original training process can be resumed exactly.
Keras 3 separates native Keras serialization from TensorFlow SavedModel export. The tagged Keras 3.11.3 save API recommends .keras for Keras model serialization and directs SavedModel use cases to model.export(). The exported serving artifact captures an inference-callable model interface, but data-loader order, Python preprocessing, external RNG state, and experiment metadata are not automatically included just because weights are present.
A training recovery point needs an explicit inventory of mutable state: model variables, optimizer variables, global step, learning-rate schedule state, random generators, dataset iterator/shuffle state, and any external state such as a curriculum phase. tf.train.Checkpoint can track TensorFlow objects attached to it, but it cannot magically capture arbitrary Python or remote pipeline state. Test recovery by stopping after a known step, restoring in a clean process, and comparing the next batch and optimizer update under the stated tolerance.
Python, TensorFlow 2.20 / Keras 3.11 API · Worked example
import pathlib
import tempfile
import numpy as np
import tensorflow as tf
from tensorflow import keras
inputs = keras.Input(shape=(1,))
outputs = keras.layers.Dense(1, use_bias=False, kernel_initializer="ones")(inputs)
model = keras.Model(inputs, outputs)
model.compile(optimizer=keras.optimizers.Adam(0.1),
loss=keras.losses.MeanSquaredError())
x = tf.constant([[1.0], [2.0]], dtype=tf.float32)
y = tf.constant([[0.0], [0.0]], dtype=tf.float32)
model.train_on_batch(x, y)
assert int(model.optimizer.iterations.numpy()) == 1
model_values = [v.numpy().copy() for v in model.weights]
optimizer_values = [v.numpy().copy() for v in model.optimizer.variables]
step = tf.Variable(1, dtype=tf.int64)
with tempfile.TemporaryDirectory() as scratch:
root = pathlib.Path(scratch)
keras_path = root / "classifier.keras"
model.save(keras_path)
restored = keras.models.load_model(keras_path)
assert int(restored.optimizer.iterations.numpy()) == 1
assert len(restored.optimizer.variables) == len(optimizer_values)
for actual, expected in zip(restored.optimizer.variables, optimizer_values):
np.testing.assert_allclose(actual.numpy(), expected)
for actual, expected in zip(restored.weights, model_values):
np.testing.assert_allclose(actual.numpy(), expected)
checkpoint = tf.train.Checkpoint(model=model, optimizer=model.optimizer, step=step)
manager = tf.train.CheckpointManager(checkpoint, str(root / "checkpoints"), max_to_keep=2)
checkpoint_path = manager.save()
step.assign(0)
model.optimizer.iterations.assign(0)
for variable in model.weights:
variable.assign(tf.zeros_like(variable))
for variable in model.optimizer.variables:
variable.assign(tf.zeros_like(variable))
status = checkpoint.restore(checkpoint_path)
status.assert_existing_objects_matched()
assert int(step.numpy()) == 1
assert int(model.optimizer.iterations.numpy()) == 1
for actual, expected in zip(model.optimizer.variables, optimizer_values):
np.testing.assert_allclose(actual.numpy(), expected)
for actual, expected in zip(model.weights, model_values):
np.testing.assert_allclose(actual.numpy(), expected)
export_path = root / "classifier_saved_model"
model.export(export_path)
assert (export_path / "saved_model.pb").is_file()
print({"keras_optimizer_iteration": int(restored.optimizer.iterations.numpy()),
"checkpoint_step": int(step.numpy()),
"checkpoint_optimizer_iteration": int(model.optimizer.iterations.numpy()),
"export_saved_model_exists": True,
"external_iterator_rng_state_attached": False})
The code trains a small compiled Keras model so Adam slot state exists, then checks .keras reload restores weights, optimizer variables, and iteration. It separately zeros and restores model/optimizer/step variables through tf.train.Checkpoint and verifies those values, then checks model.export() wrote saved_model.pb. The example does not attach an external iterator or RNG state and explicitly reports that boundary.
Executed on CPU with TensorFlow 2.20.0 and Keras 3.11.3.
Follow-up: What is the acceptance test for a resumable training checkpoint?
Restore into a fresh process, verify model and optimizer iteration state, restore or intentionally reset sampler and RNG state, then compare the next batch and update against an uninterrupted reference. Define numeric tolerance and identify any state deliberately excluded from the guarantee.
Is safe_mode enough to load an untrusted Keras model safely?
No. Keras 3.11.3's safe_mode=True disallows unsafe lambda deserialization for the Keras v3 model format; the tagged source warns that safe_mode=False can permit arbitrary code execution. That setting is not an artifact signature, provenance check, integrity proof, or guarantee against resource exhaustion. Treat model files and custom-object code as supply-chain inputs, and only load artifacts from a verified source in an appropriately restricted environment.
The safe-mode contract is deliberately narrow and format-specific. It applies to deserializing the native Keras v3 format and prevents a particular unsafe lambda path. It does not establish who created the archive, whether it was modified, whether custom classes are trustworthy, or whether a model can consume excessive memory or compute. Legacy formats and TensorFlow SavedModel use different loading paths, so do not project the .keras option onto every artifact type.
A production artifact flow should verify a digest or signature against a trusted release manifest, restrict who can publish, review custom layers and custom objects, pin the runtime and dependencies, and load in a process with limited permissions and resources. For SavedModel, TensorFlow describes it as a serialized program and graph, so treat it as executable model logic even when it does not restore arbitrary original Python source. Prefer a known model registry and a staged validation environment over accepting user-uploaded artifacts directly into a privileged service.
A fresh synthetic model is saved locally and loaded only when its bytes match the expected digest computed before the tamper test. load_verified raises the exact digest-mismatch error before calling the tracked deserializer; the call list proves the modified archive never reached Keras loading. The valid local archive is loaded with safe_mode=True, and its outputs and shape are asserted. This checks a local fixture policy, not publisher provenance or an external signed manifest.
Executed on CPU with TensorFlow 2.20.0 and Keras 3.11.3.
Follow-up: Would you load a user-uploaded .keras file in the model-serving API process?
Not in a privileged serving process. Validate provenance and format, then load and inspect it in a restricted staging worker with resource limits. Promote only approved artifacts through an authenticated registry, and keep the serving runtime's filesystem and credentials isolated.
These are Hacker News job posts that mention these technologies, not employee earnings or a measure of what a skill adds to pay. The amounts summarize annualized advertised minimums in approximate USD. Groups can overlap and differ in roles, locations and dates.
TensorFlow posts
10 posts · 10 usable advertised salary amounts
2024-08-01 to 2026-05-05
Not enough usable observations for an aggregate salary: at least 30 are needed. Individual source offers can still be useful.
Approximate USD using ECB daily reference rates as of 2026-10-30. Original currencies and offer ranges remain on the source listings. These figures cover posts tagged TensorFlow, rather than every job in the broader technology family.