keras-team/keras · error · ValueError

Expected all elements in `variables` to be `tf.Variable`…

Error message

Expected all elements in `variables` to be `tf.Variable` instances. Found instead the following types: {list(set(type(v) for v in variables))}

What it means

Element-type check in add_variable_collection() after the container check passes: every element of `variables` must be a tf.Variable (or a backend Variable convertible to one) because the archive registers them directly on the tf.Trackable; non-variable objects (raw tensors, ints, layers) are rejected with their offending types listed.

Solutions

  1. Pass only tf.Variable / backend Variable instances, e.g. model.optimizer.variables or layer.weights
  2. Convert raw tensors to tf.Variable before adding them to the collection
  3. Remove non-trainable bookkeeping objects (layers, dicts, ints) from the list
Defensive patterns

Strategy: type-guard

When it happens

Trigger: Thrown at keras/src/export/saved_model_export_archive.py:234 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/80240e38c932772f. Report an issue: GitHub.

Appendix: source

Thrown at keras/src/export/saved_model_export_archive.py:234

        export_archive.write_out("path/to/location")

        # Reload the object
        revived_object = tf.saved_model.load("path/to/location")
        # Retrieve the variables
        optimizer_variables = revived_object.optimizer_variables
        ```
        """
        if not isinstance(variables, (list, tuple, set)):
            raise ValueError(
                "Expected `variables` to be a list/tuple/set. "
                f"Received instead object of type '{type(variables)}'."
            )
        # Ensure that all variables added are either tf.Variables
        # or Variables created by Keras 3 with the TF or JAX backends.
        if not all(
            isinstance(v, (tf.Variable, backend.Variable)) for v in variables
        ):
            raise ValueError(
                "Expected all elements in `variables` to be "
                "`tf.Variable` instances. Found instead the following types: "
                f"{list(set(type(v) for v in variables))}"
            )
        if backend.backend() == "jax":
            variables = tree.flatten(
                tree.map_structure(self._convert_to_tf_variable, variables)
            )
        setattr(self._tf_trackable, name, list(variables))

    def write_out(self, filepath, options=None, verbose=True):
        """Write the corresponding SavedModel to disk.

        Arguments:
            filepath: `str` or `pathlib.Path` object.
                Path where to save the artifact.
            options: `tf.saved_model.SaveOptions` object that specifies
                SavedModel saving options.

View on GitHub (pinned to 7a34a03db6)