Deep Learning, Cloud TPU & Production Serving Masterclass TensorFlow 2.18+ • Keras 3 • OpenXLA • TF Serving • LiteRT

TensorFlow 2.x & Keras 3: @tf.function, OpenXLA, tf.data & Cloud TPUs

Born inside Google Brain to unify large-scale distributed training and zero-Python C++ production serving, TensorFlow 2.x and multi-backend Keras 3 power planetary-scale recommendation engines (DLRM/Two-Tower), high-throughput tf.data C++ streaming ETL pipelines, Google Cloud TPU pods, C++ TensorFlow Serving microservices, and billions of on-device mobile/IoT models via LiteRT (TFLite). Master every architectural layer from @tf.function polymorphic graph tracing and OpenXLA fusion to tf.GradientTape and TPUStrategy.

⚡ @tf.function + OpenXLA 📼 tf.GradientTape Autodiff 🚀 C++ tf.data Pipelines 🧩 Multi-Backend Keras 3 📱 SavedModel, TF Serving & LiteRT

01 Evolution of TensorFlow & The @tf.function(jit_compile=True) OpenXLA Pipeline

From TF 1.x Sessions to Polymorphic Graphs

When Google open-sourced TensorFlow 1.0 in November 2015 (succeeding first-generation DistBelief), engineers had to construct a declarative static tf.Graph of tf.placeholder nodes first and execute it later inside a tf.Session.run(fetches, feed_dict=...) C++ runtime. While static graphs enabled language-independent SavedModel deployment, debugging them in Python was notoriously painful.

TensorFlow 2.x flipped the default to Eager Execution (operations evaluate immediately like NumPy/PyTorch) while preserving C++ graph speed and serialization via the @tf.function decorator and OpenXLA (Accelerated Linear Algebra) compiler:

PYTHON FUNCTION:  @tf.function(jit_compile=True)
                  def train_step(x, y): ...
  │
  ├─▶ STAGE 1: AutoGraph AST Source-to-Source Transformation
  │     • Rewrites Python control-flow statements that depend on tf.Tensor values:
  │       `if t > 0:` ──▶ `tf.cond(...)`   |   `while i < n:` ──▶ `tf.while_loop(...)`
  │
  ├─▶ STAGE 2: Polymorphic Tracing & ConcreteFunction Cache Lookup
  │     • Computes a Cache Key from input signatures: (TensorSpec(shape=[B, D], dtype=bf16), python_scalar_values).
  │     • On cache miss: runs the Python function ONCE with symbolic placeholder tensors to build a C++ FuncGraph!
  │     • On cache hit: bypasses Python completely and dispatches the cached ConcreteFunction directly to the C++ Executor.
  │
  ├─▶ STAGE 3: Grappler (Graph-Level Constant Folding, Dead-Node Pruning & Layout Optimization)
  │     • Optimizes NHWC/NCHW tensor layouts, folds constants, and fuses standard Conv+Bias+Activation patterns.
  │
  └─▶ STAGE 4: OpenXLA Compiler (`jit_compile=True` → StableHLO / HLO Operator Fusion)
        • Lowers the TF FuncGraph into XLA High-Level Optimizer (HLO) IR.
        • Fuses multi-step elementwise, reduction, and matmul epilogues into a single GPU CUDA or Cloud TPU MXU kernel!
Table 1.1 — Architectural Mapping: TensorFlow 2.x / Keras 3 vs. PyTorch 2.x vs. JAX
Subsystem TensorFlow 2.x & Keras 3 PyTorch 2.x JAX / Flax
Tensors & Mutability tf.Tensor is strictly immutable; weights live in mutable tf.Variable (.assign()) torch.Tensor is mutable in-place (add_()); weights are nn.Parameter subclasses jax.Array is strictly immutable; pure functional state pytrees
Autodiff Mechanism Explicit context block: with tf.GradientTape() as tape: + tape.gradient(loss, vars) Implicit tape on requires_grad=True tensors + loss.backward() into .grad Functional transform jax.value_and_grad(loss_fn)(params)
Graph Capture & JIT @tf.function(jit_compile=True) (AutoGraph AST + Tracing → OpenXLA) @torch.compile (TorchDynamo bytecode hook → TorchInductor Triton) @jax.jit (Jaxpr tracing → OpenXLA)
Data Ingestion Pipeline C++ graph tf.data.Dataset (TFRecord, AUTOTUNE, zero Python GIL!) Multi-process Python DataLoader(num_workers, pin_memory=True) Usually uses tf.data or Grain for host data loading!
Production Export & Edge SavedModel protobuf → C++ TF Serving, LiteRT (TFLite) mobile, TF.js browser torch.export (AOTInductor), ExecuTorch, vLLM / Triton Server Exports to TensorFlow SavedModel / StableHLO via jax2tf!

