Cognibiz

TensorFlow v2.18: from eager computation to an exportable programtensorflow.org

AI technologies, organized by technology area.

TensorFlow: TensorBoard screen from the official tutorial. Curves belong to the published example, not a Cognibiz experiment.Inset: Simplified graph-mode view. TensorFlow also supports eager execution; this drawing does not imply every computation uses XLA. TensorBoard is a separate visualization tool.Credit and source

The sketch explained

TensorFlow: following a computation graph

In graph mode, connected operations transform input tensors into outputs. For model training, automatic differentiation can compute the required gradients.

On a small screen, scroll the diagram horizontally to read its labels.

TensorFlow: following a computation graphInput tensors · Operation graph · Output tensors · Gradient computationInput tensorsOperationgraphOutput tensorsGradient computation
Input tensors
A tensor represents an array of values and its dimensions.
Operation graph
Nodes represent operations; their connections express data dependencies.
Output tensors
Outputs can be predictions, a loss or other tensors.
Gradient computation
The purple arrow represents derivative propagation, not identical data flowing backwards.
Simplified graph-mode view. TensorFlow also supports eager execution; this drawing does not imply every computation uses XLA. TensorBoard is a separate visualization tool.Technical documentation
Updated

UNDERSTANDING THE SYSTEM

TensorFlow v2.18: from eager computation to an exportable program

TensorFlow provides tensor computation, automatic differentiation and tools to train and export programs. Version 2.18 notably changes NumPy compatibility and CUDA builds; effective use still depends on the shapes, dtypes, graphs and state the program handles.

02 / CHAPTER

A computation library with a specific version

TensorFlow is a computation framework rather than a pretrained model or a query language. It provides tensor operations, mutable variables and an execution engine. A project may assemble a model in Keras, train it with a custom loop and expose inference through SavedModel. Those responsibilities remain distinct even when one library makes them accessible.

The imported v2.18 label refers here to release 2.18.0, rather than the newest release. Its notes establish support for NumPy 2.0 and compilation against it by default. NumPy changed its type promotion rules: conversions or mixed-type additions may therefore change numerical precision or raise errors. A migration needs numerical regression checks, rather than a successful import alone.

Hermetic CUDA builds use dependencies selected and downloaded by Bazel instead of automatically using the local CUDA installation. This improves build reproducibility without guaranteeing identical numerical results on every device. The release also disables TensorRT support in CUDA builds. These historical changes are not installation instructions for the reader’s computer.

References for this chapter[1][2]

03 / CHAPTER

Make shape, dtype and state explicit

A tensor has values, a shape and a dtype. For an input shaped [B, 2], B is the number of examples and 2 the number of features. Its rank is two whatever B may be. A declared shape [None, 2] allows a variable batch size, not three features or arbitrary numerical types. An unknown dimension does not authorize changing what an axis means.

Broadcasting can conceal mistakes: subtracting a target shaped [B] from a prediction shaped [B, 1] can produce [B, B] rather than one difference per example. With B equal to 3, that is nine differences instead of three. Check shapes before reducing a loss; otherwise a mean can make the wrong calculation look plausible.

An ordinary tensor is not a container updated in place; a variable maintains state across calls. Updating a weight modifies that variable. A 32 × 128 FP32 array contains 16 KiB of raw data, excluding objects, buffers, gradients and optimizer state. Moving devices or changing dtype can also require transfers or conversions: shape compatibility alone does not establish an efficient hardware path.

References for this chapter[3][1]

04 / CHAPTER

Keras 3 and TensorFlow serve different roles

Keras describes layers, models and high-level training workflows. TensorFlow is the engine executing operations when the TensorFlow backend is selected. In a standard TensorFlow 2.18 configuration, the exposed Keras interface uses Keras 3; the pinned loader also retains an explicit route to the legacy Keras package. That route does not automatically migrate an old project to Keras 3.

