Yes – with the current specs there is a data race.
The problem is that every “program” ( = CUDA block / TPU tile in Pallas terminology ) receives a reference to exactly the same free_pages output buffer but they do not co-ordinate on where they write.
Why it races
-
out_shape=jax.ShapeDtypeStruct([max_num_free_pages], jnp.int32)
Together with
out_specs=pl.BlockSpec(memory_space=pltpu.SMEM) (shape / index_map are None)
⇒ the default “identity” mapping is used. Each program therefore thinks the
whole free_pages[0 : max_num_free_pages] array is its responsibility.
-
Inside the kernel every program starts with
num_free_pages_local = 0 (because the scratch num_free_pages lives in
shared memory, which is per program, not global).
When _add_free_page executes it writes to free_pages[num_free_pages]
starting at index 0, so different programs can (and usually will) overwrite
one another.
-
Only the last program (program_id(0) == num_programs(0) - 1) does the final
padding pass, but this does not prevent the earlier clobbering.
A quick experiment: instrument the kernel or run it with interpret=True; you’ll see that the output depends on launch order and is nondeterministic-looking.
How to fix it
There are two general ways.
───────────────────────────────────────────────────────────────────────────────
A. Give each program a disjoint slice of the output
───────────────────────────────────────────────────────────────────────────────
Let every program own its own row (or slice) of the output array. E.g.
grid_size = pl.cdiv(page_lengths.shape[0], 1024)
return pl.pallas_call(
_find_free_pages_kernel,
out_shape=jax.ShapeDtypeStruct([grid_size, max_num_free_pages], jnp.int32),
grid=(grid_size,),
out_specs=pl.BlockSpec(
[max_num_free_pages], # per-program tile shape
lambda pid: (pid[0], pl.dslice(0)), # index map: row = program_id
memory_space=pltpu.SMEM,
),
...
)(page_lengths)
Now free_pages inside the kernel is actually a 1-D view of the calling
program’s private row, so no two programs touch the same element and the race
is gone. After the call you can reshape / ravel or compact the rows on the
host if you really need a 1-D result.
───────────────────────────────────────────────────────────────────────────────
B. Keep one global buffer but use atomic reservation of slots
───────────────────────────────────────────────────────────────────────────────
If you truly need a single global list produced on-device you must co-ordinate
slot assignment: