Modules (tf.Module)

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

tf.Module is the small base class that TensorFlow layers and Keras models are built on. It does one job: it walks the attributes of an object and collects every tf.Variable and nested tf.Module it finds, so that you can ask for variables, trainable_variables and submodules, save the object, and hand its parameters to an optimizer without keeping a manual list. This page covers that collection mechanism, parameterised layers, freezing, tf.function on methods and the two ways to persist a module. The variable type itself is on Variables, gradients on Automatic Differentiation, graph compilation on Graphs and tf.function, and a complete loop that trains a module on A Training Loop with TF Core.

It targets Python 3.13 and TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is labelled "upcoming") and was checked against the official documentation on 2026-10-30. Examples were run on Python 3.13 with TensorFlow 2.21 and Keras 3.15 (CPU) on 2026-10-31. The PyTorch counterpart is nn.Module, and the framework-neutral picture of parameters and layers is in Neural Network Fundamentals.

What a module is

A module is any Python object whose class inherits from tf.Module. Variables and other modules assigned as attributes (directly, or inside lists, tuples and dicts held by attributes) become part of the module’s tracked state. keras.layers.Layer and keras.Model extend this idea with build-on-first-call, weights bookkeeping, losses and metrics, so understanding tf.Module explains the lower layer of everything in Subclassing and Custom Layers.

import tensorflow as tf

class SimpleModule(tf.Module):
    def __init__(self, name=None):
        super().__init__(name=name)
        self.train_me = tf.Variable(5.0, name="train_me")
        self.do_not_train_me = tf.Variable(5.0, trainable=False, name="do_not_train_me")

    def __call__(self, x):
        return self.train_me * x + self.do_not_train_me

m = SimpleModule(name="simple")
print(m(tf.constant(10.0)).numpy())               # 55.0
print([v.name for v in m.variables])               # ['do_not_train_me:0', 'train_me:0'] (sorted by attribute name)
print([v.name for v in m.trainable_variables])     # ['train_me:0']
print(m.name)                                      # simple

The three collections behave as follows:

Property What it returns

variables

every tf.Variable owned by the module and, recursively, by its submodules, trainable or not

trainable_variables

the subset whose trainable flag is True; this is what you differentiate against and pass to an optimizer

submodules

the nested tf.Module instances, found recursively

Always call super().__init__() first; the base constructor sets up the name and the naming scope, and forgetting it makes the class behave oddly rather than fail with a clear message. The optional name argument must be a valid Python identifier-like string and is used to prefix variable names in graphs and checkpoints.

Attribute discovery and its limits

The collection is performed lazily every time you read a property, by inspecting the instance attributes. That has consequences worth knowing:

  • Variables stored in plain Python containers (list, tuple, dict) held as attributes are found. A variable that is only referenced from a local variable, a closure or a global is not part of the module.

  • Variables created after the properties were read are included on the next read, which is what makes lazily built layers work.

  • A cycle, such as a child holding a reference back to the parent, is handled; each variable appears once.

  • trainable_variables is recomputed on every read, so replacing a variable with a non-trainable one (see below) takes effect immediately.

A parameterised layer and a model

A layer that owns weights is the standard pattern. Creating the variables in __init__ works when the sizes are known; creating them on first call, guarded by a flag, supports unknown input width.

class Dense(tf.Module):
    def __init__(self, out_features, name=None):
        super().__init__(name=name)
        self.out_features = out_features
        self.is_built = False

    def __call__(self, x):
        if not self.is_built:
            self.w = tf.Variable(tf.random.normal([x.shape[-1], self.out_features]), name="w")
            self.b = tf.Variable(tf.zeros([self.out_features]), name="b")
            self.is_built = True
        return tf.matmul(x, self.w) + self.b


class Sequential(tf.Module):
    def __init__(self, name=None):
        super().__init__(name=name)
        self.dense_1 = Dense(out_features=3)
        self.dense_2 = Dense(out_features=2)

    def __call__(self, x):
        x = self.dense_1(x)
        return self.dense_2(x)

model = Sequential(name="the_model")
print(model(tf.constant([[2.0, 2.0, 2.0]])))       # shape (1, 2)
print(len(model.variables))                         # 4: w and b of two layers
print([type(s).__name__ for s in model.submodules]) # ['Dense', 'Dense']

Reading model.variables before the first call returns an empty tuple for the lazily built layers, because the weights do not exist yet. Call the model once on a representative batch, or on a tf.TensorSpec-shaped dummy input, before building an optimizer or restoring a checkpoint into it. Keras formalises this with build(), compute_output_spec and symbolic inputs.

A module is not a Keras layer: it has no losses, no trainable property to flip, no get_config and no automatic input casting. In exchange it is tiny, framework-neutral and easy to read, which is why TensorFlow’s own guides use it to show how training works.

Freezing variables

A variable is excluded from trainable_variables if it was created with trainable=False. The flag is fixed at creation: tf.Variable.trainable is read-only, and v.trainable = False raises AttributeError: property 'trainable' of 'ResourceVariable' object has no setter. To freeze a block after construction, replace its variables with non-trainable copies, which keep the current values:

layer = model.dense_1
layer.w = tf.Variable(layer.w, trainable=False, name="w")
layer.b = tf.Variable(layer.b, trainable=False, name="b")

print(len(model.variables))                         # 4
print(len(model.trainable_variables))               # 2: only dense_2 remains

The simpler alternative is to leave the module unchanged and pass only the variables you want to train to the tape and the optimizer, for example model.dense_2.trainable_variables.

Replacing the variables changes which ones a GradientTape watches automatically and which ones trainable_variables returns. An existing optimizer still holds its slots for the old variable objects, so rebuild it or re-pass the list after freezing, and restore checkpoints after the replacement so the new objects receive the values. Keras layers expose the same idea through layer.trainable; see Transfer Learning and Fine-Tuning for the recipe and the BatchNorm caveat.

Methods with tf.function

A module method is an ordinary Python function until you decorate it. Decorating __call__ or another method with tf.function traces it into a graph that is cached per input signature, with the module’s variables captured by reference.

class FastModule(tf.Module):
    def __init__(self):
        super().__init__()
        self.w = tf.Variable(tf.random.normal([4, 2]))

    @tf.function(input_signature=[tf.TensorSpec(shape=[None, 4], dtype=tf.float32)])
    def __call__(self, x):
        return tf.matmul(x, self.w)

fm = FastModule()
y = fm(tf.ones([3, 4]))                              # traced once for any batch size
y2 = fm(tf.ones([10, 4]))                            # no retrace

Points that matter in practice:

  • Without input_signature, each distinct combination of shapes, dtypes and Python argument values produces a new graph, which is the retracing problem described on the graphs page. A signature with None for the batch dimension fixes that for the common case.

  • Only functions that are traced, or that were called at least once before saving, are exported with a SavedModel; the signature form is the reliable way to export a function you have not yet called.

  • Variables must be created on the first trace only. Creating a new tf.Variable on a later call inside a tf.function raises an error, which is why the is_built pattern above is done outside a compiled method or guarded.

  • Python side effects (printing, appending to a list) run only during tracing; use tf.print for per-call output.

Names and name scopes

Each module gets a name, defaulting to a snake-case version of the class name, and its variables are created inside a name scope with that prefix, so you see the_model/dense/w:0 style names in graphs and TensorBoard. Names are cosmetic in eager mode but become keys in the legacy name-based checkpoint format, so do not rely on them for anything other than readability. Object-based checkpoints, described next, key variables by attribute path instead. The module API also exposes tf.Module.with_name_scope, a decorator for methods that should run inside the module’s scope so that ops they create are grouped in the graph viewer.

Saving state: checkpoints

tf.train.Checkpoint saves and restores the values of the variables reachable from the objects you give it, keyed by the attribute path that leads to them.

ckpt = tf.train.Checkpoint(model=model)
path = ckpt.write("ckpt/my_checkpoint")             # writes .index and .data-xxxxx-of-xxxxx files
print(tf.train.list_variables(path)[:3])            # names and shapes stored

new_model = Sequential(name="the_model")
new_model(tf.constant([[2.0, 2.0, 2.0]]))           # build the variables first
tf.train.Checkpoint(model=new_model).restore(path)  # values copied into the matching Python object

A checkpoint contains values only, not computation, so the Python class must exist at restore time and have the same attribute structure. If a variable has not been created yet when restore runs, TensorFlow defers the assignment until the variable appears (restore-on-create), but building first and then restoring makes errors obvious. The full story, including CheckpointManager and assert_consumed, is on Training Checkpoints.

Saving the computation: SavedModel

tf.saved_model.save stores the traced functions and the weights, so the model can be served or loaded without the original Python code.

tf.saved_model.save(fm, "saved/fast_module")
loaded = tf.saved_model.load("saved/fast_module")
print(loaded(tf.ones([2, 4])).shape)                 # (2, 2)
print(isinstance(loaded, FastModule))                # False: it is a restored object, not your class

The directory holds saved_model.pb (the graph and function definitions) and a variables/ checkpoint. The loaded object is a generic restored object that exposes the saved functions and variables; you cannot add a new input signature to it, and Python methods that were never traced are absent. Signatures, tf.saved_model.SaveOptions and the saved_model_cli tool are on SavedModel and Signatures. For Keras models the recommended single-file format is .keras and the SavedModel for serving is produced by model.export(); both are on Saving Keras Models.

Choosing between tf.Module and Keras

Need tf.Module keras.Layer / keras.Model

Track variables and submodules

yes

yes

Build weights from input shape

manual

build() called for you

Regularisation losses, masks, training flag

manual

built in

compile, fit, callbacks

no

yes

Save with config and reload by class

no

.keras format

Runs on several backends

no, TensorFlow only

yes, with Keras 3 and keras.ops

A reasonable rule is to use tf.Module for small research code, tests and anything that needs exactly TensorFlow semantics, and Keras for everything that looks like a standard network. The two compose: a Keras layer can hold a tf.Module, and the Keras 3 TensorFlow backend tracks tf.Variable objects through keras.Layer attributes. The decision from the framework point of view is in Choosing a Framework.

Common pitfalls

  • Forgetting super().__init__() leaves the module without its name scope and tracking machinery.

  • Variables created in a method after a tf.function has traced it will not be seen by the compiled graph the way you expect; create state eagerly or on the first call outside the graph.

  • Storing tensors, not variables, as attributes: a plain tf.constant is not tracked or saved. If it must persist and not train, make it tf.Variable(..., trainable=False).

  • Reading model.variables before building returns nothing, so an optimizer created from an empty list silently trains nothing.

  • Expecting tf.saved_model.load to return your class. It returns a restored object; use a checkpoint if you want values back inside your own class.

  • Mixing Keras 2 era habits: in Keras 3 the weights live on keras.Variable objects, and the relationship to tf.Variable depends on the backend. See Keras 3 Overview.