Keras 3 supports multiple backends. A layer using its portable operations can be reusable across engines; one that directly invokes TensorFlow operations does not become portable by changing an option. The same applies to a custom training loop built around TensorFlow’s gradient machinery. Compatibility also depends on custom layers, losses and serialization.

For an application already tied to TensorFlow, starting with its backend often provides the simplest qualification path. For portability, isolate engine-specific dependencies and compare inputs, outputs and gradients in every target environment. The Keras backend, the CPU/GPU device and the XLA compiler are separate decisions. Multiple backends do not establish any universal performance ranking.

Keras 3 and TensorFlow serve different roles
DecisionQuestion to check
Keras backendDo components use portable Keras operations or TensorFlow-specific operations?
DeviceAre the dtype and operations available on the target CPU, GPU or TPU?
XLACan the computation compile and be reused, and is it useful after accounting for compilation?

References for this chapter[4][5][6]

05 / CHAPTER

Trace a function, then reuse its graph

Eager execution dispatches operations as Python instructions run, making inspection straightforward. A traced function first runs the Python needed to construct a graph of TensorFlow operations and can then reuse that graph. Its cache can contain several concrete functions for different signatures. Building a graph and compiling it with XLA are separate steps.

Retracing builds another graph when a call does not match a reusable trace. Different dtypes, shapes or Python values may trigger it. A signature allowing a variable batch dimension limits some variants but does not accept an incompatible dtype. A Python print or list mutation may happen only during tracing; state needed on every call must use suitable TensorFlow operations or variables.

The example sums the squares of two features per example. Inputs [1, 2], then [3, 4] and [0, 1], produce 5, then 25 and 1. The signature accepts batch sizes one and two under the same general shape. It rejects an input with three features. This is a functional contract that can be checked by hand, without downloads or speed measurements.

The cache stores programs, not answers

Conceptual tracing diagram. Shapes and dtypes govern reuse; no compilation time is measured.

  1. Build

    An FP32 call shaped [1, 2] builds a graph for [None, 2]. Nodes represent squaring followed by a row-wise sum.

  2. Reuse

    An FP32 call shaped [2, 2] satisfies the contract and can reuse the same graph. Values change while operations remain the same.

  3. Reject or retrace

    Input [2, 3] violates the declared signature and is rejected. Without that signature, a new shape might create another trace; this is not a cached answer.

import tensorflow as tf

@tf.function(input_signature=[tf.TensorSpec([None, 2], tf.float32)])
def score(x):
    return tf.reduce_sum(x * x, axis=1)

with tf.device("/CPU:0"):
    a = score(tf.constant([[1., 2.]], dtype=tf.float32))
    b = score(tf.constant([[3., 4.], [0., 1.]], dtype=tf.float32))
tf.debugging.assert_near(a, [5.])
tf.debugging.assert_near(b, [25., 1.])
FP32 signature with a variable batch dimension; outputs can be checked by hand, without installation instructions.

References for this chapter[7][8]

06 / CHAPTER

A gradient tape differentiates; an update changes weights

GradientTape records relevant operations executed inside its context. Reverse traversal applies the chain rule to connect a loss to watched variables. Trainable variables are watched automatically in the usual case; an ordinary tensor may require explicit watching. Integer computations are not a normal differentiable path, and moving a calculation to NumPy can break the recorded connection.

A missing gradient differs from a zero gradient. An unwatched or disconnected variable may yield no gradient, whereas zero can be the correct derivative. A normal tape is generally used for a single gradient request. A persistent tape retains additional resources for multiple requests and should be chosen deliberately. Training then needs a separate update, either manual or performed by an optimizer.

With x = 2, target y = 4 and weight w = 1, prediction wx is 2 and loss (wx − y)² is 4. The derivative 2x(wx − y) is −8. A gradient descent step of size 0.1 gives w = 1.8, prediction 3.6 and loss 0.16. This is one step on one example; it establishes neither general convergence nor generalization quality.