02 Tensor Internals: Immutable tf.Tensor vs. Mutable tf.Variable & Tracing Traps

Functional Tensors + Stateful Variables

Why did TensorFlow make tf.Tensor strictly immutable? Because inside a compiled C++ dataflow graph (@tf.function or OpenXLA), allowing arbitrary in-place buffer mutations creates hidden read-after-write race conditions across parallel execution streams. Instead, TensorFlow cleanly separates stateless dataflow values (tf.Tensor) from explicitly synchronized mutable state (tf.Variable):

Table 2.1 — Complete TensorFlow 2.x Tensor Primitives & Specialized Containers
Primitive Type Mutability Creation & Update API Production Use Case & Graph Behavior
tf.Tensor Immutable tf.constant, tf.zeros, tf.random.normal, tf.tensor_scatter_nd_update Activations, inputs, and intermediate ops. To update specific indices functionally without in-place mutation, use tf.tensor_scatter_nd_update(t, indices, updates).
tf.Variable Mutable State v = tf.Variable(init, trainable=True); v.assign(new_val); v.assign_add(delta) Model weights, biases, and step counters. Automatically watched by tf.GradientTape and synchronized across GPUs/TPUs by tf.distribute.Strategy.
tf.RaggedTensor Immutable tf.ragged.constant([[1, 2, 3], [4], [5, 6]]) Variable-length sequences (token lists, hierarchical user histories) stored via compact flat_values + row_splits offsets—eliminating 0-padding compute waste!
tf.SparseTensor Immutable tf.sparse.SparseTensor(indices, values, dense_shape) COO-encoded sparse features (100M+ categorical IDs in ad/recommendation systems or graph adjacency matrices) with tf.sparse.sparse_dense_matmul.
tf.TensorArray Graph Loop Buffer ta = tf.TensorArray(tf.float32, size=T); ta = ta.write(i, val); ta.stack() Never append to a Python list inside a @tf.function dynamic loop! Use tf.TensorArray to accumulate per-step outputs inside tf.while_loop.

Runnable Lab: @tf.function Polymorphic Tracing & Retracing Trap

Runs in Wasm Sandbox

Click Run in Sandbox to see how TensorFlow’s @tf.function caches compiled ConcreteFunction graphs by TensorSpec(shape, dtype)—and why passing raw Python floats/ints instead of tf.Tensor scalars triggers a catastrophic retracing leak:

# Pure-Python simulation of TensorFlow's @tf.function Polymorphic ConcreteFunction Cache
from dataclasses import dataclass

@dataclass(frozen=True)
class TensorSpec:
    shape: tuple[int | None, ...]
    dtype: str

class MockTensor:
    def __init__(self, shape: tuple[int, ...], dtype: str = "bfloat16"):
        self.shape = shape
        self.dtype = dtype
    def spec(self) -> TensorSpec:
        return TensorSpec(self.shape, self.dtype)

class TfFunctionPolymorphicWrapper:
    def __init__(self, fn):
        self.fn = fn
        self.concrete_cache: dict[tuple, str] = {}

    def __call__(self, *args):
        # Tensor arguments key by (shape, dtype); Python primitives key by EXACT VALUE!
        cache_key = tuple(
            a.spec() if isinstance(a, MockTensor) else ("PY_LITERAL", type(a).__name__, a)
            for a in args
        )
        if cache_key not in self.concrete_cache:
            graph_id = f"ConcreteFunction_Graph_#{len(self.concrete_cache) + 1}"
            self.concrete_cache[cache_key] = graph_id
            print(f"  [TRACE MISS] Tracing & XLA-Compiling {graph_id} for signature: {cache_key}")
        else:
            print(f"  [CACHE HIT ] Reusing compiled {self.concrete_cache[cache_key]} (0 Python overhead!)")
        return self.concrete_cache[cache_key]

