keras-team/keras · error · ValueError

Expect `mesh` to be an instance of `DeviceMesh`. Received…

Error message

Expect `mesh` to be an instance of `DeviceMesh`. Received: mesh={device_mesh} (of type {type(device_mesh)})

What it means

Raised by the constructor path in keras/src/distribution/distribution_lib.py: the distribution was initialized with a device_mesh argument that is not an instance of DeviceMesh (e.g. a raw list of devices, a string, or a mesh from a different class). The layout logic requires a real DeviceMesh to read axis names and shape, so the type guard fails.

Solutions

  1. Create a DeviceMesh first and pass it: mesh = DeviceMesh(shape, axis_names, devices); Distribution(mesh)
  2. Pass devices=[...] instead so the constructor builds the mesh for you
  3. Fix imports so you pass keras.distribution.DeviceMesh, not a lookalike
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at keras/src/distribution/distribution_lib.py:478 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/882ee6197b0dedd0. Report an issue: GitHub.

Appendix: source

Thrown at keras/src/distribution/distribution_lib.py:478

            processes in a multi-process setting. Set to `False` if the dataset
            is already sharded across hosts.  Defaults to `True`.
    """

    def __init__(self, device_mesh=None, devices=None, auto_shard_dataset=True):
        if device_mesh:
            self._initialize_with_device_mesh(device_mesh, auto_shard_dataset)
        elif devices:
            self._initialize_mesh_from_devices(devices, auto_shard_dataset)
        else:
            self._initialize_mesh_from_list_devices(auto_shard_dataset)

    @property
    def num_model_replicas(self):
        return self.device_mesh.devices.size

    def _initialize_with_device_mesh(self, device_mesh, auto_shard_dataset):
        if not isinstance(device_mesh, DeviceMesh):
            raise ValueError(
                "Expect `mesh` to be an instance of `DeviceMesh`. "
                f"Received: mesh={device_mesh} (of type {type(device_mesh)})"
            )
        super().__init__(
            device_mesh, device_mesh.axis_names[0], auto_shard_dataset
        )
        if self.device_mesh.devices.ndim != 1:
            warnings.warn(
                "Expect the input mesh to be 1D, but received "
                "mesh.devices.ndim=%d. "
                "The first axis will be used for data-parallel sharding.",
                device_mesh.devices.ndim,
            )

    def _initialize_mesh_from_devices(self, devices, auto_shard_dataset):
        devices = np.array(devices)
        device_mesh = DeviceMesh(
            shape=devices.shape,

View on GitHub (pinned to 7a34a03db6)