Variables

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

A tf.Variable is a tensor-like object whose value can be changed in place. Model parameters, optimizer slots, counters and running statistics are variables, while data and activations are the immutable tensors that flow between them. This page covers creation, assignment, attributes, device placement, automatic gradient tracking, interaction with tf.function, and the relation to Keras variables. The gradient mechanics are on Automatic Differentiation, the container class tf.Module on Modules, and persistence on Checkpoints.

It targets Python 3.13, TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is upcoming and not covered), 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 analogue is nn.Parameter on nn.Module.

Creating and using variables

import tensorflow as tf

w = tf.Variable([[1.0, 2.0], [3.0, 4.0]], name="w")      # dtype float32 inferred
b = tf.Variable(tf.zeros([2]), trainable=True, name="b")
step = tf.Variable(0, dtype=tf.int64, trainable=False, name="step")

print(w.shape, w.dtype, w.name)        # (2, 2) <dtype: 'float32'> w:0
print(w.numpy())                       # [[1. 2.] [3. 4.]] as a NumPy array
print(tf.reduce_sum(w))                # tf.Tensor(10.0, shape=(), dtype=float32)
print(tf.convert_to_tensor(w))         # snapshot as an immutable tensor

The initial value may be a tensor, a NumPy array, a Python list or a callable that returns one (useful for deferring expensive initialization). The dtype and, unless you pass shape=, the shape are fixed at creation. Variables created with trainable=False are excluded from the default gradient watch list, which is how a step counter or a frozen layer is expressed. Passing shape=tf.TensorShape(None) creates a variable of unknown shape, a rarely needed feature.

Assigning

Variables are mutated with methods, never with Python rebinding:

v = tf.Variable([1.0, 2.0, 3.0])

v.assign([4.0, 5.0, 6.0])              # replace the whole value; shape must match
v.assign_add([1.0, 1.0, 1.0])          # in place +=
v.assign_sub([0.5, 0.5, 0.5])
v[0].assign(10.0)                      # slice assignment via the indexing syntax
v.scatter_nd_update([[1]], [99.0])     # sparse updates by index

try:
    v.assign([1.0, 2.0])               # wrong shape
except (ValueError, tf.errors.InvalidArgumentError) as err:
    print(type(err).__name__)          # ValueError

a = tf.Variable([1.0, 2.0])
b = tf.Variable(a)                     # copies the value: b is independent of a
a.assign([0.0, 0.0])
print(b.numpy())                       # [1. 2.]

Python augmented assignment does not work on a variable: in TensorFlow 2.21 v += 1, v -= 1, v *= 2 and v /= 2 raise a RuntimeError whose message names the replacement, for example variable += value is reported as not supported, with the advice to use variable.assign_add(value). Use the explicit assign family.

Two further points. Creating a variable from another variable copies the value, so the two never alias. And assign returns the variable (or an op in graph mode), so assignments are traced as stateful ops with automatic control dependencies inside tf.function.

Placement and synchronization

with tf.device("CPU:0"):
    big_table = tf.Variable(tf.random.normal([100_000, 128]))   # keep a large table off the GPU

print(big_table.device)

# Aggregation and synchronization matter under tf.distribute
counter = tf.Variable(
    0,
    trainable=False,
    synchronization=tf.VariableSynchronization.ON_READ,
    aggregation=tf.VariableAggregation.SUM,
)

By default a variable is placed on the first available GPU when one exists and consumes memory there for its whole lifetime; scoping the creation with tf.device overrides that. tf.config.set_soft_device_placement(True) lets TensorFlow fall back to another device when an op has no kernel on the requested one. The synchronization and aggregation arguments describe how replicas of a variable are kept consistent under tf.distribute (mirrored, on-read for metrics and counters); they are ignored in single-device code. Details are on Distributed Training, and device selection in general on Devices.

Variables and gradients

tf.GradientTape watches trainable variables automatically; ordinary tensors must be watched explicitly.

x = tf.Variable(3.0)
frozen = tf.Variable(5.0, trainable=False)

with tf.GradientTape() as tape:
    y = x ** 2 + frozen ** 2