@TfFunctionPolymorphicWrapper
def train_step(batch_x, lr):
    return (batch_x, lr)

print("1. Calling with Python float lr (ANTI-PATTERN -> retraces on every step!):")
for step_lr in [1e-4, 2e-4, 3e-4]:
    train_step(MockTensor((32, 512)), step_lr)

print("\\n2. Calling with tf.Tensor scalar lr (BEST PRACTICE -> 1 trace reused forever!):")
for _ in range(3):
    train_step(MockTensor((32, 512)), MockTensor((), dtype="float32"))

Production TensorFlow 2.x Tensors, Variables & RaggedTensors

TF 2.18+ Idioms

Note how functional updates (tf.tensor_scatter_nd_update), tf.Variable.assign_add, and tf.Variable creation rules work inside @tf.function:

import tensorflow as tf

# 1. Immutable tf.Tensor & Functional Scatter Update (Since x[0, 1] = 99 is illegal on tf.Tensor!)
x = tf.zeros([2, 4], dtype=tf.float32)
x_updated = tf.tensor_scatter_nd_update(
    x,
    indices=[[0, 1], [1, 3]],
    updates=[99.0, 42.0],
)

# 2. Mutable tf.Variable (MUST be instantiated OUTSIDE @tf.function or inside Keras Layer.build!)
global_step = tf.Variable(0, dtype=tf.int64, trainable=False, name="global_step")
weights = tf.Variable(tf.random.normal([512, 256], stddev=0.02), trainable=True)

@tf.function(
    input_signature=[tf.TensorSpec(shape=[None, 512], dtype=tf.float32)],
    jit_compile=True,  # Compiles via OpenXLA! Dynamic batch dim `None` is supported
)
def forward_and_bump_step(inputs: tf.Tensor) -> tf.Tensor:
    global_step.assign_add(1)  # In-place C++ atomic/variable mutation inside graph!
    return tf.nn.silu(tf.matmul(inputs, weights))

# 3. Variable-Length Token Sequences without Padding Waste via tf.RaggedTensor
ragged_tokens = tf.ragged.constant([
    [101, 2054, 2003, 1996, 102],   # Length 5
    [101, 7592, 102],               # Length 3 (0 padding tokens stored!)
])
# Embedding lookup works directly on RaggedTensor!
vocab_table = tf.random.normal([10000, 64])
ragged_embeds = tf.nn.embedding_lookup(vocab_table, ragged_tokens)
pooled_mean = tf.reduce_mean(ragged_embeds, axis=1)  # Shape: [2, 64]

03 Automatic Differentiation with tf.GradientTape & Custom Gradients

Explicit Tape Context Recording

Unlike PyTorch (where every operation on a requires_grad=True tensor builds an Autograd graph by default), TensorFlow uses an explicit context manager: with tf.GradientTape() as tape:. Operations executed outside a GradientTape block never allocate backward-pass metadata—giving you zero-overhead inference by default! Inside a GradientTape block:

Runnable Lab: How tf.GradientTape Records & Unwinds Operations

Runs in Wasm Sandbox

Run this live Python implementation of tf.GradientTape to see how operations only record onto the active tape stack while inside the with GradientTape() as tape: scope:

# Pure-Python implementation of TensorFlow's explicit tf.GradientTape Context Manager
_ACTIVE_TAPE_STACK: list["MiniGradientTape"] = []

class TfVal:
    def __init__(self, val: float, trainable: bool = False, name: str = ""):
        self.val = float(val)
        self.trainable = trainable
        self.name = name

    def __mul__(self, other: "TfVal") -> "TfVal":
        out = TfVal(self.val * other.val)
        if _ACTIVE_TAPE_STACK:
            _ACTIVE_TAPE_STACK[-1]._record(out, [(self, other.val), (other, self.val)])
        return out

    def __add__(self, other: "TfVal") -> "TfVal":
        out = TfVal(self.val + other.val)
        if _ACTIVE_TAPE_STACK:
            _ACTIVE_TAPE_STACK[-1]._record(out, [(self, 1.0), (other, 1.0)])
        return out

