keras-team/keras · error · ValueError

`sparse=True` can only be used with the TensorFlow backend.

Error message

`sparse=True` can only be used with the TensorFlow backend.

What it means

Sparse output for HashedCrossing is implemented only for the TensorFlow backend (it returns tf.SparseTensors). Constructing the layer with sparse=True under jax or torch is rejected.

Source

Thrown at keras/src/layers/preprocessing/hashed_crossing.py:92

        num_bins,
        output_mode="int",
        sparse=False,
        name=None,
        dtype=None,
        **kwargs,
    ):
        if not tf.available:
            raise ImportError(
                "Layer HashedCrossing requires TensorFlow. "
                "Install it via `pip install tensorflow`."
            )

        if output_mode == "int" and dtype is None:
            dtype = "int64"

        super().__init__(name=name, dtype=dtype)
        if sparse and backend.backend() != "tensorflow":
            raise ValueError(
                "`sparse=True` can only be used with the TensorFlow backend."
            )

        argument_validation.validate_string_arg(
            output_mode,
            allowable_strings=("int", "one_hot"),
            caller_name=self.__class__.__name__,
            arg_name="output_mode",
        )

        self.num_bins = num_bins
        self.output_mode = output_mode
        self.sparse = sparse
        self._allow_non_tensor_positional_args = True
        self._convert_input_args = False
        self.supports_jit = False

    def compute_output_shape(self, input_shape):

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Set sparse=False and accept dense output
  2. Switch to the tensorflow backend (KERAS_BACKEND=tensorflow) if sparse tensors are required
  3. Post-process dense output into your framework's sparse representation downstream

Example fix

// before
KERAS_BACKEND=jax ... layer = HashedCrossing(num_bins=1000, sparse=True)
// after
layer = HashedCrossing(num_bins=1000, sparse=False)
# or run with KERAS_BACKEND=tensorflow
Defensive patterns

Strategy: validation

Validate before calling

from keras.src import backend
assert backend.backend() == "tensorflow" or not sparse, "sparse=True requires TF backend"

Type guard

def sparse_allowed():
    from keras.src import backend
    return backend.backend() == "tensorflow"

Try / catch

catch ValueError and rerun with sparse=False, converting the dense output to sparse downstream if needed

Prevention

When it happens

Trigger: layers.HashedCrossing(num_bins=..., sparse=True) while keras.config.backend() is 'jax' or 'torch'.

Common situations: Setting KERAS_BACKEND=jax or torch and constructing layers.Hashing/HashedCrossing with sparse=True to save memory on wide one-hot features.

Related errors


AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25). Data as JSON: /api/errors/127b0493c7384123. Report an issue: GitHub.