TensorFlow interview questions: Keras, tf.data, tf.function and deployment
Reviewed by Mark Dickie · Last updated
5 questions on this page you can answer and see marked on the spot. Go to the first one
TensorFlow is an open-source machine learning framework from Google that builds and runs computations as tensor operations, with Keras as its high-level model API. Interviewers expect you to explain eager execution versus graph execution with tf.function, train a model with Keras or a custom GradientTape loop, and feed it through a tf.data pipeline. Deployment questions usually cover SavedModel, TensorFlow Serving and TensorFlow Lite.
What does a TensorFlow interview test?
Most questions fall into a few areas. The table maps each one to the concrete API you should be able to talk about.
| Area | What to be ready to explain |
|---|---|
| Execution model | Eager by default in TF 2.x; tf.function traces Python into a graph and retraces on new input shapes or Python arguments |
| Training | model.compile and model.fit versus a custom loop with tf.GradientTape and optimizer.apply_gradients |
| Input pipelines | tf.data map, batch, shuffle, cache and prefetch, and why prefetch overlaps preprocessing with training |
| Model building | Sequential, the functional API and subclassing tf.keras.Model, plus custom layers and callbacks |
| Deployment | SavedModel export, TensorFlow Serving, TFLite conversion and quantization |
How should I prepare for TensorFlow interview questions?
Work through these exercises in order:
- Write a training loop with tf.GradientTape and compare its output with model.fit on the same data.
- Wrap a function in tf.function and print inside it to see when tracing happens.
- Build a tf.data pipeline from TFRecord files with shuffle, batch and prefetch(tf.data.AUTOTUNE).
- Debug a shape mismatch or a NaN loss by checking dtypes, learning rate and input scaling.
- Export a SavedModel, reload it, and convert it to TFLite.
Key facts
- Tarmac has 113 TensorFlow interview questions on this topic, 10 of them on this page, at difficulty 1–5 of 5.
- Tarmac tracked 157 job postings asking for TensorFlow in November 2026.
- Roles asking for TensorFlow advertise a median base salary of £71,000, across 33 job postings as of November 2026.
- Tarmac last reviewed these TensorFlow interview questions on 5 December 2026.
At a glance
| Questions | 10 shown · 113 in the bank |
|---|---|
| Difficulty | 1–5 of 5 |
| Formats | True / false, Multiple choice, Ordering, Find the bug, Fill in the blank, Short answer, Code output, Multiple answer, Design exercise, Flashcard |
What you'll review
- gradienttape
- custom gradients tf
- data augmentation tf
- tf data dataset
Practice questions
Try one before you open the answer. Pick an option and press Check; it's marked on the spot.
In TensorFlow, tf.GradientTape records operations for automatic differentiation only on variables that are being watched, and by default it watches all tf.Variable objects created with trainable=True.#
Options
Show answer
True. tf.GradientTape automatically watches every tf.Variable with trainable=True. To differentiate with respect to a constant tensor or a non-trainable variable, you must explicitly call tape.watch(tensor) inside the tape context.
GradientTape automatically tracks all trainable variables (those with trainable=True). To track a non-trainable variable or a constant tf.Tensor, you must explicitly call tape.watch(tensor) inside the tape context.
In TensorFlow 2.x, which decorator is used to define a custom gradient for a Python function so that tf.GradientTape uses the user-supplied gradient instead of the default computed one?#
Options
Show answer
Use the @tf.custom_gradient decorator to define a custom gradient for a function in TensorFlow 2.x. It lets you supply both the forward output and a gradient function, which tf.GradientTape will use instead of the default autodiff-computed gradient. The other decorators listed either trace graphs or do not exist.
@tf.custom_gradient is the official decorator in TensorFlow 2.x for supplying a custom backward-pass (gradient) function alongside a forward computation. @tf.function traces a graph but does not override gradients; @tf.register_gradient registers gradients for specific named ops at a lower level (used with tf.gradients in graph mode); @tf.autodiff.override does not exist.
Arrange the steps to build a minimal tf.data image input pipeline from a directory of JPEG files whose sizes vary, in the order the calls should appear in code. Use one .map call per transformation, and omit shuffle, cache, prefetch, and augmentation.#
Put these in order
Show answer
List files, then read and decode, then resize, then batch. In a minimal tf.data JPEG pipeline, list_files must produce paths before any file can be read, decoding must yield a tensor before resizing, and resizing to a fixed shape must precede .batch because images of different sizes cannot be stacked into one batch.
The steps form a strict chain. list_files yields path strings, so a map that reads and decodes those paths must come after it. Resizing needs an image tensor, so it must follow decoding. Batching stacks elements into one tensor, which requires identical shapes; because the source JPEGs vary in size, the resize must happen before .batch. Each adjacent pair is therefore forced by a data dependency, and the only valid order is listing, reading and decoding, resizing, then batching.
The following snippet is intended to create a tf.data.Dataset from a list of integers, batch it into groups of two, and print each batch. It crashes at runtime. Identify the bug from the choices below.#
import tensorflow as tf
data = [1, 2, 3, 4, 5, 6]
dataset = tf.data.Dataset.from_tensor_slices(data)
dataset = dataset.batch_size(2)
for batch in dataset:
print(batch.numpy())Options
Show answer
Line 5: batch_size is not a method of tf.data.Dataset; the correct method is batch.
tf.data.Dataset exposes a batch(batch_size) method, not batch_size. Calling dataset.batch_size(2) raises AttributeError: 'TensorSliceDataset' object has no attribute 'batch_size'. from_tensor_slices is the correct API for slicing a list element-wise (the claim that from_tensor_slices should be replaced with from_tensors is wrong). .numpy() works fine on eager tensors produced by iterating a dataset (the claim that .numpy() cannot be called on a tensor inside a Python for-loop is wrong). Plain Python lists are valid inputs to from_tensor_slices (the claim that the Python list must be converted to a NumPy array is wrong).
To create a tf.data.Dataset from a single in-memory tensor (or list of arrays) such that each element of the resulting dataset is one slice along the first dimension, you call dataset = tf.data.Dataset._____(data). This is the standard entry point when your features and labels already reside in memory as NumPy arrays or eager tensors.#
Show answer
To create a tf.data.Dataset from a single in-memory tensor (or list of arrays) such that each element of the resulting dataset is one slice along the first dimension, you call dataset = tf.data.Dataset.**from_tensor_slices**(data). This is the standard entry point when your features and labels already reside in memory as NumPy arrays or eager tensors.
tf.data.Dataset.from_tensor_slices is the canonical constructor for in-memory data: it takes one or more tensors (or arrays) and produces a dataset whose individual elements are slices along axis 0. This differs from from_tensors, which emits the entire input as a single element.
Consider the following TensorFlow code:#
Show answer
None — because x is a tf.constant, not a tf.Variable. GradientTape only automatically watches tf.Variable objects; constants are not tracked unless you explicitly call tape.watch(x). Since x was never watched, the tape has no recorded gradient information for it, so tape.gradient returns None.
tf.GradientTape automatically watches only tf.Variable instances. Here x is a tf.constant(3.0), so the tape does not record operations with respect to x unless tape.watch(x) is explicitly called inside the context. Because no watch was set, tape.gradient(y, x) has no gradient tape for x and returns Python None (not a tensor, not 0.0).
Consider the following TensorFlow code that creates a 4×4 image tensor with a single channel dimension and applies tf.image.central_crop with central_fraction=0.5. The image tensor contains the values 1–16 in row-major order. What does the code print?#
import tensorflow as tf
image = tf.constant([
[[1],[2],[3],[4]],
[[5],[6],[7],[8]],
[[9],[10],[11],[12]],
[[13],[14],[15],[16]]
], dtype=tf.int32)
result = tf.image.central_crop(image, central_fraction=0.5)
print(result.numpy().tolist())Show answer
[[[6], [7]], [[10], [11]]]
In TensorFlow 2.x, tf.image.central_crop computes the start offset per dimension as start = int((size - size * central_fraction) / 2) and the output size as size - 2 * start. For the 4×4 image with central_fraction=0.5, the height and width offsets are int((4 - 2.0) / 2) = 1, and the cropped size is 4 - 2 * 1 = 2 in both dimensions. The crop therefore selects rows 1–2 and columns 1–2 (zero-indexed). The rows are row 0 = [1,2,3,4], row 1 = [5,6,7,8], row 2 = [9,10,11,12], and row 3 = [13,14,15,16], each value wrapped in a single-element channel list. The selected region contains 6, 7, 10, and 11, and the channel dimension is preserved, so the result is [[[6], [7]], [[10], [11]]]. Calling .numpy().tolist() converts the tensor to plain Python nested lists, so print outputs [[[6], [7]], [[10], [11]]].
Which of the following statements about TensorFlow's tf.custom_gradient decorator are correct? Select all that apply.#
Options
Pick every one that applies.
Show answer
The correct statements are: the gradient function receives one upstream gradient per output in output order; it must return one gradient (or None) per input in argument order; and when variables are passed via the variables keyword, the gradient function receives them and returns a list of variable gradients as its second return value. TensorFlow does not auto-verify custom gradients against numerical estimates, and forward-pass operations inside the decorated function are not differentiated through — the custom gradient replaces default autodiff entirely.
tf.custom_gradient replaces the default autodiff for the decorated function. The gradient function receives upstream gradient(s) — one per output, in output order — and must return one gradient per input (or None for non-differentiable inputs), matching argument order. TensorFlow never automatically numerically verifies custom gradients, so the claim that TensorFlow automatically verifies the custom gradient against a numerically estimated gradient each time the function is called in eager mode is false. Operations inside the forward body are not differentiated through; the custom gradient function entirely replaces the default backward pass, so the claim that operations executed inside the forward body of a tf.custom_gradient function are differentiated through normally by the autodiff system is false. When the forward function accepts variables via the variables keyword argument, the gradient function receives an additional variables parameter and must return variable gradients as its second return value (a list), so the statement about the gradient function receiving an additional variables parameter and returning a list of variable gradients as its second return value is true.
You are building an image-classification training pipeline in TensorFlow 2.x using tf.distribute.MultiWorkerMirroredStrategy across 8 workers (4 GPUs each). The dataset is 50 million JPEG images stored as sharded TFRecord files on a network filesystem (NFS). Each worker has 256 GB RAM and local NVMe scratch space. Image resolution varies from 64×64 to 2048×2048. You need to sustain at least 10,000 images/sec aggregate throughput during training.#
Show answer
I would build the pipeline as follows:
-
File listing and sharding: Use
tf.data.Dataset.list_files(pattern, shuffle=False)to get a deterministic list of TFRecord shard files. Then call.shard(num_shards=num_workers, index=worker_index)so each of the 8 workers reads a disjoint set of files. This is the canonicaltf.dataway to partition data across workers inMultiWorkerMirroredStrategy— it avoids duplicate work and ensures every example is seen exactly once per epoch. -
Parallel interleave: Apply
.interleave(lambda f: tf.data.TFRecordDataset(f), num_parallel_calls=tf.data.AUTOTUNE, cycle_length=8, block_length=1, deterministic=False). Thecycle_length=8opens up to 8 files concurrently, overlapping NFS round-trips to saturate network bandwidth.block_length=1cycles between files one record at a time, smoothing out any single slow file. -
Shuffle: After interleaving,
.shuffle(buffer_size=100_000)to randomize within the worker's shard. A buffer of 100K samples (out of ~6.25M per worker) gives good mixing without excessive memory. On NFS, I could alternatively usetf.data.experimental.shuffle_and_repeatfused transformation. -
Map (decode → augment → resize):
.map(parse_fn, num_parallel_calls=tf.data.AUTOTUNE, deterministic=False)whereparse_fndecodes the JPEG, resizes to the target resolution (e.g., 224×224) early, then applies augmentation. Critically, I resize immediately after decode so the large-resolution intermediate tensors are short-lived. Settingdeterministic=Falseallowstf.datato run map operations out of order, maximizing GPU/CPU utilization. To mitigate memory pressure from variable resolutions, I capnum_parallel_callsat a concrete value (e.g., 16–32) rather than unbounded AUTOTUNE, so the number of concurrently decoded images is bounded. -
Batch:
.batch(batch_size, drop_remainder=True).drop_remainder=Trueis essential for distributed training — uneven batches cause shape mismatches across replicas and collective-op failures. -
Prefetch:
.prefetch(tf.data.AUTOTUNE)at the end. This overlaps data production with model execution on the GPU. AUTOTUNE lets the runtime grow the buffer to match the consumer's rate; if I needed a concrete value, I would use2 * batch_sizeto keep roughly two steps buffered. -
Options: I would set
tf.data.Options()withoptimization.autotune = True,optimization.map_and_batch_fusion = True,optimization.map_and_filter_fusion = True, andthreading.private_threadpool_sizesized to the number of CPU cores. Applying these viadataset = dataset.with_options(options)lets the runtime fuse map+batch and other adjacent transformations for lower overhead.
For the variable-resolution concern: the key is that tf.io.decode_jpeg allocates a tensor proportional to the original resolution. By resizing to 224×224 as the first operation inside the map, the large tensor is freed quickly. Additionally, bounding num_parallel_calls prevents the runtime from decoding 100 large images simultaneously and blowing past 256 GB.
This design exercise tests senior-level knowledge of the full tf.data pipeline: cross-worker sharding with .shard(), parallel .interleave() for I/O saturation, stage ordering, deterministic=False for throughput, drop_remainder=True for distributed safety, prefetch sizing, and memory management with variable-resolution inputs.
In TensorFlow 2.x, you create a tf.GradientTape() without persistent=True, call gradient() once, and then call gradient() a second time on the same tape. What happens, and what does the first call release?#
Show answer
The second call raises a RuntimeError saying a non-persistent GradientTape can only be used to compute one set of gradients. The first gradient() call releases the resources the tape holds for the backward pass, including the recorded operations and the intermediate tensors they saved. Creating the tape with persistent=True allows repeated gradient() calls.
The card makes one claim: the second call on a non-persistent tape fails. That follows from TensorFlow's documented lifecycle, where the tape's resources are released as soon as gradient() runs, so there is nothing left to replay. The RuntimeError and its message are TensorFlow's own. The card avoids the earlier overgeneralized watch claims (trainable variables are auto-watched, non-trainable ones are not, and intermediates computed from watched tensors are tracked automatically) because they are not needed to answer the question. Persistent=True is the documented way to keep the tape usable for multiple gradient() calls.
Related interview questions
Job market
See tensorflow salaries and hiring demand from live job postings.
The other 103 questions
This page shows 10 and marks what you pick. That's as far as a page can go. A free account opens the other 103 and keeps every answer. What you miss comes back until it's right: after a day, then at longer gaps.
Free · the whole bank · 100 answers per 30 days, each marked with written feedback