class MiniGradientTape:
    def __init__(self, persistent: bool = False):
        self.persistent = persistent
        self.watched: set[TfVal] = set()
        self.tape_entries: list[tuple[TfVal, list[tuple[TfVal, float]]]] = []

    def __enter__(self):
        _ACTIVE_TAPE_STACK.append(self)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        _ACTIVE_TAPE_STACK.pop()

    def watch(self, tensor: TfVal) -> None:
        self.watched.add(tensor)

    def _record(self, out: TfVal, local_jacs: list[tuple[TfVal, float]]) -> None:
        for inp, _ in local_jacs:
            if inp.trainable:
                self.watched.add(inp)
        self.tape_entries.append((out, local_jacs))

    def gradient(self, target: TfVal, sources: list[TfVal]) -> list[float | None]:
        grads: dict[TfVal, float] = {target: 1.0}
        for out_node, local_jacs in reversed(self.tape_entries):
            upstream = grads.get(out_node, 0.0)
            if upstream == 0.0:
                continue
            for inp, local_deriv in local_jacs:
                grads[inp] = grads.get(inp, 0.0) + upstream * local_deriv
        if not self.persistent:
            self.tape_entries.clear()  # Releases tape memory immediately!
        return [grads.get(src) if (src in self.watched or src.trainable) else None for src in sources]

w = TfVal(3.0, trainable=True, name="w")
b = TfVal(-1.0, trainable=True, name="b")
x_const = TfVal(4.0, trainable=False, name="x")

with MiniGradientTape() as tape:
    tape.watch(x_const)  # Explicitly watch non-Variable input tensor x_const
    # y = (w * x + b)^2
    lin = (w * x_const) + b
    loss = lin * lin

dw, db, dx = tape.gradient(loss, [w, b, x_const])
print(f"Forward: lin = {lin.val}, loss = {loss.val}")
print(f"Gradients from GradientTape: dL/dw = {dw} (2*11*4), dL/db = {db} (2*11), dL/dx = {dx} (2*11*3)")

Production tf.GradientTape & @tf.custom_gradient

Custom Backward & Jacobians

How to write a custom quantizer gradient with @tf.custom_gradient, stop gradient flow on target networks with tf.stop_gradient, and compute nested second-order derivatives:

import tensorflow as tf

# 1. @tf.custom_gradient for Quantization-Aware Training (Straight-Through Estimator)
@tf.custom_gradient
def quantize_int4_ste(x: tf.Tensor):
    scale = tf.stop_gradient(tf.reduce_max(tf.abs(x)) / 7.0 + 1e-8)
    x_quant = tf.clip_by_value(tf.round(x / scale), -8.0, 7.0) * scale

    def grad(upstream_dy: tf.Tensor) -> tf.Tensor:
        # Pass gradient straight through inside [-8*scale, 7*scale]
        mask = tf.cast((x >= -8.0 * scale) & (x <= 7.0 * scale), upstream_dy.dtype)
        return upstream_dy * mask

    return x_quant, grad

# 2. Nested GradientTapes for Exact Second-Order Derivatives (d²f / dx²)
x = tf.constant(2.5, dtype=tf.float32)
with tf.GradientTape() as outer_tape:
    outer_tape.watch(x)
    with tf.GradientTape() as inner_tape:
        inner_tape.watch(x)
        y = tf.pow(x, 3)            # y = x³
    dy_dx = inner_tape.gradient(y, x)  # dy/dx = 3x² = 18.75
d2y_dx2 = outer_tape.gradient(dy_dx, x)  # d²y/dx² = 6x = 15.0

# 3. Target-Network / Reference-Model Detachment via tf.stop_gradient
# Equivalent to PyTorch's tensor.detach():
ref_logprobs = tf.stop_gradient(reference_model(input_ids, training=False))

04 Neural Networks & Transformers in Multi-Backend Keras 3 (keras.Layer & build)

Deferred Shape Inference & Multi-Backend

Keras 3 (the default high-level API in TensorFlow 2.16+) introduces two architectural superpowers:

1. Lazy Weight Allocation in build(self, input_shape)

Unlike PyTorch’s nn.Linear(in_features, out_features) which requires hardcoding in_features inside __init__, a Keras Layer creates its weights inside def build(self, input_shape): using self.add_weight(...) automatically on the first call when input_shape[-1] becomes known!

