keras-team/keras · error · ValueError

Invalid reference variable in StatelessScope: all keys in…

Error message

Invalid reference variable in StatelessScope: all keys in argument `mapping` must be Variable instances. Received instead: {k}

What it means

Raised in StatelessScope.__init__ while validating the state_mapping argument: every key must be a Keras Variable (the reference variable whose state is being replaced). The loop hits a key of another type, meaning the mapping was built with a non-Variable placeholder as reference.

Solutions

  1. Build the mapping as {variable: value} where each key is the actual keras Variable instance
  2. Retrieve the real layer/model variables (e.g. via .variables) instead of names or tensors as keys
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at keras/src/backend/common/stateless_scope.py:51 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/e8f0350eb81122ba. Report an issue: GitHub.

Appendix: source

Thrown at keras/src/backend/common/stateless_scope.py:51

    """

    def __init__(
        self,
        state_mapping=None,
        collect_losses=False,
        initialize_variables=True,
    ):
        from keras.src import backend
        from keras.src.backend.common.variables import Variable

        self.collect_losses = collect_losses
        self.initialize_variables = initialize_variables
        self.losses = []
        self.state_mapping = {}
        state_mapping = state_mapping or {}
        for k, v in state_mapping:
            if not isinstance(k, Variable):
                raise ValueError(
                    "Invalid reference variable in StatelessScope: "
                    "all keys in argument `mapping` must be Variable "
                    f"instances. Received instead: {k}"
                )
            if isinstance(v, Variable):
                v = backend.cast(v.value, dtype=k.dtype)
            else:
                v = backend.convert_to_tensor(v, dtype=k.dtype)
            if k.shape != v.shape:
                raise ValueError(
                    "Invalid variable value in StatelessScope: "
                    "all values in argument `mapping` must be tensors with "
                    "a shape that matches the corresponding variable shape. "
                    f"For variable {k}, received invalid value {v} with shape "
                    f"{v.shape}."
                )
            self.state_mapping[id(k)] = v

View on GitHub (pinned to 7a34a03db6)