jax icon indicating copy to clipboard operation
jax copied to clipboard

[mosaic] broadcast bug

Open oliverdutton opened this issue 11 months ago • 3 comments

Description

Mosaic bug in broadcast layout. It only occurs when the 2d shapes in this seemingly innocuous code fulfill: dim0 of topk_logits is a multiple of 128 [no padding kicks in] dim1 of topk_logits is a multiple of 128 (but not 128) I get:

MosaicError: INTERNAL: Mosaic failed to compile TPU kernel: Invalid input layout

The MLIR operation involved:
  %1379 = "vector.broadcast"(%77) {in_layout = [#tpu.vpad<"32,{*,128},(8,128)">], out_layout = [#tpu.vpad<"32,{*,128},(8,128)">]} : (vector<1x128xi32>) -> vector<8x128xi32>

It’s strange because larger misaligned values add padding (which should end up at the same shapes) and compile fine. Variety of shapes and outcomes are below. It may be related to broadcasting followed by slicing (the pad in between seems to not fail, so presumably is fixing something)

I'm sorry the reproducer is complex but the take_along_axis on the broadcast was critical to surfacing the error.

Run in colab on v5e (17th Dec) with jax 0.8.0 and 0.8.1 tried with same error


!pip install -U jax[tpu]
"""
Pallas kernel call for reproducer with test configurations.
Tests various (n,b) combinations: (128,128), (137,193), (128,256), (128,384)
"""

import functools
import jax
import jax.numpy as jnp
from jax import jit, lax
from jax.experimental import pallas as pl
from jax.experimental.pallas import tpu as pltpu

NUM_SUBLANES = 8
NUM_LANES = 128


def pad(arr, tile_shape, val=0):
    """Pad array to be multiple of tile_shape dimensions.

    Args:
        arr: Input array to pad.
        tile_shape: Target tile shape (tuple of ints).
        val: Padding value (default: 0).

    Returns:
        Padded array.
    """
    if len(tile_shape) != arr.ndim:
        raise ValueError(
            f"tile_shape length {len(tile_shape)} must match array ndim {arr.ndim}"
        )

    # Calculate padding for each dimension
    pad_widths = []
    for dim_size, block_size in zip(arr.shape, tile_shape):
        # Calculate target size as next multiple of block_size
        target_size = ((dim_size + block_size - 1) // block_size) * block_size
        pad_size = target_size - dim_size
        pad_widths.append((0, pad_size))

    # Return early if no padding needed
    if all(w == (0, 0) for w in pad_widths):
        return arr

    return jnp.pad(arr, pad_widths, mode='constant', constant_values=val)


def take_along_axis_arrays(val, idx, axis):
    """Gather values from val array using indices in idx array.

    This function performs a batched gather operation that's optimized for TPU
    hardware. It processes data in tiles of size (NUM_SUBLANES, NUM_LANES).

    Args:
        val: Values array to gather from.
        idx: Indices array specifying which values to gather.
        axis: Axis along which to gather.

    Returns:
        Gathered values with shape matching idx.shape.
    """
    shape = idx.shape
    tile_shape = (NUM_SUBLANES, NUM_LANES)
    val, idx = (pad(x, tile_shape, val=0) for x in (val, idx))

    def _gather_arrays(val, idx):
        # Initialize accumulators
        accumulators = [
            jnp.zeros(tile_shape, dtype=val.dtype)
            for _ in range(idx.shape[axis] // tile_shape[axis])
        ]
        for val_offset in range(0, val.shape[axis], tile_shape[axis]):
            # Load values for this block once
            val_tile = lax.slice_in_dim(val, val_offset, val_offset+tile_shape[axis], axis=axis)

            # Apply to all K blocks
            for idx_offset in range(0, idx.shape[axis], tile_shape[axis]):
                idx_tile = lax.slice_in_dim(idx, idx_offset, idx_offset+tile_shape[axis], axis=axis)
                mask = (idx_tile >= val_offset) & (idx_tile < val_offset + tile_shape[axis])
                gather_tile = jnp.take_along_axis(
                    val_tile,
                    (idx_tile - val_offset) % tile_shape[axis],
                    axis=axis
                )
                i = idx_offset // tile_shape[axis]
                accumulators[i] = jnp.where(mask, gather_tile, accumulators[i])
        return jnp.concatenate(accumulators, axis=axis)

    batch_axis = 1 - axis
    assert val.shape[batch_axis]==idx.shape[batch_axis]
    return jnp.concatenate(
        [_gather_arrays(v, i)
         for v, i in zip(*map(lambda arr: jnp.split(
             arr, arr.shape[batch_axis] // tile_shape[batch_axis], axis=batch_axis), (val, idx)))
        ],
        axis=batch_axis
    )[:shape[0], :shape[1]]

def reproducer_kernel(topk_logits_ref, p_ref, out_ref):  
    topk_logits = topk_logits_ref[...]
    p = p_ref[...]
    shape = topk_logits.shape
    # p is (b,). probs is (n,b)
    
    cumsum_probs = topk_logits  # skip for reproducer
    
    threshold_idx = (cumsum_probs < p[None, :]).sum(0, keepdims=True)
    threshold_idx = jnp.where(p[None, :] == 1., shape[0] - 1, threshold_idx) 
    
        
    thresholds = take_along_axis_arrays(
        topk_logits, jnp.broadcast_to(threshold_idx, shape), 0)
    # broadcast appears to be the issue
    topp_logits = jnp.where(
        topk_logits >= thresholds,
        topk_logits, -1e12)
    out_ref[...] = topp_logits


def call_reproducer_kernel(topk_logits, p):
    """
    Pallas call wrapper for the reproducer kernel.
    
    Args:
        topk_logits: Input array of shape (n, b)
        p: Threshold array of shape (b,)
    
    Returns:
        Output array of shape (n, b)
    """
    n, b = topk_logits.shape
    
    out_shape = jax.ShapeDtypeStruct(
        shape=(n, b),
        dtype=topk_logits.dtype
    )
    
    result = pl.pallas_call(
        reproducer_kernel,
        out_shape=out_shape
    )(topk_logits, p)
    
    return result

import itertools
def run_tests():
    """
    Run tests with specified (n, b) configurations.
    """
    test_configs = list(itertools.product([128,137,256,384], [128,193,256,355,384]))
    print("Running reproducer kernel tests...")
    print("=" * 60)
    
    for n, b in test_configs:
        print(f"\nTesting with (n, b) = ({n}, {b})")
        print("-" * 60)
        
        # Create test inputs
        key = jax.random.PRNGKey(42)
        key1, key2 = jax.random.split(key)
        
        topk_logits = jax.random.normal(key1, (n, b))
        p = jax.random.uniform(key2, (b,), minval=0.0, maxval=1.0)
        
        try:
            # Run the kernel
            result = call_reproducer_kernel(topk_logits, p)
            
            print(f"✓ Successfully compiled!")
            
        except Exception as e:
            print(f"✗ Failed with error:")
            print(f"  {type(e).__name__}: {str(e)}")
    
    print("\n" + "=" * 60)
    print("Tests complete!")


if __name__ == "__main__":
    run_tests()
    
#### Output
Requirement already satisfied: jax[tpu] in /usr/local/lib/python3.12/dist-packages (0.8.1)
Requirement already satisfied: jaxlib<=0.8.1,>=0.8.1 in /usr/local/lib/python3.12/dist-packages (from jax[tpu]) (0.8.1)
Requirement already satisfied: ml_dtypes>=0.5.0 in /usr/local/lib/python3.12/dist-packages (from jax[tpu]) (0.5.4)
Requirement already satisfied: numpy>=2.0 in /usr/local/lib/python3.12/dist-packages (from jax[tpu]) (2.0.2)
Requirement already satisfied: opt_einsum in /usr/local/lib/python3.12/dist-packages (from jax[tpu]) (3.4.0)
Requirement already satisfied: scipy>=1.13 in /usr/local/lib/python3.12/dist-packages (from jax[tpu]) (1.16.3)
Requirement already satisfied: libtpu==0.0.30.* in /usr/local/lib/python3.12/dist-packages (from jax[tpu]) (0.0.30)
Requirement already satisfied: requests in /usr/local/lib/python3.12/dist-packages (from jax[tpu]) (2.32.4)
Requirement already satisfied: charset_normalizer<4,>=2 in /usr/local/lib/python3.12/dist-packages (from requests->jax[tpu]) (3.4.4)
Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.12/dist-packages (from requests->jax[tpu]) (3.11)
Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.12/dist-packages (from requests->jax[tpu]) (2.5.0)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.12/dist-packages (from requests->jax[tpu]) (2025.11.12)
Running reproducer kernel tests...
============================================================

Testing with (n, b) = (128, 128)
------------------------------------------------------------
✓ Successfully compiled!

Testing with (n, b) = (128, 193)
------------------------------------------------------------
✓ Successfully compiled!

Testing with (n, b) = (128, 256)
------------------------------------------------------------
✗ Failed with error:
  MosaicError: INTERNAL: Mosaic failed to compile TPU kernel: Invalid input layout

The MLIR operation involved:
  %480 = "vector.broadcast"(%44) {in_layout = [#tpu.vpad<"32,{*,128},(8,128)">], out_layout = [#tpu.vpad<"32,{*,128},(8,128)">]} : (vector<1x128xi32>) -> vector<8x128xi32>

Please report a bug at: https://github.com/google/jax/issues/new?assignees=apaszke


Testing with (n, b) = (128, 355)
------------------------------------------------------------
✓ Successfully compiled!

Testing with (n, b) = (128, 384)
------------------------------------------------------------
✗ Failed with error:
  MosaicError: INTERNAL: Mosaic failed to compile TPU kernel: Invalid input layout

The MLIR operation involved:
  %482 = "vector.broadcast"(%45) {in_layout = [#tpu.vpad<"32,{*,128},(8,128)">], out_layout = [#tpu.vpad<"32,{*,128},(8,128)">]} : (vector<1x128xi32>) -> vector<8x128xi32>

Please report a bug at: https://github.com/google/jax/issues/new?assignees=apaszke


Testing with (n, b) = (137, 128)
------------------------------------------------------------
✓ Successfully compiled!

Testing with (n, b) = (137, 193)
------------------------------------------------------------
✓ Successfully compiled!

Testing with (n, b) = (137, 256)
------------------------------------------------------------
✓ Successfully compiled!

Testing with (n, b) = (137, 355)
------------------------------------------------------------
✓ Successfully compiled!

Testing with (n, b) = (137, 384)
------------------------------------------------------------
✓ Successfully compiled!

Testing with (n, b) = (256, 128)
------------------------------------------------------------
✓ Successfully compiled!

Testing with (n, b) = (256, 193)
------------------------------------------------------------
✓ Successfully compiled!

Testing with (n, b) = (256, 256)
------------------------------------------------------------
✗ Failed with error:
  MosaicError: INTERNAL: Mosaic failed to compile TPU kernel: Invalid input layout

The MLIR operation involved:
  %929 = "vector.broadcast"(%60) {in_layout = [#tpu.vpad<"32,{*,128},(8,128)">], out_layout = [#tpu.vpad<"32,{*,128},(8,128)">]} : (vector<1x128xi32>) -> vector<8x128xi32>

Please report a bug at: https://github.com/google/jax/issues/new?assignees=apaszke


Testing with (n, b) = (256, 355)
------------------------------------------------------------
✓ Successfully compiled!

Testing with (n, b) = (256, 384)
------------------------------------------------------------
✗ Failed with error:
  MosaicError: INTERNAL: Mosaic failed to compile TPU kernel: Invalid input layout

The MLIR operation involved:
  %931 = "vector.broadcast"(%61) {in_layout = [#tpu.vpad<"32,{*,128},(8,128)">], out_layout = [#tpu.vpad<"32,{*,128},(8,128)">]} : (vector<1x128xi32>) -> vector<8x128xi32>

Please report a bug at: https://github.com/google/jax/issues/new?assignees=apaszke


Testing with (n, b) = (384, 128)
------------------------------------------------------------
✓ Successfully compiled!

Testing with (n, b) = (384, 193)
------------------------------------------------------------
✓ Successfully compiled!

Testing with (n, b) = (384, 256)
------------------------------------------------------------
✗ Failed with error:
  MosaicError: INTERNAL: Mosaic failed to compile TPU kernel: Invalid input layout

The MLIR operation involved:
  %1377 = "vector.broadcast"(%76) {in_layout = [#tpu.vpad<"32,{*,128},(8,128)">], out_layout = [#tpu.vpad<"32,{*,128},(8,128)">]} : (vector<1x128xi32>) -> vector<8x128xi32>

Please report a bug at: https://github.com/google/jax/issues/new?assignees=apaszke


Testing with (n, b) = (384, 355)
------------------------------------------------------------
✓ Successfully compiled!

Testing with (n, b) = (384, 384)
------------------------------------------------------------
✗ Failed with error:
  MosaicError: INTERNAL: Mosaic failed to compile TPU kernel: Invalid input layout

The MLIR operation involved:
  %1379 = "vector.broadcast"(%77) {in_layout = [#tpu.vpad<"32,{*,128},(8,128)">], out_layout = [#tpu.vpad<"32,{*,128},(8,128)">]} : (vector<1x128xi32>) -> vector<8x128xi32>

Please report a bug at: https://github.com/google/jax/issues/new?assignees=apaszke


============================================================
Tests complete!

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

Colab v5e, Jax 0.8.1

oliverdutton avatar Dec 17 '25 15:12 oliverdutton

I'm using

pltpu.repeat(
  jnp.broadcast_to(
    x, (NUM_SUBLANES, shape[1])
  ), shape[0]//NUM_SUBLANES, axis=0)

As a temporary workaround to broadcast (1, b) to (multiple of NUM_LANES, b)

Similarly doing it all as a pltpu.repeat without broadcasting to tile first compiles fine too: pltpu.repeat(x, n, axis=0)

oliverdutton avatar Dec 30 '25 00:12 oliverdutton

@oliverdutton also ran into this and used the workaround, on side note. pltpu.repeat is deprecated use jnp.tile instead

coolkp avatar Mar 21 '26 04:03 coolkp

This is going to be fixed in recent releases.

yueshengys avatar Apr 22 '26 23:04 yueshengys