2. Write Once with keras.ops → Run on TF, JAX, or PyTorch

By writing layer math using keras.ops (e.g., ops.matmul, ops.silu, ops.rsqrt), the exact same keras.Model can train on Cloud TPUs with JAX, export to a C++ TensorFlow SavedModel, or attach to a PyTorch ecosystem pipeline simply by setting KERAS_BACKEND.

Complete TensorFlow 2.x / Keras 3 Transformer Decoder Block (RMSNorm + Causal MultiHeadAttention + SwiGLU)

Production Architecture
import tensorflow as tf
import keras
from keras import layers, ops

@keras.saving.register_keras_serializable(package="aiagent")
class RMSNorm(layers.Layer):
    """Root-Mean-Square Layer Normalization with deferred build(input_shape)."""
    def __init__(self, eps: float = 1e-6, **kwargs):
        super().__init__(**kwargs)
        self.eps = eps

    def build(self, input_shape):
        # Automatically infers hidden dimension d_model = input_shape[-1] on first call!
        self.scale = self.add_weight(
            name="scale",
            shape=(input_shape[-1],),
            initializer="ones",
            trainable=True,
        )
        super().build(input_shape)

    def call(self, x):
        # Compute mean square in FP32 to prevent BF16 overflow
        x_fp32 = ops.cast(x, "float32")
        ms = ops.mean(ops.square(x_fp32), axis=-1, keepdims=True)
        normed = x_fp32 * ops.rsqrt(ms + self.eps)
        return ops.cast(normed, x.dtype) * self.scale

@keras.saving.register_keras_serializable(package="aiagent")
class SwiGLUFFN(layers.Layer):
    """3-Matrix Gated SwiGLU Feed-Forward Network."""
    def __init__(self, d_model: int, d_ff: int, **kwargs):
        super().__init__(**kwargs)
        self.w_gate = layers.Dense(d_ff, use_bias=False)
        self.w_up   = layers.Dense(d_ff, use_bias=False)
        self.w_down = layers.Dense(d_model, use_bias=False)

    def call(self, x):
        return self.w_down(ops.silu(self.w_gate(x)) * self.w_up(x))

@keras.saving.register_keras_serializable(package="aiagent")
class CausalTransformerBlock(layers.Layer):
    def __init__(self, d_model: int = 1024, num_heads: int = 16, d_ff: int = 2816, dropout: float = 0.0, **kwargs):
        super().__init__(**kwargs)
        self.attn_norm = RMSNorm()
        self.attn = layers.MultiHeadAttention(
            num_heads=num_heads,
            key_dim=d_model // num_heads,
            dropout=dropout,
            use_bias=False,
        )
        self.ffn_norm = RMSNorm()
        self.ffn = SwiGLUFFN(d_model=d_model, d_ff=d_ff)

    def call(self, x, training: bool = False):
        # Pre-RMSNorm + Causal Self-Attention (use_causal_mask=True applies lower-triangular mask automatically!)
        h = self.attn_norm(x)
        attn_out = self.attn(query=h, value=h, key=h, use_causal_mask=True, training=training)
        x = x + attn_out
        # Pre-RMSNorm + SwiGLU FFN
        x = x + self.ffn(self.ffn_norm(x))
        return x

05 High-Throughput C++ tf.data.Dataset ETL & Custom @tf.function Training Loop

GIL-Free Streaming + XLA Mixed Precision

tf.data.Dataset is widely considered one of the strongest engineering components in the TensorFlow ecosystem—even JAX and MaxText training pipelines on Cloud TPU pods use tf.data for host data loading! Because every transformation (.interleave, .map, .batch, .prefetch) compiles into a C++ dataflow graph executed by TensorFlow’s native C++ thread pool, it completely bypasses the Python Global Interpreter Lock (GIL):

Production tf.data.AUTOTUNE Streaming Pipeline + mixed_bfloat16 XLA Training Step

Copy-Paste Production Template
import tensorflow as tf
import keras

# 1. Enable Global Mixed Precision (Computes layers in bfloat16; keeps Variables in float32!)
keras.mixed_precision.set_global_policy("mixed_bfloat16")

