keras-team/keras · error · ValueError
You are attempting to initialize a variable while in a…
Error message
You are attempting to initialize a variable while in a stateless scope. This is disallowed. Make sure that all variables are initialized before you start using your layer/model objects.
What it means
Error "You are attempting to initialize a variable while in a stateless scope. This is disallowed. Make sure that all variables are initialized before you start using your layer/model objects." thrown in keras-team/keras.
Solutions
- Move variable creation and initialization out of stateless scopes: build your layer/model (model.build(input_shape) or one eager forward pass) before entering stateless execution such as jax.jit or tf.function.
- Do not create Keras variables inside traced functions; create them eagerly in build() so initialization completes before tracing.
- If wrapping code in a stateless_scope, initialize all variables before entering the scope.
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at keras/src/backend/common/variables.py:226 when the library encounters an invalid state.
Common situations: See trigger scenarios.
AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25).
Data as JSON: /api/errors/a106f0b2000a6f3b.
Report an issue: GitHub.
Appendix: source
Thrown at keras/src/backend/common/variables.py:226
if callable(initializer):
self._shape = self._validate_shape(shape)
self._initialize_with_initializer(initializer)
else:
self._initialize(initializer)
self._shape = self._validate_shape(self._value.shape)
self._ndim = len(self._shape)
def _deferred_initialize(self):
if self._value is not None:
# If NNX is enabled, it's possible the variable was already
# initialized by a concrete call. In this case, _deferred_initialize
# returns early and does not raise an error.
if config.is_nnx_enabled():
return
raise ValueError(f"Variable {self.path} is already initialized.")
if in_stateless_scope():
raise ValueError(
"You are attempting to initialize a variable "
"while in a stateless scope. This is disallowed. "
"Make sure that all variables are initialized "
"before you start using your layer/model objects."
)
self._initialize_with_initializer(self._initializer)
self._initializer = None
def _validate_shape(self, shape):
shape = standardize_shape(shape)
if None in shape:
raise ValueError(
"Shapes used to initialize variables must be "
"fully-defined (no `None` dimensions). Received: "
f"shape={shape} for variable path='{self.path}'"
)
return shape
View on GitHub (pinned to 7a34a03db6)