jax-ml/jax · error · TypeError
Invalid scalar value {x}
Error message
Invalid scalar value {x} What it means
jax.dtypes.scalar_type_of maps a Python/numpy scalar to int/float/complex/bool; anything else (strings, None, arbitrary objects) is not a scalar and raises TypeError. It is used by lax._const when coercing Python values into typed constants.
Source
Thrown at jax/_src/dtypes.py:436
@export
def scalar_type_of(x: Any) -> type:
"""Return the scalar type associated with a JAX value."""
typ = dtype(x)
if typ in _custom_float_dtypes:
return float
elif typ in _intn_dtypes:
return int
elif np.issubdtype(typ, np.bool_):
return bool
elif np.issubdtype(typ, np.integer):
return int
elif np.issubdtype(typ, np.floating):
return float
elif np.issubdtype(typ, np.complexfloating):
return complex
else:
raise TypeError(f"Invalid scalar value {x}")
def scalar_type_to_dtype(typ: type, value: Any = None) -> DType:
"""Return the numpy dtype for the given scalar type.
Raises
------
OverflowError: if `typ` is `int` and the value is too large for int64.
Examples
--------
>>> scalar_type_to_dtype(int)
dtype('int32')
>>> scalar_type_to_dtype(float)
dtype('float32')
>>> scalar_type_to_dtype(complex)
dtype('complex64')
>>> scalar_type_to_dtype(int)View on GitHub (pinned to 1e1c6a8fc0)
Solutions
- Convert inputs to scalars before passing to JAX ops: int(v)/float(v)
- Validate with isinstance(x, (bool, int, float, complex)) (plus numpy scalars) at your API boundary
- Fix data pipeline producing strings/None for numeric fields
Example fix
# before jnp.float32(config['scale']) # scale is '2.0' # after jnp.float32(float(config['scale']))
Defensive patterns
Strategy: type-guard
Validate before calling
assert isinstance(x, (bool, int, float, complex)), f'not a scalar: {x!r}' Type guard
def is_python_scalar(x) -> bool:
return isinstance(x, (bool, int, float, complex)) and not isinstance(x, bool) or isinstance(x, bool) Try / catch
try:
fn(x)
except TypeError:
fn(float(x)) # when a numeric string was intended Prevention
- Coerce config strings to numbers at load
- Reject None before passing into math
When it happens
Trigger: Passing a string, bytes, None, or custom object where a Python scalar is expected, e.g. lax ops building constants from user-supplied values (lax._const -> scalar_type_of).
Common situations: Trace-time constants from config (strings meant to be numbers); None defaults leaking into math; unhashable/non-scalar objects in place of scalars.
Related errors
- iteration over a 0-d array
- Argument to to_dlpack must be a jax.Array, got {type(x)}
- The array passed to from_dlpack must have __dlpack__ and __d
- dtype {dtype!r} not understood
- cond_fun must return a boolean scalar, but got output type(s
AI-assisted analysis of jax-ml/jax@1e1c6a8fc0 (2026-08-27).
Data as JSON: /api/errors/cb53b611fee790a7.
Report an issue: GitHub.