From recorded computation to an updated weight

A scalar example connects forward computation, derivative and update. Values follow from the equation rather than measured training.

  1. Record

    With w = 1 and x = 2, prediction is 2. The target is 4 and squared loss is 4. The tape retains the connection between w and the loss.

  2. Differentiate

    Reverse traversal gives dL/dw = 2x(wx − y) = −8. The gradient alone does not update the weight.

  3. Update

    A step of 0.1 changes the weight to 1.8. Prediction becomes 3.6 and loss 0.16; another step would require another computation.

import tensorflow as tf

with tf.device("/CPU:0"):
    w = tf.Variable(1.0, dtype=tf.float32)
    x = tf.constant(2.0, dtype=tf.float32)
    target = tf.constant(4.0, dtype=tf.float32)
    with tf.GradientTape() as tape:
        prediction = w * x
        loss = tf.square(prediction - target)
    gradient = tape.gradient(loss, w)
    assert gradient is not None
    w.assign_sub(0.1 * gradient)
    new_loss = tf.square(w * x - target)
tf.debugging.assert_near(loss, 4.0)
tf.debugging.assert_near(gradient, -8.0)
tf.debugging.assert_near(w, 1.8)
tf.debugging.assert_near(new_loss, 0.16)
One gradient descent step on CPU; assertions allow for FP32 rounding.

References for this chapter[9][10]

07 / CHAPTER

The input pipeline is part of the program

An input pipeline describes elements and transformations: reading, decoding, shuffling, batching and prefetching. Its iterator actually produces the elements; defining the pipeline does not materialize the whole dataset. Transformation order matters. Caching after random augmentation may freeze the first traversal’s results, whereas caching before augmentation preserves the opportunity to vary them.

Prefetching prepares elements while computation consumes earlier ones. Its buffer counts elements at the point where it is placed: after batching, an element is a batch. It uses memory and cannot make a slow source infinitely fast. Automatic parallelism tuning guarantees neither minimum memory nor interchangeable ordering. Version 2.18 adds a synchronous mode and an unbounded thread-pool option to map; their usefulness depends on the workload.

The example visits integers zero through five, squares them, caches them and groups them in pairs. It yields exactly [0, 1], [4, 9] and [16, 25]. An in-memory cache is reasonable for six values, not necessarily for a large collection of decoded images. In production, check cardinality, iteration termination and the final batch; dropping an incomplete batch stabilizes a shape while omitting data.

Prepare, buffer, consume

Boxes represent elements and then batches; widths encode neither time, throughput nor hardware capacity.

  1. Transform

    Integers 0 through 5 become 0, 1, 4, 9, 16 and 25. A cache here preserves these deterministic results.

  2. Batch

    Grouping by two yields [0, 1], [4, 9], [16, 25]. After this transformation, one pipeline element is one batch.

  3. Prefetch

    A one-element prefetch buffer now holds one batch ahead. It can overlap preparation with consumption at the cost of additional memory.

import tensorflow as tf

with tf.device("/CPU:0"):
    dataset = tf.data.Dataset.range(6)
    dataset = dataset.map(lambda x: x * x)
    dataset = dataset.cache().batch(2).prefetch(1)
    batches = [batch.numpy().tolist() for batch in dataset]
assert batches == [[0, 1], [4, 9], [16, 25]]
A finite in-memory pipeline; expected values are calculations rather than performance measurements.

References for this chapter[11][12]

08 / CHAPTER

XLA and device placement optimize an already correct program

XLA compiles supported computations. It can fuse operations and choose execution paths that reduce some intermediate storage or kernel launches. An ordinary traced function does not automatically request this explicit compilation. When compilation is required, an unsupported operation can make that path fail; transparent fallback to eager execution is not guaranteed.

