jax icon indicating copy to clipboard operation
jax copied to clipboard

jax.numpy trim_zeros not compatible with jax.jit , does not document this limitation

Open anna-researcher opened this issue 5 months ago • 0 comments

Description

jnp.trim_zeros works correctly in eager mode but raises ConcretizationTypeError under jax.jit. Unlike similar JAX functions with data-dependent output sizes (jnp.nonzero, jnp.unique, jnp.compress, jnp.extract) which explicitly document their JIT incompatibility and provide a size= workaround, jnp.trim_zeros has no mention of this limitation in its docstring and provides no workaround.

Minimal Reproducer

import jax
import jax.numpy as jnp

t = jnp.array([0.0, 1.0, 2.0, 0.0])

def f(x):
    return jnp.trim_zeros(x)

print(f(t))      # works: [1. 2.]
jax.jit(f)(t)    # crashes

Error

jax.errors.ConcretizationTypeError: Abstract tracer value encountered where concrete value is expected: traced array with shape float32[4]
Error arose in the `filt` argument of trim_zeros()
The error occurred while tracing the function f at <string>:4 for jit. This concrete value was not available in Python because it depends on the value of the argument x.

Root Cause

In lax_numpy.py, trim_zeros calls core.concrete_or_error() unconditionally on the input array, making it fundamentally incompatible with JIT tracing. The output size depends on data values, which cannot be resolved at trace time.

Unlike jnp.nonzero, jnp.unique, and jnp.compress which document this limitation clearly and offer a size= parameter as a JIT-compatible escape hatch, jnp.trim_zeros provides neither a warning nor a workaround. A user reading the docstring has no indication the function will silently work in eager mode but crash under jax.jit.

Expected Behavior

Either:

  1. The docstring should explicitly warn that jnp.trim_zeros is not JIT-compatible, consistent with how jnp.nonzero, jnp.unique, and jnp.compress document their JIT limitations, OR
  2. A size= parameter should be added (similar to jnp.nonzero(size=)) to enable JIT-compatible usage with static output shapes.

System info (python version, jaxlib version, accelerator, etc.)

jax:    0.10.1
jaxlib: 0.10.1
numpy:  2.4.6
python: 3.12.13 | packaged by Anaconda, Inc. | (main, Mar 19 2026, 20:20:58) [GCC 14.3.0]
device info: cpu-1, 1 local devices
process_count: 1
platform: uname_result(system='Linux', node='unicorn-login-01', release='6.8.0-110-generic', version='#110-Ubuntu SMP PREEMPT_DYNAMIC Thu Mar 19 15:09:20 UTC 2026', machine='x86_64')
JAX_PLATFORMS=cpu

anna-researcher avatar Jun 19 '26 23:06 anna-researcher