def build_streaming_tfrecord_pipeline(
    file_pattern: str,
    batch_size: int = 32,
    seq_len: int = 2048,
) -> tf.data.Dataset:
    feature_spec = {
        "input_ids": tf.io.FixedLenFeature([seq_len], tf.int64),
        "labels":    tf.io.FixedLenFeature([seq_len], tf.int64),
    }

    def _parse_example(serialized_proto: tf.Tensor) -> tuple[tf.Tensor, tf.Tensor]:
        parsed = tf.io.parse_single_example(serialized_proto, feature_spec)
        return tf.cast(parsed["input_ids"], tf.int32), tf.cast(parsed["labels"], tf.int32)

    # 2. C++ Parallel Interleave -> Shuffle -> Parallel Map -> Batch -> Async Prefetch
    files = tf.data.Dataset.list_files(file_pattern, shuffle=True)
    ds = files.interleave(
        lambda fp: tf.data.TFRecordDataset(fp, compression_type="GZIP", buffer_size=16 * 1024 * 1024),
        cycle_length=tf.data.AUTOTUNE,
        num_parallel_calls=tf.data.AUTOTUNE,
        deterministic=False,  # Allows faster out-of-order shard reads across GCS/S3!
    )
    ds = (
        ds.shuffle(buffer_size=10_000)
        .map(_parse_example, num_parallel_calls=tf.data.AUTOTUNE)
        .batch(batch_size, drop_remainder=True)  # Fixed batch shape prevents XLA retracing!
        .prefetch(buffer_size=tf.data.AUTOTUNE)  # Overlaps CPU ETL of batch N+1 with GPU/TPU compute of batch N
    )
    return ds

# 3. Compiled @tf.function + OpenXLA Custom Training Step
optimizer = keras.optimizers.AdamW(learning_rate=3e-4, weight_decay=0.1, beta_1=0.9, beta_2=0.95)
loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True, ignore_class=-100)

@tf.function(jit_compile=True)
def compiled_train_step(model: keras.Model, input_ids: tf.Tensor, labels: tf.Tensor) -> tf.Tensor:
    with tf.GradientTape() as tape:
        logits = model(input_ids, training=True)  # Forward pass in bfloat16
        loss = loss_fn(labels, logits)            # Loss reduction in float32

    # Compute gradients & clip global L2 norm to 1.0 in one fused XLA graph
    grads = tape.gradient(loss, model.trainable_variables)
    clipped_grads, _ = tf.clip_by_global_norm(grads, clip_norm=1.0)
    optimizer.apply_gradients(zip(clipped_grads, model.trainable_variables))
    return loss

06 Interactive TensorFlow OpenXLA, tf.distribute & LiteRT Deployment Planner

Live Architecture Advisor
TensorFlow 2.x Training & Serving Architecture Calculator

Select your target hardware, execution mode, and export precision to calculate memory footprint, XLA speedup, and recommended TensorFlow strategy:

Strategy: tf.distribute.TPUStrategy + OpenXLA
7.0B Params
1B7B32B70B
8 Chips
1 Chip8 (Pod Slice)64 Chips
1. Per-Chip Memory Footprint
18.20 GB / Chip
Sharded 16Ψ/N state + XLA fused buffers
2. Compiler Throughput Gain
2.25× Speedup
OpenXLA HLO fusion eliminates HBM round-trips
3. Recommended Distribution API
TPUStrategy + DTensor Mesh
ICI 3D Torus AllGather + ReduceScatter
4. Production Export Artifact
SavedModel (saved_model.pb)
Zero-Python C++ TF Serving gRPC endpoint

07 Distributed tf.distribute.Strategy & Zero-Python Serving (SavedModel & LiteRT)

