TensorFlow interview questions and answers, from Keras basics to serving

TensorFlow interview questions focus on how TF 2 actually runs your code: eager execution by default, graphs built by tf.function tracing, Keras for models and training, tf.data for input, and SavedModel for anything that leaves the notebook. Experienced candidates are also asked about custom loops with GradientTape, distribution strategies and serving or on-device conversion. Teams that ship to production often care more about the input pipeline and export path than about the model itself.

By Published 7 min read

Where TensorFlow questions come up

TensorFlow is common in companies with long-running production ML, mobile and edge deployments, and Google Cloud or TPU workloads. Interviews for those teams test the whole route from raw records to a served model, not just layer definitions. Versions matter here more than in most frameworks: TF 1 used sessions and placeholders, TF 2 made eager execution the default, and recent releases ship Keras 3, which can also run on JAX or PyTorch backends. If you are unsure which version a team runs, ask, and frame answers around TF 2 behavior.

  1. Screening questionsShort checks on eager mode, tf.function, Keras APIs and loss settings, often from a recruiter's list or a hiring manager.
  2. Hands-on taskBuild and train a small Keras model on a provided dataset, or fix a notebook where the input pipeline or loss is wrong.
  3. Production discussionHow you would export, version, serve and monitor the model, and how you would make training faster or cheaper.
  4. Project deep diveA model you shipped: data volume, training setup, what broke and how you measured the result.

TensorFlow fundamentals questions

Core questions for freshers and early-career candidates
QuestionWhat it testsWhat a strong answer shows
What is eager execution, and what replaced sessions?TF 2 basicsOperations run immediately and return concrete values, like NumPy. Graphs still exist, but you get them by wrapping functions in tf.function instead of building a graph and running it in a session.
tf.Tensor versus tf.Variable?StateTensors are immutable values. Variables hold mutable state, such as weights, that persists across calls and that optimizers update with assign.
What does tf.function do?TracingIt traces the Python function once per input signature into a graph, then reuses that graph. You gain speed and exportability but lose ordinary Python side effects inside it.
Sequential, Functional or subclassed model?Keras stylesSequential for a plain stack, Functional for branches, shared layers and multiple inputs or outputs, subclassing for custom forward logic. Functional models are easier to inspect, plot and serialize.
What does from_logits=True mean in a loss?Loss inputsThe model outputs raw scores and the loss applies softmax or sigmoid itself, which is more numerically stable than a softmax layer followed by a loss that expects probabilities.
Sparse categorical or categorical crossentropy?Label formatSparse takes integer class ids; categorical takes one-hot vectors. Using the wrong one gives a shape error or, worse, a silently wrong loss.
What does the training argument do when you call a model?Layer behaviorIt switches layers like dropout and batch normalization between training and inference behavior. fit sets it for you; custom loops must pass it.
What happens in compile, fit and evaluate?Keras workflowcompile attaches optimizer, loss and metrics; fit runs the training loop with batching, callbacks and validation; evaluate reports loss and metrics on held-out data.
How do you check whether TensorFlow sees a GPU?Devicestf.config.list_physical_devices("GPU"). Mention that driver and CUDA versions must match what the installed TF build expects, which is a common setup failure.
What file formats can a Keras model be saved in?SerializationThe native .keras file for Keras models, SavedModel directories for serving and conversion, and weights-only files. Older code may still use HDF5 .h5, which recent versions treat as legacy.
Core questions for freshers and early-career candidates. Scroll sideways on a small screen.

tf.function and tracing questions

Tracing confuses more candidates than any other TF topic, so interviewers like it. Python code inside a tf.function runs while the graph is being built; only TensorFlow ops become part of the graph and run on every call. Passing new Python values, or tensors with a new shape or dtype, triggers a fresh trace, which is slow if it happens on every step.

import tensorflow as tf

@tf.function
def double(x):
    print("tracing")            # Python print: runs only while tracing
    tf.print("running", x)      # graph op: runs on every call
    return x * 2

double(tf.constant(1))          # tracing, then running 1
double(tf.constant(2))          # running 2 (same dtype and shape, no retrace)
double(3)                       # tracing again: each new Python value is a new trace
Python side effects run during tracing only; tf.print runs on every call.
  • Why does TF warn about excessive retracing? Usually Python numbers or varying shapes are passed in. Convert inputs to tensors, or fix the signature with input_signature and None for variable dimensions.
  • Why can't you use a Python `if` on a tensor value inside tf.function? You can, through AutoGraph, which rewrites it into tf.cond. But the branch then depends on tensor values at run time, and both branches must produce compatible outputs.
  • Why should you not create Variables on every call? A tf.function may create variables only on its first trace. Create them once, in a layer's build or outside the function.
  • How do you debug code inside a tf.function? Temporarily run eagerly with tf.config.run_functions_eagerly(True), use tf.print, and switch back before timing anything.

Intermediate questions: data, training and Keras internals

  • How do you build a fast tf.data pipeline? Read with parallel interleave for sharded files, map with num_parallel_calls=tf.data.AUTOTUNE, cache after expensive but deterministic steps, shuffle with a sensible buffer, batch, then prefetch so the accelerator never waits.
  • Where does `cache` go, and what is the risk? After decoding and before random augmentation. Placed after augmentation, every epoch replays the same augmented samples.
  • What is a TFRecord, and why use one? A file of serialized tf.train.Example records that streams well from disk or cloud storage and shards cleanly across workers.
  • What does a custom layer's `build` method do? It creates weights lazily once the input shape is known, so the layer works without hard-coded input sizes.
  • Which callbacks have you used? EarlyStopping with restore_best_weights, ModelCheckpoint on a validation metric, ReduceLROnPlateau, and TensorBoard for curves and profiling.
  • Why keep preprocessing layers inside the model? Normalization, text vectorization or resizing saved with the model removes a whole class of train and serve mismatches.
  • When is a persistent GradientTape needed? When you call tape.gradient more than once, for example for two losses or for higher-order derivatives. Delete it afterwards to free memory.
  • How do you fine-tune a pretrained Keras model with batch norm? Freeze the base, train the head, then unfreeze top layers with a low learning rate. Call the base with training=False so batch norm keeps its learned statistics.
  • How do you enable mixed precision? Set a global policy such as mixed_float16, keep the final layer in float32 for stable outputs, and let the loss scaling that fit applies handle underflow.
import numpy as np
import tensorflow as tf

rng = np.random.default_rng(0)
x = rng.normal(size=(1000, 8)).astype("float32")
y = (x[:, 0] + x[:, 1] > 0).astype("int32")

ds = (tf.data.Dataset.from_tensor_slices((x, y))
      .shuffle(1000, seed=0)
      .batch(32)
      .prefetch(tf.data.AUTOTUNE))

model = tf.keras.Sequential([
    tf.keras.Input(shape=(8,)),
    tf.keras.layers.Dense(16, activation="relu"),
    tf.keras.layers.Dense(2),                 # logits, no softmax
])
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
optimizer = tf.keras.optimizers.Adam(1e-2)

@tf.function
def train_step(xb, yb):
    with tf.GradientTape() as tape:
        logits = model(xb, training=True)     # training flag drives dropout and batch norm
        loss = loss_fn(yb, logits)
    grads = tape.gradient(loss, model.trainable_variables)
    optimizer.apply_gradients(zip(grads, model.trainable_variables))
    return loss

for epoch in range(5):
    for xb, yb in ds:
        loss = train_step(xb, yb)
print("last batch loss", float(loss))
A tf.data pipeline and a custom training step with GradientTape, the loop interviewers ask you to write by hand.

Senior and production scenario questions