Benefits depend on shapes, operations, hardware and reuse of the compiled program. First compilation can dominate a short run, while changing shapes can create multiple compilations. External Python calls and dimensions depending on values complicate the contract. Keeping a correct version without XLA makes it possible to compare results and identify constraints introduced by compilation.

Placement assigns operations to devices that are available and support them. An input created on the CPU and consumed on a GPU may require a transfer; the whole pipeline does not necessarily move. Evaluate an accelerated path by separating data preparation, tracing, compilation, transfers and steady execution, and by actually waiting for results. Hermetic CUDA builds concern software construction rather than elimination of these runtime costs.

References for this chapter[13][8][2]

09 / CHAPTER

Distribute batches without silently changing the loss

A distribution strategy specifies how variables and computation are arranged. A mirrored strategy replicates variables across devices and synchronizes contributions from replicas; it does not automatically shard every matrix of an oversized model. TPU execution imposes its own constraints, and multi-worker training adds configuration, input handling and communication to local requirements.

The global batch is the sum of the replicas’ batches for a synchronized step. In a custom loop, loss normalization and gradient reduction must be designed together. One approach divides the local sum of per-example losses by the global batch size, then sums contributions. Averaging each local loss and summing without correction multiplies the gradient scale for equal local batches.

For four examples split two per replica, local loss sums of 2 and 6 give global mean (2 + 6) / 4 = 2. Normalized contributions are 0.5 and 1.5, which sum to 2. Adding local means 1 and 3 would give 4. With unequal local batch sizes, a simple mean of means is wrong as well. Verify this arithmetic and an equivalent single-device step before interpreting speedup.

References for this chapter[14][15]

10 / CHAPTER

Weights, resumable state and inference interfaces are different artifacts

Saved weights describe parameter values. Resuming training also requires reconstructing computation and, depending on the goal, optimizer state, counters, random state and input position. A TensorFlow checkpoint preserves tracked object state; it does not by itself contain the definition of the entire Python program. Exact resumption therefore needs an explicit policy beyond saving weights.

SavedModel packages exported TensorFlow computations, variables and call signatures for a compatible runtime. A signature specifies input and output names, shapes and dtypes; it does not automatically turn every Python method into an API. In Keras 3, a native .keras archive and a SavedModel export are distinct paths. The consulted pinned Keras implementation stores configuration, weights and optimizer state when present in the native archive; custom components require their own reconstruction rules.

The final example exports a minimal module whose signature accepts a variable-length FP32 vector, reloads its own temporary directory and checks that [2] produces a prediction of 3.6. It needs only one variable and an exported function. A real service must also test preprocessing, output names, boundary cases, consumer compatibility and numerical tolerances. Choosing TensorFlow for its production paths is justified by this checked contract, rather than merely possessing a saved file.

import tempfile
import tensorflow as tf

class Scale(tf.Module):
    def __init__(self):
        super().__init__()
        self.w = tf.Variable(1.8, dtype=tf.float32)

    @tf.function(input_signature=[tf.TensorSpec([None], tf.float32)])
    def serve(self, x):
        return {"prediction": self.w * x}

with tf.device("/CPU:0"), tempfile.TemporaryDirectory() as folder:
    model = Scale()
    tf.saved_model.save(model, folder, signatures={"serving_default": model.serve})
    restored = tf.saved_model.load(folder)
    result = restored.signatures["serving_default"](x=tf.constant([2.]))
    tf.debugging.assert_near(result["prediction"], [3.6])
SavedModel round trip in a temporary directory created by the example; no external model is loaded.
Weights, resumable state and inference interfaces are different artifacts
ArtifactContents and purpose
Weights onlyParameter values; architecture and resumption procedure must still be provided.
CheckpointTracked object state; include the objects needed to resume and reconstruct computation.
.keras archiveConfiguration, weights and optimizer state when present, for rebuilding a compatible Keras model.
SavedModelExported computation, variables and inference signatures for a compatible TensorFlow consumer.

References for this chapter[16][17][18]