Cloud TPU Pods to Mobile Edge
Table 7.1 — TensorFlow Distributed Training & Production Serving Strategies
Strategy / Runtime Hardware Topology Variable Synchronization When to Use in Production
MirroredStrategy 1 Node, 2–8 GPUs (NVLink / PCIe) MirroredVariable synchronized via NCCL Ring AllReduce Single-machine multi-GPU data-parallel training when model state (16Ψ) fits on 1 GPU.
TPUStrategy Google Cloud TPU v4 / v5e / v5p Pod Slices Synchronous XLA AllReduce over optical Inter-Chip Interconnect (ICI) High-throughput BF16 matrix workloads on Cloud TPUs with steps_per_execution=50 to eliminate host-device loop latency.
DTensor (Mesh Sharding) N-Dimensional GPU or TPU Mesh (batch, model) dtensor.Layout shards weight tensors across mesh axes (SPMD) Combining Data Parallelism + Tensor/Model Parallelism for large models exceeding single-chip HBM.
SavedModel + TF Serving C++ gRPC/REST Server (CPU / GPU / TensorRT) Immutable versioned saved_model.pb + dynamic request batching Sub-5ms p99 production inference microservices with zero Python interpreter or GIL overhead and zero-downtime model hot-swapping.
LiteRT (TensorFlow Lite) iOS (CoreML/Metal), Android (NNAPI/NPU), Arm Cortex-M FlatBuffer .tflite with Full-Integer INT8 Quantization On-device mobile, automotive, and embedded edge inference (4× smaller binary, zero memory allocation copy via FlatBuffers).

1. Multi-GPU / Cloud TPU Training with strategy.scope() & strategy.run()

import tensorflow as tf
import keras

def create_distribution_strategy() -> tf.distribute.Strategy:
    try:
        # Automatically detect & initialize Google Cloud TPU Pod slice if present
        resolver = tf.distribute.cluster_resolver.TPUClusterResolver()
        tf.config.experimental_connect_to_cluster(resolver)
        tf.tpu.experimental.initialize_tpu_system(resolver)
        return tf.distribute.TPUStrategy(resolver)
    except ValueError:
        # Fall back to single-node Multi-GPU NCCL MirroredStrategy
        return tf.distribute.MirroredStrategy()

strategy = create_distribution_strategy()
print("Active Replicas:", strategy.num_replicas_in_sync)

# CRITICAL: Model & Optimizer MUST be created inside strategy.scope() so Variables are mirrored!
with strategy.scope():
    model = build_transformer_model()
    optimizer = keras.optimizers.AdamW(learning_rate=3e-4)
    loss_fn = keras.losses.SparseCategoricalCrossentropy(
        from_logits=True,
        reduction=keras.losses.Reduction.NONE,  # Scale manually by global_batch_size!
    )

@tf.function(jit_compile=True)
def distributed_train_step(dist_inputs):
    def replica_fn(inputs):
        x, y = inputs
        with tf.GradientTape() as tape:
            logits = model(x, training=True)
            per_example_loss = loss_fn(y, logits)
            scaled_loss = tf.nn.compute_average_loss(
                per_example_loss,
                global_batch_size=32 * strategy.num_replicas_in_sync,
            )
        grads = tape.gradient(scaled_loss, model.trainable_variables)
        optimizer.apply_gradients(zip(grads, model.trainable_variables))
        return scaled_loss

    per_replica_losses = strategy.run(replica_fn, args=(dist_inputs,))
    return strategy.reduce(tf.distribute.ReduceOp.SUM, per_replica_losses, axis=None)

2. Exporting SavedModel Signatures for TF Serving & LiteRT INT8 Quantization

import tensorflow as tf

class ServingExportModule(tf.Module):
    def __init__(self, trained_model: tf.keras.Model):
        super().__init__()
        self.model = trained_model

    @tf.function(input_signature=[
        tf.TensorSpec(shape=[None, 512], dtype=tf.int32, name="input_ids")
    ])
    def serve_logits(self, input_ids: tf.Tensor) -> dict[str, tf.Tensor]:
        logits = self.model(input_ids, training=False)
        top_probs, top_ids = tf.math.top_k(tf.nn.softmax(logits[:, -1, :]), k=5)
        return {"top_token_ids": top_ids, "top_probs": top_probs}

# 1. Export Versioned SavedModel for C++ TensorFlow Serving Container (/models/agent_router/1/)
export_module = ServingExportModule(model)
tf.saved_model.save(
    export_module,
    export_dir="/tmp/models/agent_router/1",
    signatures={"serving_default": export_module.serve_logits},
)

# 2. Convert SavedModel to On-Device LiteRT (.tflite) with Full-Integer INT8 Quantization
converter = tf.lite.TFLiteConverter.from_saved_model("/tmp/models/agent_router/1")
converter.optimizations = [tf.lite.Optimize.DEFAULT]  # 4x smaller weights + NPU acceleration
tflite_flatbuffer = converter.convert()
with open("/tmp/agent_router_int8.tflite", "wb") as f:
    f.write(tflite_flatbuffer)

08 Frequently Asked TensorFlow Engineering & Interview Questions

Production & Architecture
1. Why does @tf.function print "WARNING:tensorflow:5 out of the last 5 calls to ... triggered tf.function retracing"? →

A @tf.function caches compiled ConcreteFunction graphs using a key derived from (1) the tf.TensorSpec(shape, dtype) of every tf.Tensor argument and (2) the exact value of every non-Tensor Python argument. Retracing occurs for two reasons: either you are passing a changing Python scalar (like step = 1, 2, 3 or a Python float learning rate) instead of wrapping it in tf.constant() / tf.Variable(), or you are passing tensors with variable sequence lengths without specifying a wildcard dimension input_signature=[tf.TensorSpec(shape=[None, None], dtype=tf.int32)].

2. Why can't you create a new tf.Variable inside a @tf.function on every call? →

In eager mode, a Python function runs line-by-line on every call; in graph mode (@tf.function), the Python body only runs once during tracing to build the static C++ FuncGraph. If a function attempts to instantiate a fresh tf.Variable on every execution, the first trace would succeed and subsequent calls would silently reuse the old variable—violating eager semantics. Therefore, TensorFlow raises a ValueError: tf.function only supports singleton tf.Variables created on the first call. Always instantiate tf.Variable objects in __init__ or Layer.build() outside the @tf.function!

3. Why must you use tf.nn.compute_average_loss() instead of tf.reduce_mean() inside tf.distribute.Strategy? →

When training across N GPU or TPU replicas, each replica receives a local micro-batch of size B_local = B_global / N. When MirroredStrategy or TPUStrategy synchronizes gradients across replicas during optimizer.apply_gradients(), it sums the gradients across all N replicas. If each replica divided its loss by B_local via tf.reduce_mean(), the summed gradient would be N times too large! tf.nn.compute_average_loss(per_example_loss, global_batch_size=B_global) divides each replica’s loss sum by B_global so the cross-replica gradient sum equals the exact global batch average.

4. How does Keras 3 support TensorFlow, JAX, and PyTorch simultaneously? →

Keras 3 decouples layer definitions from any single tensor runtime by routing all mathematical operations through the stateless keras.ops namespace (an implementation of the Python Array API standard plus neural network primitives) and delegating the training step (`train_step`) to backend-specific compilers: @tf.function on TensorFlow, @jax.jit with pure state pytrees on JAX, and torch.autograd / torch.compile on PyTorch.

5. What makes a TensorFlow SavedModel and C++ TensorFlow Serving ideal for high-QPS production microservices? →

A SavedModel directory contains a self-contained protobuf computation graph (saved_model.pb) and weight shards (variables/) with zero dependency on the original Python source code. TensorFlow Serving loads this protobuf directly into a multi-threaded C++ gRPC/HTTP server that automatically polls filesystem/GCS paths for new model versions (atomic hot-swapping with zero downtime) and groups concurrent single-item RPC requests into hardware-optimal GPU/TPU batches via a configurable C++ batching scheduler.

Companion Deep Learning Guide

PyTorch 2.x Engineering Masterclass

Compare TensorFlow with PyTorch 2.x: strided UntypedStorage views, reverse-mode Autograd DAGs, FlashAttention-2 SDPA, torch.compile Triton codegen, and FSDP2.

Explore PyTorch 2.x Guide →
11-Page Multi-Module Course

LLM Engineering Masterclass Bootcamp

Master the full LLM lifecycle: BPE tokenizers, GQA/MLA Transformers, LoRA & 4-bit QLoRA math, DPO/GRPO alignment, HITL gateways, and Top 10 LLM models.

Launch LLM Bootcamp →
11-Page Multi-Module Course

Python Engineering Masterclass Bootcamp

Master CPython PyObject & pymalloc internals, PEP 703 No-GIL, all 20 Python data structures & methods, descriptors, and the Top 100 Coding Interview IDE.

Launch Python Bootcamp →