jax-ml/jax · error · ValueError

x and y cannot be broadcast together.

Error message

x and y cannot be broadcast together.

What it means

After rank equality is established, the outer axes (all axes except the transform axis) of x and y must be mutually broadcastable (same length or 1). If not, jnp.broadcast_shapes raises internally and it is re-raised with this clearer message.

Source

Thrown at jax/_src/scipy/signal.py:674

  if y is None:
    check_arraylike('spectral_helper', x)
    x, = promote_dtypes_inexact(x)
    y_arr = x  # place-holder for type checking
    outershape = tuple_delete(x.shape, axis)
  else:
    if mode != 'psd':
      raise ValueError("two-argument mode is available only when mode=='psd'")
    check_arraylike('spectral_helper', x, y)
    x, y_arr = promote_dtypes_inexact(x, y)
    if x.ndim != y_arr.ndim:
      raise ValueError("two-arguments must have the same rank ({x.ndim} vs {y.ndim}).")
    # Check if we can broadcast the outer axes together
    try:
      outershape = jnp.broadcast_shapes(tuple_delete(x.shape, axis),
                                        tuple_delete(y_arr.shape, axis))
    except ValueError as err:
      raise ValueError('x and y cannot be broadcast together.') from err

  result_dtype = dtypes.to_complex_dtype(x.dtype)
  freq_dtype = np.finfo(result_dtype).dtype

  nperseg_int: int = 0
  nfft_int: int = 0
  noverlap_int: int = 0

  if nperseg is not None:  # if specified by user
    nperseg_int = core.concrete_or_error(
        int, nperseg, "nperseg of windowed-FFT")
    if nperseg_int < 1:
      raise ValueError('nperseg must be a positive integer')
  # parse window; if array like, then set nperseg = win.shape
  win, nperseg_int = signal_helper._triage_segments(
      window, nperseg if nperseg is None else nperseg_int,
      input_length=x.shape[axis], dtype=x.dtype)

View on GitHub (pinned to 1e1c6a8fc0)

Solutions

  1. Slice or reshape both inputs to matching outer dimensions
  2. Pad/repeat the smaller outer dim with jnp.broadcast_to where semantically valid
  3. Add an assertion on outer shapes before calling csd

Example fix

// before
f, Pxy = jax.scipy.signal.csd(x, y)  # (16,N) vs (8,N)
// after
n = min(x.shape[0], y.shape[0])
f, Pxy = jax.scipy.signal.csd(x[:n], y[:n])
Defensive patterns

Strategy: validation

Validate before calling

outershape = jnp.broadcast_shapes(x.shape[:-1], y.shape[:-1])  # raises early if incompatible
x, y = jnp.broadcast_to(x, outershape + x.shape[-1:]), jnp.broadcast_to(y, outershape + y.shape[-1:])

Try / catch

try:
    f, P = jax.scipy.signal.csd(x, y)
except ValueError as e:
    if 'broadcast' in str(e):
        n = min(x.shape[0], y.shape[0])
        f, P = jax.scipy.signal.csd(x[:n], y[:n])
    else:
        raise

Prevention

When it happens

Trigger: csd with x shape (16, 1000) and y shape (8, 1000) — channel counts 16 vs 8 cannot broadcast.

Common situations: Multichannel recordings with mismatched channel counts; batches whose leading dims drifted apart after slicing.

Related errors


AI-assisted analysis of jax-ml/jax@1e1c6a8fc0 (2026-08-27). Data as JSON: /api/errors/84ab41266c762cb7. Report an issue: GitHub.