Port a small transformer block to JAX and read the HLO
CPU · your Macnotebook150 minrequiredGoal · A PyTorch transformer block re-implemented in JAX with numerically matching outputs, its lowered and compiled HLO text saved, and the dot and fusion operations counted and explained.
- 1pip install jax (CPU); write a one-layer pre-norm transformer block (RMSNorm, 4-head attention, SwiGLU MLP) in PyTorch with fixed-seed weights and run it on an input of shape (2, 16, 256).
- 2Re-implement the same block in JAX with jax.numpy using the exported weights; compare outputs with the PyTorch block at atol 1e-5 in fp32.
- 3Call jax.jit(block).lower(x).as_text() and save the StableHLO; count dot_general operations and confirm the count matches the matmuls you wrote (q, k, v, o projections, scores, attention-value product, gate, up and down projections).
- 4Call .compile().as_text() and save the compiled HLO; count fusion ops and find which elementwise operations XLA fused into the matmuls or into the softmax.
- 5Add jax.sharding with a 2-device mesh (use XLA_FLAGS=--xla_force_host_platform_device_count=2) sharding the hidden dimension of the MLP; recompile and find the all-reduce or reduce-scatter XLA inserted.
- 6Change the input sequence length to 17 and observe recompilation; explain in a markdown cell why static shapes matter on TPUs.
- 7Time the jitted and the non-jitted JAX block and the PyTorch eager block for 100 iterations on CPU.
- Deliverable
- jax_block.ipynb with both HLO texts saved as files and a table of operation counts.
- Check
- Outputs match at atol 1e-5; the lowered StableHLO contains exactly 9 dot_general operations; the sharded compiled HLO contains at least one all-reduce or reduce-scatter; a sequence length change triggers a recompile (observable via a new compile log line or a jitted call time spike).