Scenarios for experienced candidates and MLOps-leaning roles
ScenarioWhat it testsWhat a strong answer shows
Train on four GPUs in one machine.DistributionCreate tf.distribute.MirroredStrategy, build and compile the model inside strategy.scope(), scale the global batch size and often the learning rate, and keep the dataset as tf.data so it can be split across replicas.
Move training to several machines or to TPUs.Scale-outMultiWorkerMirroredStrategy with cluster configuration, or TPUStrategy, plus sharded input files and checkpoints written to shared storage.
Serve the model behind an API with versioning.ServingExport a SavedModel with an explicit serving signature, load it in TensorFlow Serving under a numbered version directory, and roll forward or back by version.
Put the model on a phone.EdgeConvert with the TFLite converter, apply post-training quantization, check accuracy on a held-out set after conversion, and confirm every op is supported on the target.
The GPU shows almost all memory used before training starts.MemoryBy default TF reserves most GPU memory up front. Enable memory growth when several processes share a card, and do not read that number as a leak.
Steps are slow but the GPU is mostly idle.Input boundUse the TensorBoard profiler to confirm input wait, then parallelize map, add prefetch, cache decoded data, and move heavy augmentation onto the accelerator.
A reloaded model gives different predictions.SerializationCustom layers or losses not registered for deserialization, preprocessing done outside the model, or saving weights only and rebuilding a slightly different architecture.
Migrate a TF1 codebase.Legacy codeReplace sessions and placeholders with functions and Keras models, retire tf.compat.v1 piece by piece, and keep a numeric comparison test on fixed inputs while you go.
When would you choose TFX or a similar pipeline tool?ML pipelinesWhen data validation, training, evaluation and push to serving must run repeatably on schedule. For a single model with a small team, a simpler scheduled job may be enough.
Scenarios for experienced candidates and MLOps-leaning roles. Scroll sideways on a small screen.

Fictional example

Answering "training is slow even on a big GPU"
Interviewer
Each epoch takes forty minutes on an expensive GPU. How would you speed it up?
Candidate
I would profile one epoch before touching anything, because the answer is different if the GPU is starved or saturated. In a past project the trace showed the device idle most of each step. Our pipeline decoded JPEGs in a single-threaded map and shuffled after batching. I moved decoding into a parallel map with autotune, cached the decoded and resized images to local disk, shuffled before batching and added prefetch. That made the input pipeline keep up. Only then did I turn on mixed precision and raise the batch size with a matching learning rate change, checking that validation accuracy held. I would also wrap the step in tf.function if it were a custom loop and confirm it was not retracing each batch.

A one-week TensorFlow practice plan

  • Day 1: build the same classifier three ways, Sequential, Functional and subclassed, and save and reload each one.
  • Day 2: write a tf.data pipeline from files, then time it with and without parallel map, cache and prefetch.
  • Day 3: write a custom training step with GradientTape and match its results to fit on a fixed seed.
  • Day 4: break tracing on purpose with Python arguments and varying shapes, read the warnings, then fix them.
  • Day 5: fine-tune a pretrained image model with frozen and then partly unfrozen layers.
  • Day 6: export a SavedModel with a signature, then convert it to TFLite with quantization and compare accuracy.
  • Day 7: a timed mock: build, train and export a small model while explaining each choice aloud.

Many job posts list both frameworks, so read PyTorch interview questions for the other side of the comparison and scikit-learn interview questions for the baselines and pipelines that usually come first. For research-heavy roles, see machine learning scientist interview questions.

A framework round goes better when you can explain tracing or an export path in plain words without stalling. For rehearsal, Natively, an AI interview assistant for Mac and Windows, writes a transcript of your mock session on your own machine, and it can suggest answers live as practice questions come in. It can also read a notebook error or a coding prompt from a screenshot and propose a fix, and with Pro or the free trial it tailors suggestions to the résumé and job description you supply. Review the saved notes afterwards to spot the topics you hedged.

Questions people ask

What TensorFlow questions are asked in interviews?

Eager versus graph execution, what tf.function tracing does, Keras model styles, loss settings such as from_logits, tf.data pipelines, custom loops with GradientTape, and for senior roles distribution strategies, SavedModel, serving and TFLite.

Is TensorFlow still asked in ML interviews?

Yes, especially at teams with established production ML, mobile or edge deployment, or TPU workloads. Many job posts list PyTorch and TensorFlow together, so be ready to compare them.

What is the hardest TensorFlow interview topic?

Usually tf.function: Python side effects run only while tracing, new Python values or shapes cause retracing, and variables may be created only once.

How do I prepare for a TensorFlow interview?

Build one model in Sequential, Functional and subclassed form, write a GradientTape training step, tune a tf.data pipeline, and export a SavedModel. Explain each step aloud as you practice.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP