keras-team/keras · error · ValueError
Variable is already initialized.
Error message
Variable {self.path} is already initialized. What it means
Raised by Variable._deferred_initialize when deferred (lazy) initialization is triggered but the variable already holds a concrete value. This typically happens when a variable created under a stateless scope (e.g. inside a functional call or jax.jit trace) was already initialized by a concrete forward pass, and the deferred init path then tries to initialize it again. The NNX-enabled code path above returns early in exactly this situation; with NNX disabled, Keras treats re-initialization as a bug and raises.
Solutions
- Avoid triggering variable creation/initialization paths twice on the same variable; create variables once (typically in build()) and reuse them.
- If the variable was already initialized by a concrete call, skip manual re-initialization instead of forcing _deferred_initialize again.
- On the JAX backend, enabling NNX (keras.config.set_nnx_enabled(True)) makes this case return early instead of raising.
- Do not call private initialization APIs (_initialize, _deferred_initialize) on variables managed by Keras.
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at keras/src/backend/common/variables.py:223 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/707fb571bcc5fe32.
Report an issue: GitHub.
Appendix: source
Thrown at keras/src/backend/common/variables.py:223
"(with a `shape` and `initializer` argument)."
)
else:
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}'"View on GitHub (pinned to 7a34a03db6)