TECHNOLOGY

JAX boolean masking under JIT: preserve shape when the selected count is data-dependent

In this article
THE QUICK TAKE

Selecting values into a shorter array is different from masking values in a fixed-shape calculation.

Locate the unknown output dimension

A quality filter keeps embeddings whose score passes a threshold and then computes a sum. The input batch shape is known, but the number of selected rows depends on the scores. The JAX error reference explains why non-concrete boolean indexing can fail under JIT: the shortened array’s size is not known from its ordinary static shape contract. The comparison itself is not necessarily the unsupported part.

Ask whether compaction is actually required

If the consumer only needs a masked sum, constructing a shorter intermediate array may be unnecessary. The where reference describes selecting between broadcast-compatible values. Preserve the original shape and replace excluded contributions with an appropriate neutral value. That rewrite solves a different problem from returning a genuinely variable-length list of selected embeddings to another system; the latter still needs an explicit representation and boundary.

Preserve the reduction’s denominator

A masked mean needs a count of included elements rather than the original batch length. Define the result when no elements qualify, and keep that policy visible to downstream code. In a quality-scoring workflow, silently dividing by all examples changes the statistic even if the program now compiles. Similarly, a neutral value for a sum is not automatically neutral for a maximum, product or normalization. Rewrite the mathematical operation, not only the failing line.

Inspect branches used by differentiation

The control-flow guide distinguishes staged control flow and selection. Do not assume that masking an invalid expression makes all its numerical consequences disappear. The where documentation warns that NaN inputs can affect reverse-mode gradients even when their branch is not selected. For a differentiable objective, ensure intermediate expressions have a defined domain and test the gradient as well as the displayed forward value.

Carry validity with padded outputs

If a consumer genuinely needs selected rows, a bounded padded representation with a validity mask may be suitable, provided its capacity and overflow behavior are explicit. The guides on attention-mask axes and variable-length loss reduction explain related semantic issues. A shape-compatible program is useful only when its masks, denominators and excluded examples still express the intended model task.

Earn rental income from GPUs

Have idle GPUs or looking to fund AI infrastructure? Retrivium finds a rental platform, sets up the server and helps you assess income and costs with a pilot.

Explore GPU hosting
← All articles