print(tape.gradient(y, [x, frozen]))     # [6.0, None]: untrainable variable is not watched

with tf.GradientTape(watch_accessed_variables=False) as tape:
    tape.watch(frozen)                   # opt in explicitly
    y = frozen * 2.0
print(tape.gradient(y, frozen))          # 2.0

A gradient of None means the variable was not connected to the output through differentiable ops; common causes are assigning with assign inside the tape (which cuts the path), converting to NumPy, casting to an integer dtype or using an untrainable variable. A minimal training step keeps the weights as variables and updates them with assign_sub:

w = tf.Variable(tf.random.normal([3, 1]))
b = tf.Variable(tf.zeros([1]))

def step(x, y, lr=0.1):
    with tf.GradientTape() as tape:
        loss = tf.reduce_mean((tf.matmul(x, w) + b - y) ** 2)
    gw, gb = tape.gradient(loss, [w, b])
    w.assign_sub(lr * gw)
    b.assign_sub(lr * gb)
    return loss

The complete version with a tf.Module is on A Training Loop with TF Core.

Variables inside tf.function

class Counter(tf.Module):
    def __init__(self):
        self.n = tf.Variable(0)            # created once in __init__

    @tf.function
    def __call__(self):
        self.n.assign_add(1)
        return self.n

c = Counter()
print(c().numpy(), c().numpy())            # 1 2

@tf.function
def bad():
    v = tf.Variable(1.0)                   # a new variable on each trace is an error
    return v

# bad() raises ValueError on the second trace
@tf.function
def good(x):
    if not hasattr(good, "v"):
        good.v = tf.Variable(1.0)          # lifted out on the first call only
    return good.v * x

A traced function may only create a variable on its first call; later traces must reuse it. The safest style is to create variables in __init__ of a tf.Module or Keras layer (or in build) and only read or assign them inside the function. Automatic control dependencies guarantee that stateful ops run in program order inside a function, so reads and writes of a variable behave like eager code. See Graphs and tf.function for retracing rules.

Keras 3 variables

Keras 3 defines its own keras.Variable, a backend-independent wrapper: on the TensorFlow backend it holds a tf.Variable, on JAX and PyTorch a corresponding native object. Layers create them through self.add_weight(...), and model.weights, trainable_weights and non_trainable_weights list them.

import keras

layer = keras.layers.Dense(4)
layer.build((None, 8))
for v in layer.weights:
    print(v.path, v.shape, v.trainable)    # dense/kernel (8, 4) True, dense/bias (4,) True

v = keras.Variable(initializer=keras.initializers.Zeros(), shape=(3,), dtype="float32", trainable=False, name="state")
v.assign([1.0, 2.0, 3.0])
print(v.value)                              # the backend variable: a tf.Variable on TensorFlow
print(keras.ops.convert_to_numpy(v))

Inside a custom layer, state must go through Keras variables (not plain Python attributes or raw tf.Variable created outside tracking) if the layer is to be saved, run under JAX or have its weights listed; see Subclassing and Custom Layers and Keras Multi-Backend. Keras 2 code that stored arbitrary tf.Variable objects on layers sometimes relied on tracking behaviour that changed in Keras 3; see Migrating from Keras 2 to Keras 3.

Pitfalls

  • Variables are not thread-safe for concurrent updates unless you use the atomic methods such as assign_add; read-modify-write built from numpy() is racy and also not traceable.

  • tf.Variable objects are not hashable by value in TensorFlow 2: equality is identity-based, and variables cannot be used as dictionary keys when variable equality is enabled; use v.ref() for a hashable reference.

  • A variable captured by a tf.function is passed by reference; reassigning the Python name later does not change what the traced graph reads.

  • Reading v.numpy() in a loop forces a device sync and a copy; keep the loop in a tf.function when performance matters.

  • Optimizer state (momentum, Adam moments) is held in optimizer variables and must be saved along with the model weights to resume training.

  • Older TF1 code using tf.get_variable, variable_scope and tf.global_variables_initializer is obsolete; TensorFlow 2 variables are initialized on creation, and sharing is done by sharing Python objects.