ORIGINAL DOCUMENT

Catalog record

2. Low-level software, compilers and training frameworks

TensorFlow tensorflow.org v2.18 — Innovation: 7, Adoption: 9

7/10Innovation
9/10Adoption

Editorial source: Taxonomie des Technologies d'Intelligence Artificielle · § 5883. Addresses restored with dots; innovation and adoption scores remain those of the document.

VERIFY AND EXPLORE

References

Historical scope: TensorFlow 2.18.0, released in October 2024. Sources accessed on November 4, 2026. Code references are pinned to tag 2.18.0; living guides explain mechanisms rather than establish release-specific features. CPU examples are documentary and their values follow from algebra; TensorFlow was neither installed nor run for this dossier.

  1. 01
    TensorFlow 2.18.0 release notes

    Historical source for NumPy 2.0, hermetic CUDA builds, disabled TensorRT support and data options; no local qualification is implied.

    github.com ·
  2. 02
    TensorFlow 2.18 announcement, October 2024

    Dated release context distinguishing TensorFlow changes from Keras changes.

    blog.tensorflow.org ·
  3. 03
    Tensors: shape and dtype

    Living guide to rank, dimensions and broadcasting; used for mechanisms rather than the 2.18 changelog.

    www.tensorflow.org ·
  4. 04
    Keras 3 and its backends

    Living overview of Keras and execution engines; later capabilities are not attributed to 2.18.

    keras.io ·
  5. 05
    Keras loader at TensorFlow tag 2.18.0

    Pinned code distinguishing Keras 3 from the explicitly selected legacy package.

    github.com ·
  6. 06
    Migration to Keras 3

    Guide to backend dependencies, compilation and saving changes.

    keras.io ·
  7. 07
    Traced functions and retracing

    Guide to concrete-function caches, signatures and Python tracing side effects.

    www.tensorflow.org ·
  8. 08
    Polymorphic functions in TensorFlow 2.18.0

    Pinned implementation and contract for traced functions, signatures and explicit compilation.

    github.com ·
  9. 09
    Automatic differentiation

    Guide to variable watching, reverse traversal and missing gradients.

    www.tensorflow.org ·
  10. 10
    GradientTape at tag 2.18.0

    Pinned tape contract covering persistence and gradient computation.

    github.com ·
  11. 11
    Input pipeline performance

    Guide to caching, batching, prefetching and parallelism; its benchmark values are not reproduced here.

    www.tensorflow.org ·
  12. 12
    Input pipelines at tag 2.18.0

    Pinned transformation signatures and behavior, including map options added in 2.18.

    github.com ·
  13. 13
    XLA with a TensorFlow function

    Living guide to explicit compilation; the official redirect to OpenXLA was observed.

    openxla.org ·
  14. 14
    Distributed training

    Guide to strategies, replicas and execution constraints.

    www.tensorflow.org ·
  15. 15
    Loss normalization at tag 2.18.0

    Pinned code describing division by global batch size in a custom distributed loop.

    github.com ·
  16. 16
    Training checkpoints

    Guide to tracked values and the reconstruction required for resumption.

    www.tensorflow.org ·
  17. 17
    SavedModel format

    Guide to exported functions, variables and signatures; distinguish older examples from Keras 3 paths.

    www.tensorflow.org ·
  18. 18
    Keras saving at tag 3.6.0

    Contemporary historical Keras source for native archives and export; not a claim that every TensorFlow 2.18 installation pins Keras 3.6.0.

    github.com ·

Catalog provenance

Taxonomie des Technologies d'Intelligence Artificielle · Google Docs

Source document consulted on . § 5883.

Websites cited in the record

A website’s inclusion in the catalog does not verify the versions, projections or results mentioned in the document.

FROM KNOWLEDGE TO PROJECT

Apply this knowledge to your context.

Scope, architecture, roadmap and notes: keep your decisions in the dedicated space.

Open dedicated space