sample_id stringlengths 21 196 | text stringlengths 105 936k | metadata dict | category stringclasses 6
values |
|---|---|---|---|
jax-ml/jax:jax/experimental/mosaic/gpu/mma.py | # Copyright 2025 The JAX Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import itertools
from jax.experimental.mosaic.gpu import fragmented_array as fa
from jaxlib.mlir import ir
from jaxlib.mlir.dialects import llvm
from jaxlib.mlir.dialects import vector
import numpy as np
from . import utils
SUPPORTED_F8_TYPES = (ir.Float8E4M3FNType, ir.Float8E5M2Type)
class MMALayouts:
"""Container for MMA layouts, providing a convenient way to create
layouts for MMA operands based on warp configuration.
"""
def __init__(self, element_type: ir.Type):
elems_per_reg = 32 // utils.bitwidth(element_type)
k = 8 * elems_per_reg
sub_k = 4 * elems_per_reg
self.lhs = fa.TiledLayout(
fa.Tiling(((64, k), (16, sub_k), (8, sub_k), (elems_per_reg,))),
warp_dims=(-7,),
lane_dims=(-3, -2),
vector_dim=-1,
)
self.rhs = fa.TiledLayout(
fa.Tiling(((8, k), (8, sub_k), (elems_per_reg,))),
warp_dims=(fa.Replicated(4),),
lane_dims=(-3, -2),
vector_dim=-1,
)
self.acc = fa.TiledLayout(
fa.Tiling(((64, 8), (16, 8), (8, 8), (2,))),
warp_dims=(-7,),
lane_dims=(-3, -2),
vector_dim=-1,
)
def _ptx_dtype_str(dtype: ir.Type, *, is_signed: bool | None = None) -> str:
if isinstance(dtype, ir.Float8E4M3FNType):
return "e4m3"
elif isinstance(dtype, ir.Float8E5M2Type):
return "e5m2"
elif isinstance(dtype, ir.IntegerType):
if is_signed is None:
raise ValueError("is_signed must be specified for integer types")
return "s8" if is_signed else "u8"
return str(dtype)
def _mma_single_tile(
acc: fa.FragmentedArray, a: fa.FragmentedArray, b: fa.FragmentedArray
) -> fa.FragmentedArray:
"""Performs `acc + a @ b.T` using warp level MMA instructions."""
i32 = ir.IntegerType.get_signless(32)
k_tile = 32 // utils.bytewidth(a.mlir_dtype)
assert a.shape == (64, k_tile)
assert b.shape == (8, k_tile)
assert acc.shape == (64, 8)
assert a.mlir_dtype == b.mlir_dtype
is_integer = isinstance(a.mlir_dtype, ir.IntegerType)
assert acc.mlir_dtype == i32 if is_integer else ir.F32Type.get()
assert acc.is_signed in {None, True}
assert (
isinstance(acc.layout, fa.TiledLayout)
and isinstance(a.layout, fa.TiledLayout)
and isinstance(b.layout, fa.TiledLayout)
)
num_acc_regs, num_a_regs, num_b_regs = 4, 4, 2
acc_regs = [ # pylint: disable=g-complex-comprehension
vector.extract(
reg,
dynamic_position=[],
static_position=ir.DenseI64ArrayAttr.get([pos]),
)
for reg in acc.registers.flatten()
for pos in range(acc.layout.vector_length)
]
a_regs = [utils.bitcast(r, i32) for r in a.registers.flatten()]
b_regs = [utils.bitcast(r, i32) for r in b.registers.flatten()]
# Make sure we have the right number of registers for the instruction.
assert len(a_regs) == 4
assert len(acc_regs) == 4
assert len(b_regs) == 2
a_ptx_dtype = _ptx_dtype_str(a.mlir_dtype, is_signed=a.is_signed)
b_ptx_dtype = _ptx_dtype_str(b.mlir_dtype, is_signed=b.is_signed)
acc_ptx_dtype = "s32" if is_integer else "f32"
acc_constraint = "r" if is_integer else "f"
instr = f"mma.sync.aligned.m16n8k{k_tile}.row.col.{acc_ptx_dtype}.{a_ptx_dtype}.{b_ptx_dtype}.{acc_ptx_dtype}"
counter = itertools.count()
n_regs_str = lambda n: (
"{" + ",".join([f"${next(counter)}" for _ in range(n)]) + "}"
)
out_regs_str = n_regs_str(num_acc_regs)
a_regs_str = n_regs_str(num_a_regs)
b_regs_str = n_regs_str(num_b_regs)
c_regs_str = n_regs_str(num_acc_regs)
ptx = f"{instr} {out_regs_str}, {a_regs_str}, {b_regs_str}, {c_regs_str};"
# See: https://llvm.org/docs/LangRef.html#inline-assembler-expressions
constraints = (
f"{','.join([f'={acc_constraint}']*num_acc_regs)},"
f"{','.join(['r']*num_a_regs)},"
f"{','.join(['r']*num_b_regs)},"
f"{','.join([acc_constraint]*num_acc_regs)}"
)
in_operands = [*a_regs, *b_regs, *acc_regs]
acc_struct_type = ir.Type.parse(
f"!llvm.struct<({','.join(str(acc.mlir_dtype) for _ in acc_regs)})>"
)
out_regs_struct = llvm.inline_asm(
acc_struct_type,
in_operands,
ptx,
constraints,
has_side_effects=False,
)
out_regs = [
llvm.extractvalue(acc.mlir_dtype, out_regs_struct, [i])
for i in range(len(acc_regs))
]
vec_regs = []
vec_undef = llvm.mlir_undef(ir.VectorType.get((2,), acc.mlir_dtype))
for first, second in zip(out_regs[::2], out_regs[1::2]):
vec = llvm.insertelement(vec_undef, first, position=utils.c(0, i32))
vec = llvm.insertelement(vec, second, position=utils.c(1, i32))
vec_regs.append(vec)
out_regs = np.asarray(vec_regs, dtype=object).reshape(acc.registers.shape)
return fa.FragmentedArray(
_registers=out_regs, _layout=acc.layout, _is_signed=acc.is_signed
)
# TODO(cperivol): More datatypes other than (b)f16.
def mma(
acc: fa.FragmentedArray,
a: fa.FragmentedArray,
b: fa.FragmentedArray,
) -> fa.FragmentedArray:
"""Computes `acc + a @ b.T` using synchronouse MMA instructions.
All operands must have `TiledLayout`s. The layouts must be generated
by the `MMALayouts` class, which ensures that the tiles are mapped
to the warps correctly.
Args:
acc: A `FragmentedArray` with a `TiledLayout` generated from
`MMALayouts.acc`.
a: A `FragmentedArray` with a `TiledLayout` generated from
`MMALayouts.lhs`.
b: A `FragmentedArray` with a `TiledLayout` generated from `MMALayouts.rhs`.
Returns:
A new `FragmentedArray` with the result of the computation with
the same type as `acc`.
"""
(m, k) = a.shape
(n, k2) = b.shape
(m2, n2) = acc.shape
if m != m2:
raise ValueError(f"M mismatch: {m} != {m2}")
if n != n2:
raise ValueError(f"N mismatch: {n} != {n2}")
if k != k2:
raise ValueError(f"K mismatch: {k} != {k2}")
# todo(cperivol): A tile shape can have dimensions that are higher
# multiples of the mma op size as long as those dimensions are not
# sharded across warps.
bf16 = ir.BF16Type.get()
f16 = ir.F16Type.get()
i8 = ir.IntegerType.get_signless(8)
i32 = ir.IntegerType.get_signless(32)
f8e4m3fn = ir.Float8E4M3FNType.get()
f8e5m2 = ir.Float8E5M2Type.get()
if (element_type := a.mlir_dtype) != b.mlir_dtype:
raise ValueError(f"Dtype mismatch: {a.mlir_dtype} != {b.mlir_dtype}")
if element_type not in (bf16, f16, f8e4m3fn, f8e5m2, i8):
raise NotImplementedError(
"Only bf16, f16, float8_e4m3fn, float8_e5m2 and i8 supported for the"
" operands."
)
if element_type == i8:
if acc.mlir_dtype != i32:
raise NotImplementedError("Only s32 accumulator supported for i8 operands.")
if not acc.is_signed:
raise ValueError("Only signed accumulator supported for i8 operands.")
elif acc.mlir_dtype != ir.F32Type.get():
raise NotImplementedError("Only f32 accumulator supported for floating operands.")
layouts = MMALayouts(element_type)
if layouts.lhs != a.layout:
raise ValueError("Expected MMALayouts.lhs layout for A")
if layouts.rhs != b.layout:
raise ValueError("Expected MMALayouts.rhs layout for B")
if layouts.acc != acc.layout:
raise ValueError("Expected MMALayouts.acc layout for acc")
assert isinstance(a.layout, fa.TiledLayout)
assert isinstance(b.layout, fa.TiledLayout)
assert isinstance(acc.layout, fa.TiledLayout)
m_tile, k_tile = a.layout.base_tile_shape
n_tile, k_tile2 = b.layout.base_tile_shape
m_tile2, n_tile2 = acc.layout.base_tile_shape
assert k_tile == k_tile2
assert m_tile2 == m_tile
assert n_tile2 == n_tile
num_m_tiles, num_n_tiles, num_k_tiles = m // m_tile, n // n_tile, k // k_tile
# Do not modify the accumualtor itself.
acc = acc.copy()
s = lambda idx, length: slice(idx * length, (idx + 1) * length)
for k_idx in range(num_k_tiles):
for m_idx in range(num_m_tiles):
for n_idx in range(num_n_tiles):
ms = s(m_idx, m_tile)
ns = s(n_idx, n_tile)
ks = s(k_idx, k_tile)
acc[ms, ns] = _mma_single_tile(acc[ms, ns], a[ms, ks], b[ns, ks])
return acc
| {
"repo_id": "jax-ml/jax",
"file_path": "jax/experimental/mosaic/gpu/mma.py",
"license": "Apache License 2.0",
"lines": 218,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
jax-ml/jax:jax/experimental/mosaic/gpu/test_util.py | # Copyright 2025 The JAX Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import enum
import jax
from jax._src.lib.mlir import ir
from jax.experimental.mosaic.gpu import fragmented_array as fa
from jax.experimental.mosaic.gpu import layouts
from jax.experimental.mosaic.gpu import tcgen05
from jax.experimental.mosaic.gpu import utils
class RegisterLayout(enum.Enum):
"""The list of supported register layouts."""
WGMMA = enum.auto()
WG_SPLAT = enum.auto()
WG_STRIDED = enum.auto()
TCGEN05 = enum.auto()
TCGEN05_M64_COLLECTIVE = enum.auto()
TCGEN05_TMEM_NATIVE = enum.auto()
SMEM_GMEM_COPY = enum.auto()
TMA_GATHER_INDICES = enum.auto()
def to_mgpu(
self, shape: tuple[int, int], dtype: jax.typing.DTypeLike | ir.Type
) -> fa.FragmentedLayout:
if not isinstance(dtype, ir.Type):
dtype = utils.dtype_to_ir_type(dtype)
match self:
case RegisterLayout.WGMMA:
return fa.WGMMA_LAYOUT
case RegisterLayout.WG_SPLAT:
return fa.WGSplatFragLayout(shape)
case RegisterLayout.WG_STRIDED:
ty = ir.VectorType.get(shape, dtype)
layout = fa.WGStridedFragLayout.from_shaped_type(ty)
assert layout is not None
return layout
case RegisterLayout.TCGEN05:
return fa.TCGEN05_LAYOUT
case RegisterLayout.TCGEN05_M64_COLLECTIVE:
return tcgen05.fa_m64_collective_layout(shape[1])
case RegisterLayout.TCGEN05_TMEM_NATIVE:
return fa.TMEM_NATIVE_LAYOUT
case RegisterLayout.SMEM_GMEM_COPY:
swizzle = 128
bitwidth = utils.bitwidth(dtype)
tiling = (8, 8 * swizzle // bitwidth)
row_tiles, col_tiles = utils.tile_shape(shape, tiling)[-4:-2]
return fa.tiled_copy_smem_gmem_layout(
row_tiles, col_tiles, swizzle, bitwidth
)
case RegisterLayout.TMA_GATHER_INDICES:
return fa.TMA_GATHER_INDICES_LAYOUT
def to_layout_attr(
self, shape: tuple[int, int], dtype: jax.typing.DTypeLike | ir.Type
) -> ir.Attribute:
return layouts.to_layout_attr(self.to_mgpu(shape, dtype))
| {
"repo_id": "jax-ml/jax",
"file_path": "jax/experimental/mosaic/gpu/test_util.py",
"license": "Apache License 2.0",
"lines": 66,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:jax/experimental/pallas/ops/gpu/blackwell_matmul_mgpu.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Matrix Multiplication kernel for Blackwell GPUs."""
import dataclasses
import enum
import functools
import itertools
import statistics
import jax
from jax import lax
from jax._src import test_util as jtu # noqa: F401
from jax.experimental.mosaic.gpu import profiler
import jax.experimental.pallas as pl
import jax.experimental.pallas.mosaic_gpu as plgpu
import jax.numpy as jnp
import numpy as np
class MatmulDimension(enum.IntEnum):
M = 0
N = 1
@dataclasses.dataclass(frozen=True)
class TuningConfig:
tile_m: int
tile_n: int
tile_k: int
max_concurrent_steps: int
collective: bool
epilogue_tile_n: int = 64
grid_minor_dim: MatmulDimension = MatmulDimension.N
grid_tile_width: int = 1
def matmul_kernel(a, b, config: TuningConfig):
dtype = a.dtype
if a.dtype != b.dtype:
raise ValueError(
f"Matmul LHS and RHS have incompatible dtypes {a.dtype} vs {b.dtype}"
)
m, k = a.shape
k2, n = b.shape
if k != k2:
raise ValueError(
f"Matmul LHS and RHS have incompatible shapes {a.shape} vs {b.shape}"
)
collective = config.collective
tile_m, tile_n, tile_k = (config.tile_m, config.tile_n, config.tile_k)
epilogue_tile_n = config.epilogue_tile_n
if tile_n % epilogue_tile_n != 0:
raise ValueError(
f"{tile_n=} must be divisible by {epilogue_tile_n=}"
)
block_tile_m = tile_m
block_tile_n = tile_n
if collective:
tile_m *= 2
tile_n *= 2
swizzle = plgpu.find_swizzle(tile_k * jnp.dtype(dtype).itemsize * 8)
swizzle_elems = swizzle // jnp.dtype(dtype).itemsize
transforms = (
plgpu.TilingTransform((8, swizzle_elems)),
plgpu.SwizzleTransform(swizzle),
)
out_swizzle = plgpu.find_swizzle(epilogue_tile_n * jnp.dtype(dtype).itemsize * 8)
out_swizzle_elems = out_swizzle // jnp.dtype(dtype).itemsize
out_transforms = (
plgpu.TilingTransform((8, out_swizzle_elems)),
plgpu.SwizzleTransform(out_swizzle),
)
if m % tile_m != 0:
raise ValueError(f"{m=} must be divisible by {tile_m=}")
if n % tile_n != 0:
raise ValueError(f"{n=} must be divisible by {tile_n=}")
if k % tile_k != 0:
raise ValueError(f"{k=} must be divisible by {tile_k=}")
m_iters = m // tile_m
n_iters = n // tile_n
k_iters = k // tile_k
max_concurrent_steps = config.max_concurrent_steps
TMA_WARP = 0
MMA_WARP = 1
COMPUTE_WG = 0
STORE_WG = 1
def kernel(a_gmem, b_gmem, out_gmem,
a_smem, b_smem, acc_tmem, acc_smem,
ab_tma_barrier, store_done_barrier, mma_done_barrier,
consumed_barrier):
wg_idx = lax.axis_index("wg")
cluster_idx = lax.axis_index("x")
is_lead_block = cluster_idx == 0
@plgpu.dynamic_scheduling_loop(grid_names=("mn_linear",), thread_axis="wg")
def mn_loop(loop_info: plgpu.NDLoopInfo): # pylint: disable=unused-variable
(lin_idx,) = loop_info.index
local_index = loop_info.local_index
m_index, n_index = plgpu.planar_snake(
lin_idx,
(m_iters, n_iters),
config.grid_minor_dim,
config.grid_tile_width,
)
block_m_index = m_index * 2 + cluster_idx if collective else m_index
block_slice_m = pl.ds(block_m_index * block_tile_m, block_tile_m)
slice_m = pl.ds(m_index * tile_m, tile_m)
slice_n = pl.ds(n_index * tile_n, tile_n)
acc_slot = lax.rem(local_index, jnp.int32(2))
@pl.when(wg_idx == COMPUTE_WG)
def _():
@pl.core_map(plgpu.WarpMesh(axis_name="warp"))
def _per_warp():
warp_id = lax.axis_index("warp")
@pl.when(warp_id == TMA_WARP)
def _memory():
def _loop_body(ki, _):
slice_k = pl.ds(ki * tile_k, tile_k)
slot = lax.rem(ki, max_concurrent_steps)
@pl.when(jnp.logical_or(ki >= max_concurrent_steps,
local_index > 0))
def _():
plgpu.barrier_wait(consumed_barrier.at[slot])
plgpu.copy_gmem_to_smem(
a_gmem.at[slice_m, slice_k],
a_smem.at[slot],
ab_tma_barrier.at[slot],
partitioned_axis=0 if collective else None,
collective_axes="x" if collective else None,
)
plgpu.copy_gmem_to_smem(
b_gmem.at[slice_k, slice_n],
b_smem.at[slot],
ab_tma_barrier.at[slot],
partitioned_axis=1 if collective else None,
collective_axes="x" if collective else None,
)
lax.fori_loop(0, k_iters, _loop_body, None)
@pl.when(jnp.logical_and(warp_id == MMA_WARP, local_index > 1))
def _wait_store():
plgpu.barrier_wait(store_done_barrier.at[acc_slot])
@pl.when(jnp.logical_and(warp_id == MMA_WARP, is_lead_block))
def _compute():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
plgpu.barrier_wait(ab_tma_barrier.at[slot])
is_last_iter = ki >= k_iters - 1
acc_tmem_slice = acc_tmem.at[:, pl.ds(acc_slot * tile_n, tile_n)]
plgpu.tcgen05_mma(
acc_tmem_slice,
a_smem.at[slot],
b_smem.at[slot],
consumed_barrier.at[slot],
accumulate=(ki > 0),
collective_axis="x" if collective else None,
)
@pl.when(is_last_iter)
def _():
plgpu.tcgen05_commit_arrive(
mma_done_barrier.at[acc_slot],
collective_axis="x" if collective else None,
)
lax.fori_loop(0, k_iters, _loop_body, None)
@pl.when(wg_idx == STORE_WG)
def _():
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
plgpu.barrier_wait(mma_done_barrier.at[acc_slot])
acc_tmem_slot = acc_tmem.at[:, pl.ds(acc_slot * tile_n, tile_n)]
step_out_gmem = out_gmem.at[block_slice_m, slice_n]
for ni in range(tile_n // epilogue_tile_n):
acc_smem_ni = acc_smem.at[ni % 2]
ni_col_slice = pl.ds(ni * epilogue_tile_n, epilogue_tile_n)
acc_smem_ni[...] = plgpu.async_load_tmem(
acc_tmem_slot.at[:, ni_col_slice]
).astype(dtype)
plgpu.commit_smem()
plgpu.copy_smem_to_gmem(acc_smem_ni, step_out_gmem.at[:, ni_col_slice])
plgpu.wait_smem_to_gmem(1, wait_read_only=True)
plgpu.wait_load_tmem() # Load must complete before we continue.
plgpu.barrier_arrive(store_done_barrier.at[acc_slot])
if collective:
store_done_barrier = plgpu.ClusterBarrier(
collective_axes=("x",),
num_arrivals=1,
num_barriers=2,
orders_tensor_core=True,
)
else:
store_done_barrier = plgpu.Barrier( # type: ignore
num_arrivals=1, num_barriers=2, orders_tensor_core=True
)
f = plgpu.kernel(
kernel,
out_shape=jax.ShapeDtypeStruct((m, n), dtype),
grid=(m_iters * n_iters,),
grid_names=("mn_linear",),
num_threads=2,
thread_name="wg",
cluster_names=("x",),
cluster=(1 + collective,),
scratch_shapes=dict(
a_smem=plgpu.SMEM(
(max_concurrent_steps, block_tile_m, tile_k),
dtype,
transforms=transforms,
),
b_smem=plgpu.SMEM(
(max_concurrent_steps, tile_k, block_tile_n),
dtype,
transforms=transforms,
),
acc_tmem=plgpu.TMEM(
(block_tile_m, tile_n * 2), jnp.float32, collective=collective
),
acc_smem=plgpu.SMEM(
(2, block_tile_m, epilogue_tile_n),
dtype,
transforms=out_transforms,
),
ab_tma_barrier=plgpu.Barrier(
num_arrivals=2, num_barriers=max_concurrent_steps
),
store_done_barrier=store_done_barrier,
mma_done_barrier=plgpu.Barrier(
num_arrivals=1, num_barriers=2, orders_tensor_core=True
),
consumed_barrier=plgpu.Barrier(
num_arrivals=1,
num_barriers=max_concurrent_steps,
orders_tensor_core=True,
),
),
)
return f(a, b)
def main(_) -> None:
problem_it = [(4096, 8192, 4096)]
for M, N, K in problem_it:
print(f"==== {M=} {N=} {K=} ====")
matmul_flops = 2 * M * N * K
peak_flops = 2.25e15 # f16 TensorCore peak = 2250 TFLOPS
a = jax.random.uniform(jax.random.key(1), (M, K), jnp.float16, -1, 1)
b = jax.random.uniform(jax.random.key(2), (K, N), jnp.float16, -1, 1)
tuning_it = itertools.product(
(128,), # tile_m
(128, 256), # tile_n
(64,), # tile_k
MatmulDimension, # grid_minor_dim
(1, 4, 8, 12, 16), # grid_tile_width
(2, 4, 6), # max_concurrent_steps
(False, True), # collective
(32,), # epilogue_tile_n
)
best_util = -float("inf")
expected = jnp.dot(a, b, precision=jax.lax.DotAlgorithmPreset.F16_F16_F32)
for (tile_m, tile_n, tile_k, grid_minor_dim, grid_tile_width,
max_concurrent_steps, collective, epilogue_tile_n) in tuning_it:
# Only N <= 128 are supported for collective MMAs
if collective and tile_n > 128:
continue
config = TuningConfig(
tile_m=tile_m,
tile_n=tile_n,
tile_k=tile_k,
max_concurrent_steps=max_concurrent_steps,
collective=collective,
epilogue_tile_n=epilogue_tile_n,
grid_minor_dim=grid_minor_dim,
grid_tile_width=grid_tile_width,
)
if collective:
tile_m *= 2
tile_n *= 2
try:
out, runtimes_ms = profiler.measure(
functools.partial(matmul_kernel, config=config), iterations=10
)(a, b)
assert runtimes_ms is not None
runtime_ms = statistics.median(runtimes_ms)
except ValueError as e:
if ("exceeds available shared memory" in e.args[0] or
"Accumulator layout mismatch:" in e.args[0]):
# Accumulator layout mismatch triggers for tile_n=256 on some configs.
continue
raise
runtime_us = runtime_ms * 1e3 # type: ignore
optimal_time = matmul_flops / peak_flops * 1e6 # us
achieved_tc_util = optimal_time / runtime_us * 100
if achieved_tc_util > best_util:
np.testing.assert_allclose(out, expected)
best_util = achieved_tc_util
print(
f"{tile_m=} {tile_n=} {tile_k=} {max_concurrent_steps=} "
f"{grid_minor_dim=} {grid_tile_width=} "
f"{epilogue_tile_n=} "
f"{collective=} : "
f"{runtime_us:<7.1f}us"
f" = {achieved_tc_util:4.1f}% TC utilization"
)
print(f"\tBest utilization: {best_util:4.1f}%")
_, runtimes_ms = profiler.measure(
functools.partial(
jnp.dot, precision=jax.lax.DotAlgorithmPreset.F16_F16_F32
),
iterations=10,
)(a, b)
assert runtimes_ms is not None
runtime_ms = statistics.median(runtimes_ms)
runtime_us = runtime_ms * 1e3 # type: ignore
optimal_time = matmul_flops / peak_flops * 1e6 # us
achieved_tc_util = optimal_time / runtime_us * 100
print(f"\tReference: {achieved_tc_util:4.1f}%")
if __name__ == "__main__":
from absl import app
jax.config.config_with_absl()
app.run(main)
| {
"repo_id": "jax-ml/jax",
"file_path": "jax/experimental/pallas/ops/gpu/blackwell_matmul_mgpu.py",
"license": "Apache License 2.0",
"lines": 318,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
jax-ml/jax:jax/experimental/pallas/ops/gpu/blackwell_ragged_dot_mgpu.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Ragged/Grouped Matrix Multiplication kernel for Blackwell GPUs."""
import dataclasses
import functools
import itertools
import math
import jax
from jax import lax
from jax._src import test_util as jtu # noqa: F401
from jax.experimental.mosaic.gpu import profiler
import jax.experimental.pallas as pl
import jax.experimental.pallas.mosaic_gpu as plgpu
from jax.experimental.pallas.ops.gpu import blackwell_matmul_mgpu
from jax.experimental.pallas.ops.gpu import ragged_dot_mgpu
import jax.numpy as jnp
import numpy as np
from typing import Sequence
@dataclasses.dataclass(frozen=True)
class TuningConfig:
tile_m: int
tile_n: int
tile_k: int
max_concurrent_steps: int
collective: bool
grid_tile_width: int
grid_minor_dim: blackwell_matmul_mgpu.MatmulDimension
epilogue_tile_n: int = 64
def __str__(self):
return "_".join(f"{k}={v}" for k, v in dataclasses.asdict(self).items())
# TODO(justinfu): Merge with blackwell_matmul_mgpu.py
def do_matmul(a_gmem,
b_gmem,
out_gmem,
grid_indices: Sequence[jax.Array],
wg_axis: str,
collective_axes: tuple[str, ...],
local_index: jax.Array,
config: TuningConfig,
group_info: ragged_dot_mgpu.GroupInfo,
a_smem, b_smem, acc_tmem, acc_smem,
a_tma_barrier, b_tma_barrier, store_done_barrier, mma_done_barrier,
consumed_barrier
):
"""Compute a non-ragged matmul for a single output block."""
dtype = out_gmem.dtype
m, k = a_gmem.shape
collective = config.collective
tile_m, tile_n, tile_k = (config.tile_m, config.tile_n, config.tile_k)
epilogue_tile_n = config.epilogue_tile_n
max_concurrent_steps = config.max_concurrent_steps
block_tile_m = tile_m
if collective:
tile_m *= 2
tile_n *= 2
k_iters = k // tile_k
if collective:
m_index, n_index, cluster_idx = grid_indices
block_m_index = m_index * 2 + cluster_idx
is_lead_block = cluster_idx == 0
else:
m_index, n_index = grid_indices
cluster_idx = 0 # type: ignore
block_m_index = m_index
is_lead_block = True # type: ignore
wg_idx = lax.axis_index(wg_axis)
collective_axis = collective_axes[0] if collective else None
TMA_WARP = 0
MMA_WARP = 1
COMPUTE_WG = 0
STORE_WG = 1
block_slice_m = pl.ds(block_m_index * block_tile_m, block_tile_m)
slice_m = pl.ds(m_index * tile_m, tile_m)
slice_n = pl.ds(n_index * tile_n, tile_n)
acc_slot = lax.rem(local_index, jnp.int32(2))
regs_layout = plgpu.Layout.TCGEN05
@pl.when(wg_idx == COMPUTE_WG)
@jax.named_scope("compute_wg")
def _():
@pl.core_map(plgpu.WarpMesh(axis_name="warp"))
def _per_warp():
warp_id = lax.axis_index("warp")
@pl.when(warp_id == TMA_WARP)
def _memory():
def _loop_body(ki, _):
slice_k = pl.ds(ki * tile_k, tile_k)
slot = lax.rem(ki, max_concurrent_steps)
@pl.when(jnp.logical_or(ki >= max_concurrent_steps,
local_index > 0))
def _():
plgpu.barrier_wait(consumed_barrier.at[slot])
plgpu.copy_gmem_to_smem(
a_gmem.at[slice_m, slice_k],
a_smem.at[slot],
a_tma_barrier.at[slot],
partitioned_axis=0 if collective else None,
collective_axes=collective_axis,
)
plgpu.copy_gmem_to_smem(
b_gmem.at[slice_k, slice_n],
b_smem.at[slot],
b_tma_barrier.at[slot],
partitioned_axis=1 if collective else None,
collective_axes=collective_axis,
)
lax.fori_loop(0, k_iters, _loop_body, None)
@pl.when(jnp.logical_and(warp_id == MMA_WARP, local_index > 1))
def _wait_store():
plgpu.barrier_wait(store_done_barrier.at[acc_slot])
@pl.when(jnp.logical_and(warp_id == MMA_WARP, is_lead_block))
def _compute():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
plgpu.barrier_wait(a_tma_barrier.at[slot])
plgpu.barrier_wait(b_tma_barrier.at[slot])
is_last_iter = ki >= k_iters - 1
acc_tmem_slice = acc_tmem.at[:, pl.ds(acc_slot * tile_n, tile_n)]
plgpu.tcgen05_mma(
acc_tmem_slice,
a_smem.at[slot],
b_smem.at[slot],
consumed_barrier.at[slot],
accumulate=(ki > 0),
collective_axis=collective_axis,
)
@pl.when(is_last_iter)
def _():
plgpu.tcgen05_commit_arrive(
mma_done_barrier.at[acc_slot],
collective_axis=collective_axis,
)
lax.fori_loop(0, k_iters, _loop_body, None)
@pl.when(wg_idx == STORE_WG)
@jax.named_scope("store_wg")
def _():
plgpu.barrier_wait(mma_done_barrier.at[acc_slot])
acc_tmem_slot = acc_tmem.at[:, pl.ds(acc_slot * tile_n, tile_n)]
step_out_gmem = out_gmem.at[block_slice_m, slice_n]
# group_info contains start/size info relative to the logical
# tiling (tile_m) but because for collective matmuls we use 2 CTAs per
# logical block, but we need to compute the start/size relative to the
# current block.
# For example, for the following parameters:
# block_tile_m=64 (tile_m=128)
# group_info.start_within_block=60
# group_info.actual_size=37
# The requested copy will be split across both blocks
# Memory: | Block 0 | Block 1 |
# |--- 64 ---|--- 64 ---|
# Copy: |-- 37 --|
# Where block 0 copies rows 60-64 (4 rows total) and block 1 copies
# the remaining rows 64-97 (33 rows total).
smem_start = group_info.start_within_block - cluster_idx * block_tile_m
smem_start = lax.max(smem_start, jnp.int32(0))
def _clamp(min, x, max):
return lax.max(lax.min(x, max), min)
block0_copy_size = _clamp(
jnp.int32(0),
block_tile_m - group_info.start_within_block,
group_info.actual_size)
block_local_size = lax.select(is_lead_block,
# block 0 copies up to end of the first block or actual_size,
# whichever comes first.
block0_copy_size,
# block 1 copies the remaining rows that block 0 did not copy.
group_info.actual_size - block0_copy_size
)
for ni in range(tile_n // epilogue_tile_n):
acc_smem[...] = plgpu.async_load_tmem(
acc_tmem_slot.at[:, pl.ds(ni * epilogue_tile_n, epilogue_tile_n)],
layout=regs_layout).astype(dtype)
plgpu.commit_smem()
cur_smem_idx = smem_start
remaining_rows = min(block_tile_m, m)
while remaining_rows > 0:
const_rows_len = 1 << int(math.log2(remaining_rows))
remaining_rows //= 2
@pl.when(block_local_size & const_rows_len != 0)
def _():
o_smem_slice = acc_smem.at[pl.ds(cur_smem_idx, const_rows_len)]
o_gref_slice = step_out_gmem.at[
pl.ds(cur_smem_idx, const_rows_len),
pl.ds(ni * epilogue_tile_n, epilogue_tile_n),
]
plgpu.copy_smem_to_gmem(o_smem_slice, o_gref_slice)
cur_smem_idx += block_local_size & const_rows_len
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
plgpu.wait_load_tmem() # Load must complete before we continue.
plgpu.barrier_arrive(store_done_barrier.at[acc_slot])
def ragged_dot_kernel(a, b, group_sizes, config: TuningConfig):
dtype = a.dtype
if a.dtype != b.dtype:
raise ValueError(
f"Matmul LHS and RHS have incompatible dtypes {a.dtype} vs {b.dtype}"
)
m, k = a.shape
num_groups, k2, n = b.shape
if num_groups != group_sizes.shape[0]:
raise ValueError("RHS and group_sizes have incompatible shapes.")
if k != k2:
raise ValueError(
"Matmul LHS and RHS have incompatible shapes "
f"{a.shape} vs {b.shape[1:]}"
)
collective = config.collective
tile_m, tile_n, tile_k = (config.tile_m, config.tile_n, config.tile_k)
block_tile_m = tile_m
block_tile_n = tile_n
if collective:
tile_m *= 2
tile_n *= 2
m_iters = m // tile_m
n_iters = n // tile_n
max_concurrent_steps = config.max_concurrent_steps
epilogue_tile_n = config.epilogue_tile_n
if tile_n % epilogue_tile_n != 0:
raise ValueError(
f"{tile_n=} must be divisible by {epilogue_tile_n=}"
)
if m % tile_m != 0:
raise ValueError(f"{m=} must be divisible by {tile_m=}")
if n % tile_n != 0:
raise ValueError(f"{n=} must be divisible by {tile_n=}")
if k % tile_k != 0:
raise ValueError(f"{k=} must be divisible by {tile_k=}")
swizzle = plgpu.find_swizzle(tile_k * jnp.dtype(dtype).itemsize * 8)
swizzle_elems = swizzle // jnp.dtype(dtype).itemsize
transforms = (
plgpu.TilingTransform((8, swizzle_elems)),
plgpu.SwizzleTransform(swizzle),
)
def kernel(a_gmem, b_gmem, group_sizes_gmem, out_gmem):
linear_grid = (m_iters + num_groups - 1) * n_iters
group_sizes_regs = [group_sizes_gmem[i] for i in range(num_groups)]
cluster_idx = lax.axis_index("x")
@functools.partial(pl.run_scoped,
a_smem=plgpu.SMEM(
(max_concurrent_steps, block_tile_m, tile_k),
dtype, transforms=transforms
),
b_smem=plgpu.SMEM(
(max_concurrent_steps, tile_k, block_tile_n),
dtype, transforms=transforms
),
# Temporary SMEM used for storing accumulator output to GMEM.
acc_smem=plgpu.SMEM(
(block_tile_m, epilogue_tile_n), dtype),
# a/b_tma_barrier
a_tma_barrier=plgpu.Barrier(num_arrivals=1, num_barriers=max_concurrent_steps),
b_tma_barrier=plgpu.Barrier(num_arrivals=1, num_barriers=max_concurrent_steps),
# store_done_barrier, double-buffered
store_done_barrier=plgpu.Barrier(num_arrivals=1, num_barriers=2,
orders_tensor_core=True),
# mma_done_barrier, double-buffered
mma_done_barrier=plgpu.Barrier(num_arrivals=1, num_barriers=2,
orders_tensor_core=True),
# consumed_barrier
consumed_barrier=plgpu.Barrier(
num_arrivals=1,
num_barriers=max_concurrent_steps,
orders_tensor_core=True,
),
# Accumulator TMEM (double-buffered)
acc_tmem=plgpu.TMEM(
(block_tile_m, tile_n * 2), jnp.float32, collective=collective),
collective_axes=("wg",)
)
def _scoped(**ref_kwargs):
@plgpu.nd_loop(grid=(linear_grid,),
collective_axes="sm")
def mn_loop(loop_info: plgpu.NDLoopInfo): # pylint: disable=unused-variable
linear_idx, = loop_info.index
local_index = loop_info.local_index # type: ignore
m_index, n_index = plgpu.planar_snake(
linear_idx,
(m_iters + num_groups - 1, n_iters),
config.grid_minor_dim,
config.grid_tile_width,
)
with jax.named_scope("create_group_info"):
group_info = ragged_dot_mgpu.GroupInfo.create(
group_sizes_regs, tile_m, m_index
)
do_matmul(
a_gmem,
b_gmem.at[group_info.group_id],
out_gmem,
grid_indices=(group_info.block, n_index, cluster_idx),
wg_axis="wg",
collective_axes=("x",) if collective else (),
local_index=local_index, # type: ignore
config=config,
group_info=group_info,
**ref_kwargs
)
num_sms = jax.local_devices()[0].core_count
compiler_params = None
f = plgpu.kernel(
kernel,
compiler_params=compiler_params,
kernel_name=f"ragged_dot_kernel_{str(config)}",
out_shape=jax.ShapeDtypeStruct((m, n), dtype),
grid=(num_sms//2,) if collective else (num_sms,),
grid_names=("sm",),
num_threads=2,
thread_name="wg",
cluster_names=("x",) if collective else (),
cluster=(2,) if collective else (),
)
return f(a, b, group_sizes)
def ragged_dot_reference(a, b, g):
return lax.ragged_dot(a, b, g, preferred_element_type=jnp.float16)
def sample_group_sizes(key: jax.Array,
num_groups: int,
num_elements: int,
alpha: float = 10.0,
):
"""Sample group sizes.
Args:
key: PRNG key.
num_groups: Number of groups to sample.
num_elements: Total number of elements to sample.
alpha: Shape parameter. The lower the alpha, the more imbalanced the
group sizes will be. As alpha approaches infinity, the group sizes
approach a uniform distribution.
Returns:
A jax.Array of shape (num_groups,) that sums to num_elements.
"""
probs_key, sample_key = jax.random.split(key)
probs = jax.random.dirichlet(probs_key, jnp.ones((num_groups,)) * alpha)
return jax.random.multinomial(
sample_key, num_elements, probs).astype(jnp.int32)
def main(_) -> None:
M = 16 * 1024
K = 2048
N = 16 * 1024
num_groups = 16
group_sizes = sample_group_sizes(jax.random.key(0), num_groups, M, alpha=10.0)
print(f"==== {M=} {N=} {K=} {num_groups=}====")
matmul_flops = 2 * M * N * K
peak_flops = 2.25e15 # f16 TensorCore peak = 2250 TFLOPS
a = jax.random.uniform(jax.random.key(1), (M, K), jnp.float16)
b = jax.random.uniform(jax.random.key(2), (num_groups, K, N), jnp.float16)
tuning_it = itertools.product(
(128,), # tile_m
(128,), # tile_n
(64,), # tile_k
(1, 8, 12, 16), # grid_tile_width
blackwell_matmul_mgpu.MatmulDimension, # grid_minor_dim
(4, 6) # max_concurrent_steps
)
best_util = -float("inf")
for (tile_m, tile_n, tile_k, grid_tile_width, grid_minor_dim,
max_concurrent_steps,) in tuning_it:
config = TuningConfig(
tile_m=tile_m,
tile_n=tile_n,
tile_k=tile_k,
grid_tile_width=grid_tile_width,
grid_minor_dim=grid_minor_dim,
max_concurrent_steps=max_concurrent_steps,
collective=True,
)
try:
out, runtime_ms = profiler.measure(
functools.partial(ragged_dot_kernel, config=config),
iterations=10
)(a, b, group_sizes)
runtime_ms = np.median(runtime_ms if runtime_ms else []) # type: ignore
except ValueError as e:
if ("exceeds available shared memory" in e.args[0] or
"Accumulator layout mismatch:" in e.args[0]):
print(e.args[0])
continue
raise
expected = ragged_dot_reference(a, b, group_sizes)
np.testing.assert_allclose(out, expected)
runtime_us = runtime_ms * 1e3 # type: ignore
optimal_time = matmul_flops / peak_flops * 1e6 # us
achieved_tc_util = optimal_time / runtime_us * 100
if achieved_tc_util > best_util:
best_util = achieved_tc_util
print(
f"{tile_m=} {tile_n=} {tile_k=} {grid_tile_width=} {grid_minor_dim=} {max_concurrent_steps=} "
f"{runtime_us:<7.1f}us"
f" = {achieved_tc_util:4.1f}% TC utilization"
)
print(f"\tBest utilization: {best_util:4.1f}%")
if __name__ == "__main__":
from absl import app
jax.config.config_with_absl()
app.run(main)
| {
"repo_id": "jax-ml/jax",
"file_path": "jax/experimental/pallas/ops/gpu/blackwell_ragged_dot_mgpu.py",
"license": "Apache License 2.0",
"lines": 403,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
jax-ml/jax:jax/experimental/pallas/ops/gpu/collective_matmul_mgpu.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A collective matmul kernel implemented using Mosaic GPU."""
import functools
import itertools
import jax
import os
from jax import lax
from jax.experimental import multihost_utils
from jax.experimental import pallas as pl
from jax.experimental.mosaic.gpu import profiler
from jax.experimental.pallas import mosaic_gpu as plgpu
from jax.experimental.pallas.ops.gpu import hopper_matmul_mgpu
import jax.numpy as jnp
MatmulDimension = hopper_matmul_mgpu.MatmulDimension
TuningConfig = hopper_matmul_mgpu.TuningConfig
def is_nvshmem_used() -> bool:
return (
"XLA_FLAGS" in os.environ
and "--xla_gpu_experimental_enable_nvshmem" in os.environ["XLA_FLAGS"]
)
def all_gather_lhs_matmul(
lhs: jax.Array,
rhs: jax.Array,
axis_name,
*,
config: hopper_matmul_mgpu.TuningConfig,
dtype: jnp.dtype = jnp.float16,
) -> jax.Array:
if (
num_devices := jax.device_count()
) != jax.process_count() and num_devices != jax.local_device_count():
raise ValueError(
"Kernel requires either 1 process per single GPU or 1 process per all"
" GPUs."
)
if (axis_size := lax.axis_size(axis_name)) != num_devices:
raise ValueError("The kernel can only work over all devices in a Mesh.")
if jnp.dtype(dtype) not in map(jnp.dtype, [jnp.float16, jnp.bfloat16]):
raise NotImplementedError(f"Only f16 and bf16 are supported, got {dtype=}")
if config.cluster_dimension is not None:
raise NotImplementedError("Cluster dimension must be None for all-gather matmuls.")
m_shard, k = lhs.shape
k2, n_shard = rhs.shape
if k != k2:
raise ValueError(
f"lhs and rhs must have the same contraction size, got {k} and {k2}."
)
if (element_type := lhs.dtype) != rhs.dtype:
raise ValueError(
f"lhs and rhs must have the same element type, got {element_type} and"
f" {rhs.dtype}."
)
tile_m, tile_n, tile_k = config.tile_m, config.tile_n, config.tile_k
max_concurrent_steps = config.max_concurrent_steps
if max_concurrent_steps < 2:
raise ValueError("max_concurrent_steps must be >= 2")
cta_tile_m = tile_m * (1 + (config.wg_dimension == MatmulDimension.M))
epi_tile_n = config.epi_tile_n or tile_n
epi_tile_m = config.epi_tile_m or tile_m
if tile_n % epi_tile_n != 0:
raise ValueError(f"{tile_n=} must be divisible by {epi_tile_n=}")
if tile_m % epi_tile_m != 0:
raise ValueError(f"{tile_m=} must be divisible by {epi_tile_m=}")
num_sms = jax.devices()[0].core_count # 132 for H100 SXM GPUs.
def kernel_body(lhs_local_ref, rhs_ref, out_ref, scratch_ref):
received_sem = pl.get_global(plgpu.SemaphoreType.REGULAR)
wg_idx = lax.axis_index("wg")
dev_id = lax.axis_index(axis_name)
send_dev_id = lax.rem(dev_id + axis_size - 1, jnp.int32(axis_size))
send_scratch_ref = plgpu.remote_ref(scratch_ref, send_dev_id)
def send_lhs(m_idx, n_idx, k_idx, a_smem, b_smem, send_ref, should_send):
del b_smem # Unused.
# We only send when n_idx == 0 to avoid sending the same data
# multiple times when revisiting lhs.
@pl.when(should_send & jnp.bool(n_idx == 0))
def _():
k_slice = pl.ds(k_idx * tile_k, tile_k)
m_slice = pl.ds(m_idx * cta_tile_m, cta_tile_m)
plgpu.copy_smem_to_gmem(a_smem, send_ref.at[m_slice, k_slice])
# We only delay release by 1 step, so we need to wait for the
# previous copies.
plgpu.wait_smem_to_gmem(1, wait_read_only=True)
def device_step(lhs_source_ref, device_offset):
# Invariant: lhs_source_ref is ready to be used
next_scratch_slot = device_offset
out_device_m_slice = pl.ds(
lax.rem(device_offset + dev_id, jnp.int32(num_devices)) * m_shard,
m_shard,
)
is_send_wg = wg_idx == 0
has_send_space = next_scratch_slot < num_devices - 1
should_send = is_send_wg & has_send_space
# This reuses the regular matmul kernel, only with the exception of
# inserting send_lhs into the pipeline.
# TODO(apaszke): This contains run_scoped inside, meaning that it will
# synchronize all threads at each device step. If we optimize the barrier
# below, then it might be better to move it out to make bubbles smaller.
hopper_matmul_mgpu.kernel(
lhs_source_ref, # Use the lhs from previous step.
rhs_ref, # Use the same rhs for all steps.
None, # No C.
out_ref.at[out_device_m_slice], # Use a slice of the output.
config=config,
pipeline_callback=functools.partial(
send_lhs,
send_ref=send_scratch_ref.at[next_scratch_slot],
should_send=should_send,
),
delay_release=1,
)
# Wait for the next scratch to arrive --- see the device loop invariant.
@pl.when(should_send)
def _signal():
# TODO(apaszke): We could do this signal a lot earlier if we better
# control the order of sends. If we tile the grid along N, then we can
# signal as soon as everyone moves on from the first column tile.
# Make sure the copy is done and signal the receiving device.
plgpu.wait_smem_to_gmem(0, wait_read_only=False)
pl.semaphore_signal(received_sem, device_id=send_dev_id)
@pl.when(next_scratch_slot < num_devices - 1)
def _wait():
pl.semaphore_wait(received_sem, value=(device_offset + 1) * num_sms, decrement=False)
# We peel the first step to copy data directly form lhs_local_ref.
device_step(lhs_local_ref, 0)
@pl.loop(1, num_devices)
def _device_loop(device_offset):
device_step(scratch_ref.at[device_offset - 1], device_offset)
# Make sure all copies are fully done.
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
result, _ = plgpu.kernel(
kernel_body,
out_shape=[
# The output, with its M dimension all-gathered.
jax.ShapeDtypeStruct((axis_size * m_shard, n_shard), dtype),
# The scratch buffer used for the all-gather.
jax.ShapeDtypeStruct((num_devices - 1, m_shard, k), dtype),
],
grid=(num_sms,),
grid_names=("cluster_grid",),
num_threads=3,
thread_name="wg",
cluster=(1,),
cluster_names=("cluster",),
)(lhs, rhs)
return result
def _min_results_across_devices(kernels_ms : list[tuple[str, float]]) -> float:
# We choose the minimum across processes to choose the runtime that didn't
# include devices waiting for other devices.
if is_nvshmem_used():
time_us = sum(t * 1e3 for _, t in kernels_ms)
return min(multihost_utils.process_allgather(time_us).tolist())
# profiler.measures measures all devices visible to the process, so we
# need to select the mimimum result of each kernel across devices.
# This code relies on the fact that with collective metadata a single kernel
# with unique name is launched on each device.
min_values : dict[str, float] = {}
for kernel_name, t in kernels_ms:
if kernel_name not in min_values or t < min_values[kernel_name]:
min_values[kernel_name] = t
return sum(time_ms * 1e3 for time_ms in min_values.values())
def _run_example():
P = jax.sharding.PartitionSpec
m_shard = 1024
n_shard = 4096
k = 4096
dtype = jnp.bfloat16
shards = jax.device_count()
mesh = jax.make_mesh(
(shards,), ("x",), axis_types=(jax.sharding.AxisType.Explicit,)
)
jax.set_mesh(mesh)
# We measure time per-shard and so we only need FLOPs per shard.
matmul_flops = 2 * (shards * m_shard) * n_shard * k
peak_flops = 990e12 # f16 TensorCore peak = 990 TFLOPS
optimal_time = matmul_flops / peak_flops * 1e6 # us
a = jax.random.normal(jax.random.key(1), (shards * m_shard, k), dtype)
b = jax.random.normal(jax.random.key(2), (k, shards * n_shard), dtype)
a = jax.sharding.reshard(a, P("x", None))
b = jax.sharding.reshard(b, P(None, "x"))
_, ref_kernels_ms = profiler.measure(jax.jit(
jax.shard_map(
lambda x, y: lax.all_gather(x, "x", axis=0, tiled=True) @ y,
out_specs=P(None, "x"),
check_vma=False,
)
), aggregate=False)(a, b)
ref_time_us = _min_results_across_devices(ref_kernels_ms)
ref_util = optimal_time / ref_time_us * 100
tuning_it = itertools.product(
(128, 256,), # tile_m
(64, 128), # tile_n
(64,), # tile_k
(4,), # max_concurrent_steps
(MatmulDimension.M, MatmulDimension.N), # grid_minor_dim
(4, 8, 16), # grid_tile_width
MatmulDimension, # wg_dimension
)
best_util = 0.0
best_runtime = float("inf")
def build_kernel(**kwargs):
return jax.jit(
jax.shard_map(
functools.partial(all_gather_lhs_matmul, **kwargs),
out_specs=P(None, "x"),
check_vma=False,
)
)
for tile_m, tile_n, tile_k, max_concurrent_steps, grid_minor_dim, grid_tile_width, wg_dimension in tuning_it:
try:
config = TuningConfig(
tile_m=tile_m,
tile_n=tile_n,
tile_k=tile_k,
max_concurrent_steps=max_concurrent_steps,
grid_minor_dim=grid_minor_dim,
grid_tile_width=grid_tile_width,
wg_dimension=wg_dimension,
)
_, kernels_ms = profiler.measure(
build_kernel(axis_name="x", config=config, dtype=dtype),
aggregate=False,
)(a, b)
except ValueError as e:
if "exceeds available shared memory" in e.args[0]: # Ignore SMEM OOMs.
continue
raise
runtime_us = _min_results_across_devices(kernels_ms)
achieved_tc_util = optimal_time / runtime_us * 100
if achieved_tc_util > best_util:
best_runtime = runtime_us
best_util = achieved_tc_util
print(
f"{tile_m=} {tile_n=} {tile_k=} {max_concurrent_steps=} {grid_minor_dim=} {grid_tile_width=} {wg_dimension=}: "
f"{runtime_us:<7.1f}us"
f" = {achieved_tc_util:4.1f}% TC utilization"
)
print(f"\tBest: {best_runtime:<7.1f}us = {best_util:4.1f}% TC utilization")
print(f"\tRef: {ref_time_us:<7.1f}us = {ref_util:4.1f}% TC utilization")
if __name__ == "__main__":
if is_nvshmem_used():
from jax._src import test_multiprocess as jt_multiprocess # pytype: disable=import-error
jt_multiprocess.main(shard_main=_run_example)
else:
from jax._src.config import config as jax_config
from absl import app
jax_config.config_with_absl()
app.run(lambda _: _run_example())
| {
"repo_id": "jax-ml/jax",
"file_path": "jax/experimental/pallas/ops/gpu/collective_matmul_mgpu.py",
"license": "Apache License 2.0",
"lines": 259,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
jax-ml/jax:jax/experimental/pallas/ops/gpu/hopper_matmul_mgpu.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Matrix Multiplication kernel for Hopper GPUs."""
import statistics
import dataclasses
import enum
import functools
import itertools
import jax
from jax import lax
from jax._src import test_util as jtu # noqa: F401
from jax.experimental.mosaic.gpu import profiler
import jax.experimental.pallas as pl
import jax.experimental.pallas.mosaic_gpu as plgpu
from jax.extend import backend
import jax.numpy as jnp
import numpy as np
# mypy: ignore-errors
class MatmulDimension(enum.IntEnum):
M = 0
N = 1
def __str__(self):
return self.name
def __repr__(self):
return self.name
@dataclasses.dataclass(frozen=True)
class TuningConfig:
tile_m: int
tile_n: int
tile_k: int
max_concurrent_steps: int
epi_tile_n: int | None = 64 # This needs to be lowered for for small N.
epi_tile_m: int | None = 64
grid_minor_dim: MatmulDimension = MatmulDimension.N
grid_tile_width: int = 1
wg_dimension: MatmulDimension = MatmulDimension.N
cluster_dimension: None | MatmulDimension = None
# pipeline_callback and delay_release are only used for collective matmuls.
def kernel(a_gmem, b_gmem, c_gmem, out_gmem, config: TuningConfig,
pipeline_callback=None, delay_release=0):
dtype = a_gmem.dtype
out_dtype = out_gmem.dtype
assert b_gmem.dtype == dtype
if c_gmem is not None:
assert c_gmem.dtype == out_dtype
m, k = a_gmem.shape
k2, n = b_gmem.shape
assert k == k2
tile_m, tile_n, tile_k = config.tile_m, config.tile_n, config.tile_k
max_concurrent_steps = config.max_concurrent_steps
swizzle = plgpu.find_swizzle(tile_k * jnp.dtype(dtype).itemsize * 8)
swizzle_elems = swizzle // jnp.dtype(dtype).itemsize
transforms = (
plgpu.TilingTransform((8, swizzle_elems)), plgpu.SwizzleTransform(swizzle)
)
cta_tile_m = tile_m * (1 + (config.wg_dimension == MatmulDimension.M))
cta_tile_n = tile_n * (1 + (config.wg_dimension == MatmulDimension.N))
cluster_tile_m = cta_tile_m * (1 + (config.cluster_dimension == MatmulDimension.M))
cluster_tile_n = cta_tile_n * (1 + (config.cluster_dimension == MatmulDimension.N))
if m % cluster_tile_m != 0:
raise ValueError(f"{m=} must be divisible by {cluster_tile_m} for the given config")
if n % cluster_tile_n != 0:
raise ValueError(f"{n=} must be divisible by {cluster_tile_n} for the given config")
if k % tile_k != 0:
raise ValueError(f"{k=} must be divisible by {tile_k=}")
m_iters = m // cluster_tile_m
n_iters = n // cluster_tile_n
k_iters = k // tile_k
epi_tile_m = config.epi_tile_m or tile_m
epi_tile_n = config.epi_tile_n or tile_n
# We don't need multiple slots if there's only one epilogue tile.
num_out_slots = min(2, (tile_m * tile_n) // (epi_tile_m * epi_tile_n))
out_swizzle = plgpu.find_swizzle(epi_tile_n * jnp.dtype(out_dtype).itemsize * 8)
out_swizzle_elems = out_swizzle // jnp.dtype(out_dtype).itemsize
out_transforms = (
plgpu.TilingTransform((8, out_swizzle_elems)),
plgpu.SwizzleTransform(out_swizzle),
)
def get_pipeline(pipeline_body, compute_context):
return plgpu.emit_pipeline_warp_specialized(
pipeline_body,
grid=(k_iters,),
memory_registers=40,
in_specs=[
plgpu.BlockSpec(
(cta_tile_m, tile_k),
lambda k: (0, k),
transforms=transforms,
memory_space=plgpu.SMEM,
delay_release=delay_release,
collective_axes=("cluster",)
if config.cluster_dimension == MatmulDimension.N
else (),
),
plgpu.BlockSpec(
(tile_k, cta_tile_n),
lambda k: (k, 0),
transforms=transforms,
memory_space=plgpu.SMEM,
delay_release=delay_release,
collective_axes=("cluster",)
if config.cluster_dimension == MatmulDimension.M
else (),
),
],
wg_axis="wg",
num_compute_wgs=2,
max_concurrent_steps=max_concurrent_steps,
compute_context=compute_context,
)
# Functions don't influence the allocations necessary to run the pipeline.
ignore = lambda *_, **__: None
@functools.partial(
pl.run_scoped,
pipeline_allocs=get_pipeline(ignore, ignore).get_allocations(a_gmem, b_gmem),
out_smem=plgpu.SMEM(
(2, num_out_slots, epi_tile_m, epi_tile_n),
out_dtype,
transforms=out_transforms,
),
c_barrier=None if c_gmem is None else plgpu.Barrier(num_barriers=2 * num_out_slots),
collective_axes="wg",
)
def _pipeline_scope(pipeline_allocs, out_smem, c_barrier):
wg_idx = lax.axis_index("wg")
cta_idx = lax.axis_index("cluster")
@plgpu.nd_loop((m_iters * n_iters,), collective_axes="cluster_grid")
def _mn_loop(loop_info: plgpu.NDLoopInfo):
(lin_idx,) = loop_info.index
m_cluster_idx, n_cluster_idx = plgpu.planar_snake(
lin_idx,
(m_iters, n_iters),
config.grid_minor_dim,
config.grid_tile_width,
)
m_idx = m_cluster_idx
n_idx = n_cluster_idx
if config.cluster_dimension == MatmulDimension.M:
m_idx = m_cluster_idx * 2 + cta_idx
elif config.cluster_dimension == MatmulDimension.N:
n_idx = n_cluster_idx * 2 + cta_idx
cta_m_slice = pl.ds(m_idx * cta_tile_m, cta_tile_m)
cta_n_slice = pl.ds(n_idx * cta_tile_n, cta_tile_n)
if config.wg_dimension == MatmulDimension.M:
wg_m_slice = pl.ds(wg_idx * tile_m, tile_m)
wg_n_slice = slice(None)
else:
wg_m_slice = slice(None)
wg_n_slice = pl.ds(wg_idx * tile_n, tile_n)
def compute_context(eval_pipeline):
@functools.partial(
pl.run_scoped, acc_ref=plgpu.ACC((tile_m, tile_n), jnp.float32)
)
def _acc_scope(acc_ref):
eval_pipeline(acc_ref)
acc = acc_ref[...].astype(out_dtype)
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
for epi_mi in range(tile_m // epi_tile_m):
for epi_ni in range(tile_n // epi_tile_n):
epi_m_slice = slice(epi_mi * epi_tile_m, (epi_mi + 1) * epi_tile_m)
epi_n_slice = slice(epi_ni * epi_tile_n, (epi_ni + 1) * epi_tile_n)
slot = (epi_mi * (tile_n // epi_tile_n) + epi_ni) % 2
plgpu.wait_smem_to_gmem(1, wait_read_only=True)
if c_gmem is None:
out_smem[wg_idx, slot] = acc[epi_m_slice, epi_n_slice]
else:
# TODO: Consider using triple-buffering so to not end up issuing
# the copy and immediately blocking on it
plgpu.copy_gmem_to_smem(
c_gmem.at[cta_m_slice, cta_n_slice]
.at[wg_m_slice, wg_n_slice]
.at[epi_m_slice, epi_n_slice],
out_smem.at[wg_idx, slot],
c_barrier.at[wg_idx * num_out_slots + slot],
)
plgpu.barrier_wait(c_barrier.at[wg_idx * num_out_slots + slot])
out_smem[wg_idx, slot] += acc[epi_m_slice, epi_n_slice]
plgpu.commit_smem()
plgpu.copy_smem_to_gmem(
out_smem.at[wg_idx, slot],
out_gmem.at[cta_m_slice, cta_n_slice]
.at[wg_m_slice, wg_n_slice]
.at[epi_m_slice, epi_n_slice],
)
def mma_body(idxs, a_smem, b_smem, acc_ref):
plgpu.wgmma(acc_ref, a_smem.at[wg_m_slice], b_smem.at[:, wg_n_slice])
if pipeline_callback is not None:
(k_idx,) = idxs
pipeline_callback(m_idx, n_idx, k_idx, a_smem, b_smem)
plgpu.wgmma_wait(delay_release)
return acc_ref
get_pipeline(mma_body, compute_context)(
a_gmem.at[cta_m_slice, :],
b_gmem.at[:, cta_n_slice],
allocations=pipeline_allocs,
)
# Await all transfers before we exit.
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
def matmul(a, b, c, config: TuningConfig):
dtype = a.dtype
if a.dtype != b.dtype:
raise ValueError(
f"Matmul LHS and RHS have incompatible dtypes {a.dtype} vs {b.dtype}"
)
m, k = a.shape
k2, n = b.shape
assert k == k2
if k != k2:
raise ValueError(
f"Matmul LHS and RHS have incompatible shapes {a.shape} vs {b.shape}"
)
if c is None:
out_dtype = dtype
else:
if c.shape != (m, n):
raise ValueError(f"C has incompatible shape {c.shape} vs {(m, n)}")
out_dtype = c.dtype
tile_m, tile_n = config.tile_m, config.tile_n
epi_tile_n = config.epi_tile_n or tile_n
epi_tile_m = config.epi_tile_m or tile_m
config = dataclasses.replace(config, epi_tile_n=epi_tile_n, epi_tile_m=epi_tile_m)
num_sms = backend.get_default_device().core_count
cluster_size = 1 + (config.cluster_dimension is not None)
f = plgpu.kernel(
functools.partial(kernel, config=config),
out_shape=jax.ShapeDtypeStruct((m, n), out_dtype),
grid=(num_sms // cluster_size,),
grid_names=("cluster_grid",),
cluster=(cluster_size,),
cluster_names=("cluster",),
num_threads=3,
thread_name="wg",
)
return f(a, b, c)
def main(_) -> None:
problem_it = [(4096, 8192, 4096)]
for M, N, K in problem_it:
print(f"==== {M=} {N=} {K=} ====")
matmul_flops = 2 * M * N * K
peak_flops = 990e12 # f16 TensorCore peak = 990 TFLOPS
a = jax.random.uniform(jax.random.key(0), (M, K), jnp.float16)
b = jax.random.uniform(jax.random.key(1), (K, N), jnp.float16)
ref = a @ b
tuning_it = itertools.product(
(128, 256,), # tile_m
(64, 128), # tile_n
(64,), # tile_k
(4,), # max_concurrent_steps
(True,), # Tiled epilogue
(MatmulDimension.M, MatmulDimension.N), # grid_minor_dim
(4, 8, 16), # grid_tile_width
MatmulDimension, # wg_dimension
# Consider adding MatmulDimension here to try out collective TMA kernels
(None,) # cluster_dimension
)
best_util = 0.0
best_runtime = float("inf")
for tile_m, tile_n, tile_k, max_concurrent_steps, tiled_epilogue, grid_minor_dim, grid_tile_width, wg_dimension, cluster_dimension in tuning_it:
config = TuningConfig(
tile_m=tile_m,
tile_n=tile_n,
tile_k=tile_k,
max_concurrent_steps=max_concurrent_steps,
epi_tile_n=64 if tiled_epilogue else None,
epi_tile_m=64 if tiled_epilogue else None,
grid_minor_dim=grid_minor_dim,
grid_tile_width=grid_tile_width,
wg_dimension=wg_dimension,
cluster_dimension=cluster_dimension,
)
try:
out, runtimes_ms = profiler.measure(
functools.partial(matmul, config=config), iterations=10,
)(a, b, None)
assert runtimes_ms is not None
runtime_ms = statistics.median(runtimes_ms)
except ValueError as e:
if "exceeds available shared memory" in e.args[0]: # Ignore SMEM OOMs.
continue
raise
np.testing.assert_allclose(out, ref)
runtime_us = runtime_ms * 1e3 # type: ignore
optimal_time = matmul_flops / peak_flops * 1e6 # us
achieved_tc_util = optimal_time / runtime_us * 100
if achieved_tc_util > best_util:
best_runtime = runtime_us
best_util = achieved_tc_util
print(
f"{tile_m=} {tile_n=} {tile_k=} {max_concurrent_steps=} {tiled_epilogue=} {grid_minor_dim=} {grid_tile_width=} {wg_dimension=} {cluster_dimension=}:"
f" {runtime_us:<7.1f}us = {achieved_tc_util:4.1f}% TC utilization"
)
print(f"\tBest: {best_runtime:<7.1f}us = {best_util:4.1f}% TC utilization")
if __name__ == "__main__":
from absl import app
jax.config.config_with_absl()
app.run(main)
| {
"repo_id": "jax-ml/jax",
"file_path": "jax/experimental/pallas/ops/gpu/hopper_matmul_mgpu.py",
"license": "Apache License 2.0",
"lines": 307,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
jax-ml/jax:jax/experimental/pallas/ops/gpu/hopper_mixed_type_matmul_mgpu.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Matrix Multiplication kernel for Hopper GPUs."""
import statistics
import dataclasses
import enum
import functools
import itertools
import jax
from jax._src import dtypes
from jax import lax
from jax._src import test_util as jtu # noqa: F401
from jax.experimental.mosaic.gpu import profiler
import jax.experimental.pallas as pl
import jax.experimental.pallas.mosaic_gpu as plgpu
from jax.extend import backend
import jax.numpy as jnp
import numpy as np
class MatmulDimension(enum.IntEnum):
M = 0
N = 1
def __str__(self):
return self.name
def __repr__(self):
return self.name
@dataclasses.dataclass(frozen=True)
class TuningConfig:
tile_m: int
tile_n: int
tile_k: int
max_concurrent_steps: int
epi_tile_n: int | None = 64 # This needs to be lowered for for small N.
epi_tile_m: int | None = 64
grid_minor_dim: MatmulDimension = MatmulDimension.N
grid_tile_width: int = 1
wg_dimension: MatmulDimension = MatmulDimension.N
cluster_dimension: None | MatmulDimension = None
def mixed_matmul_kernel(
a: jax.Array, b: jax.Array, *, out_dtype: jnp.dtype, config: TuningConfig
) -> jax.Array:
"""Mixed-type matrix multiplication kernel for Hopper GPUs.
Specifically, this kernel implements the function
(a.as_dtype(b.dtype) @ b).astype(out_dtype).
"""
if a.dtype == b.dtype:
raise ValueError(
f"Mixed matmul LHS and RHS have the same dtype {a.dtype}. For such "
"matrix multiplications, use the `hopper_matmul_mgpu` kernel instead."
)
match (a.dtype, b.dtype):
case (jnp.int8, jnp.bfloat16):
pass
case (jnp.int8, jnp.float16):
pass
case _, _:
# We do support more combinations, but we haven't benchmarked them
# yet---so we raise for the time being.
raise NotImplementedError(
f"Unbenchmarked dtype combination: {a.dtype=} and {b.dtype=}"
)
m, k = a.shape
k2, n = b.shape
if k != k2:
raise ValueError(
f"Matmul LHS and RHS have incompatible shapes {a.shape} vs {b.shape}"
)
tile_m, tile_n, tile_k = config.tile_m, config.tile_n, config.tile_k
epi_tile_n = config.epi_tile_n or tile_n
epi_tile_m = config.epi_tile_m or tile_m
if tile_n % epi_tile_n != 0:
raise ValueError(f"{tile_n=} must be divisible by {epi_tile_n=}")
if tile_m % epi_tile_m != 0:
raise ValueError(f"{tile_m=} must be divisible by {epi_tile_m=}")
a_bits = dtypes.itemsize_bits(a.dtype)
b_bits = dtypes.itemsize_bits(b.dtype)
out_bits = dtypes.itemsize_bits(out_dtype)
a_swizzle = plgpu.find_swizzle(tile_k * a_bits, "lhs")
b_swizzle = plgpu.find_swizzle(tile_n * b_bits, "rhs")
out_swizzle = plgpu.find_swizzle(epi_tile_n * out_bits, "out")
a_transforms = (
plgpu.TilingTransform((8, a_swizzle * 8 // a_bits)),
plgpu.SwizzleTransform(a_swizzle),
)
b_transforms = (
plgpu.TilingTransform((8, b_swizzle * 8 // b_bits)),
plgpu.SwizzleTransform(b_swizzle),
)
out_transforms = (
plgpu.TilingTransform((8, out_swizzle * 8 // out_bits)),
plgpu.SwizzleTransform(out_swizzle),
)
max_concurrent_steps = config.max_concurrent_steps
cta_tile_m = tile_m * (1 + (config.wg_dimension == MatmulDimension.M))
cta_tile_n = tile_n * (1 + (config.wg_dimension == MatmulDimension.N))
cluster_tile_m = cta_tile_m * (1 + (config.cluster_dimension == MatmulDimension.M))
cluster_tile_n = cta_tile_n * (1 + (config.cluster_dimension == MatmulDimension.N))
if m % cluster_tile_m != 0:
raise ValueError(f"{m=} must be divisible by {cluster_tile_m} for the given config")
if n % cluster_tile_n != 0:
raise ValueError(f"{n=} must be divisible by {cluster_tile_n} for the given config")
if k % tile_k != 0:
raise ValueError(f"{k=} must be divisible by {tile_k=}")
m_iters = m // cluster_tile_m
n_iters = n // cluster_tile_n
k_iters = k // tile_k
def kernel(a_gmem, b_gmem, out_gmem, out_smem):
def get_pipeline(pipeline_body, compute_context):
return plgpu.emit_pipeline_warp_specialized(
pipeline_body,
grid=(k_iters,),
memory_registers=40,
in_specs=[
plgpu.BlockSpec(
(cta_tile_m, tile_k),
lambda k: (0, k),
transforms=a_transforms,
memory_space=plgpu.SMEM,
collective_axes=("cluster",)
if config.cluster_dimension == MatmulDimension.N
else (),
),
plgpu.BlockSpec(
(tile_k, cta_tile_n),
lambda k: (k, 0),
transforms=b_transforms,
memory_space=plgpu.SMEM,
collective_axes=("cluster",)
if config.cluster_dimension == MatmulDimension.M
else (),
),
],
wg_axis="wg",
num_compute_wgs=2,
max_concurrent_steps=max_concurrent_steps,
compute_context=compute_context,
)
# Functions don't influence the allocations necessary to run the pipeline.
ignore = lambda *_, **__: None
@functools.partial(
pl.run_scoped,
pipeline_allocs=get_pipeline(ignore, ignore).get_allocations(a_gmem, b_gmem),
collective_axes="wg",
)
def _pipeline_scope(pipeline_allocs):
wg_idx = lax.axis_index("wg")
cta_idx = lax.axis_index("cluster")
@plgpu.nd_loop((m_iters * n_iters,), collective_axes="cluster_grid")
def _mn_loop(loop_info: plgpu.NDLoopInfo):
(lin_idx,) = loop_info.index
m_cluster_idx, n_cluster_idx = plgpu.planar_snake(
lin_idx,
(m_iters, n_iters),
config.grid_minor_dim,
config.grid_tile_width,
)
m_idx = m_cluster_idx
n_idx = n_cluster_idx
if config.cluster_dimension == MatmulDimension.M:
m_idx = m_cluster_idx * 2 + cta_idx
elif config.cluster_dimension == MatmulDimension.N:
n_idx = n_cluster_idx * 2 + cta_idx
cta_m_slice = pl.ds(m_idx * cta_tile_m, cta_tile_m)
cta_n_slice = pl.ds(n_idx * cta_tile_n, cta_tile_n)
if config.wg_dimension == MatmulDimension.M:
wg_m_slice = pl.ds(wg_idx * tile_m, tile_m)
wg_n_slice = slice(None)
else:
wg_m_slice = slice(None)
wg_n_slice = pl.ds(wg_idx * tile_n, tile_n) # type: ignore
def compute_context(eval_pipeline):
@functools.partial(
pl.run_scoped, acc_ref=plgpu.ACC((tile_m, tile_n), jnp.float32)
)
def _acc_scope(acc_ref):
eval_pipeline(acc_ref)
acc = acc_ref[...].astype(out_dtype)
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
for epi_mi in range(tile_m // epi_tile_m):
for epi_ni in range(tile_n // epi_tile_n):
epi_m_slice = slice(epi_mi * epi_tile_m, (epi_mi + 1) * epi_tile_m)
epi_n_slice = slice(epi_ni * epi_tile_n, (epi_ni + 1) * epi_tile_n)
slot = (epi_mi * (tile_n // epi_tile_n) + epi_ni) % 2
plgpu.wait_smem_to_gmem(1, wait_read_only=True)
out_smem[wg_idx, slot] = acc[epi_m_slice, epi_n_slice]
plgpu.commit_smem()
plgpu.copy_smem_to_gmem(
out_smem.at[wg_idx, slot],
out_gmem.at[cta_m_slice, cta_n_slice]
.at[wg_m_slice, wg_n_slice]
.at[epi_m_slice, epi_n_slice],
)
def mma_body(_, a_smem, b_smem, acc_ref):
with jax.named_scope("smem_load"):
a_reg = a_smem[wg_m_slice]
with jax.named_scope("dequant"):
a_reg = a_reg.astype(b.dtype)
with jax.named_scope("wgmma"):
plgpu.wgmma(acc_ref, a_reg, b_smem.at[:, wg_n_slice])
with jax.named_scope("wgmma_wait"):
plgpu.wgmma_wait(0)
return acc_ref
get_pipeline(mma_body, compute_context)(
a_gmem.at[cta_m_slice, :],
b_gmem.at[:, cta_n_slice],
allocations=pipeline_allocs,
)
# Await all transfers before we exit.
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
# We don't need multiple slots if there's only one epilogue tile.
num_out_slots = min(2, (tile_m * tile_n) // (epi_tile_m * epi_tile_n))
num_sms = backend.get_default_device().core_count
cluster_size = 1 + (config.cluster_dimension is not None)
f = plgpu.kernel(
kernel,
out_shape=jax.ShapeDtypeStruct((m, n), out_dtype),
grid=(num_sms // cluster_size,),
grid_names=("cluster_grid",),
cluster=(cluster_size,),
cluster_names=("cluster",),
num_threads=3,
thread_name="wg",
scratch_shapes=dict(
out_smem=plgpu.SMEM(
(2, num_out_slots, epi_tile_m, epi_tile_n),
out_dtype,
transforms=out_transforms,
)
),
)
return f(a, b)
def reference(
a: jax.Array, b: jax.Array, *, out_dtype: jnp.dtype
) -> jax.Array:
"""Reference implementation of a mixed-type matrix multiplication."""
return jax.numpy.dot(a, b, preferred_element_type=jnp.float32).astype(
out_dtype
)
def main(_) -> None:
problem_it = [(4096, 8192, 4096)]
for M, N, K in problem_it:
print(f"==== {M=} {N=} {K=} ====")
matmul_flops = 2 * M * N * K
peak_flops = 990e12 # f16 TensorCore peak = 990 TFLOPS
a = jax.random.randint(
jax.random.key(0), minval=-128, maxval=127, shape=(M, K), dtype=jnp.int8
)
b = jax.random.uniform(jax.random.key(1), (K, N), jnp.bfloat16)
ref = reference(a, b, out_dtype=jnp.bfloat16)
tuning_it = itertools.product(
(64, 128, 256,), # tile_m
(64, 128), # tile_n
(64, 128), # tile_k
(4,), # max_concurrent_steps
(True,), # Tiled epilogue
(MatmulDimension.M, MatmulDimension.N), # grid_minor_dim
(4, 8, 16), # grid_tile_width
MatmulDimension, # wg_dimension
# Consider adding MatmulDimension here to try out collective TMA kernels
(None,) # cluster_dimension
)
best_util = 0.0
best_runtime = float("inf")
for tile_m, tile_n, tile_k, max_concurrent_steps, tiled_epilogue, grid_minor_dim, grid_tile_width, wg_dimension, cluster_dimension in tuning_it:
config = TuningConfig(
tile_m=tile_m,
tile_n=tile_n,
tile_k=tile_k,
max_concurrent_steps=max_concurrent_steps,
epi_tile_n=64 if tiled_epilogue else None,
epi_tile_m=64 if tiled_epilogue else None,
grid_minor_dim=grid_minor_dim,
grid_tile_width=grid_tile_width,
wg_dimension=wg_dimension,
cluster_dimension=cluster_dimension,
)
try:
out, runtimes_ms = profiler.measure(
functools.partial(
mixed_matmul_kernel, out_dtype=jnp.bfloat16, config=config
),
iterations=10,
)(a, b)
assert runtimes_ms is not None
runtime_ms = statistics.median(runtimes_ms)
except ValueError as e:
if "exceeds available shared memory" in e.args[0]: # Ignore SMEM OOMs.
continue
raise
np.testing.assert_allclose(out, ref)
runtime_us = runtime_ms * 1e3 # type: ignore
optimal_time = matmul_flops / peak_flops * 1e6 # us
achieved_tc_util = optimal_time / runtime_us * 100
if achieved_tc_util > best_util:
best_runtime = runtime_us
best_util = achieved_tc_util
print(
f"{tile_m=} {tile_n=} {tile_k=} {max_concurrent_steps=} {tiled_epilogue=} {grid_minor_dim=} {grid_tile_width=} {wg_dimension=} {cluster_dimension=}:"
f" {runtime_us:<7.1f}us = {achieved_tc_util:4.1f}% TC utilization"
)
print(f"\tBest: {best_runtime:<7.1f}us = {best_util:4.1f}% TC utilization")
if __name__ == "__main__":
from absl import app
jax.config.config_with_absl()
app.run(main)
| {
"repo_id": "jax-ml/jax",
"file_path": "jax/experimental/pallas/ops/gpu/hopper_mixed_type_matmul_mgpu.py",
"license": "Apache License 2.0",
"lines": 315,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
jax-ml/jax:jax/experimental/pallas/ops/gpu/ragged_dot_mgpu.py | # Copyright 2025 The JAX Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Ragged dot Pallas-Mosaic-GPU implementation."""
import dataclasses
import functools
import itertools
import math
import jax
from jax import lax
from jax import numpy as jnp
from jax import random
from jax._src import test_util as jtu # noqa: F401
from jax.experimental import pallas as pl
from jax.experimental.mosaic.gpu import profiler
from jax.experimental.pallas import mosaic_gpu as plgpu
import numpy as np
@dataclasses.dataclass(frozen=True)
class GroupInfo:
"""Information regarding the group being processed in a block."""
group_id: jax.Array
block: jax.Array
block_start: jax.Array
actual_start: jax.Array
actual_end: jax.Array
start_within_block: jax.Array
actual_size: jax.Array
@classmethod
def create(cls, group_lengths, tile, tid):
"""Get the group info for the current block."""
tile = jnp.int32(tile)
group_boundaries = [group_lengths[i] for i in range(len(group_lengths))]
# We usually only have very few groups, so we unroll the loop processing
# them. Normally we'd break out of the loop early, once we'd have found our
# boundary, but we can't do that when unrolling, so we rely on many selects
# to mask out the epilogue of the loop.
group_end = group_start = block = group = end = jnp.array(
0, dtype=jnp.int32
)
for i, b in enumerate(group_boundaries):
# Start/end are inclusive
start = end
end = start + b
final = end - 1
start_block = lax.div(start, tile)
final_block = lax.div(final, tile)
block_end = final_block + 1
tid_begin = start_block + i
tid_end = block_end + i
# How many blocks after is our block?
this_is_group = (tid_begin <= tid) & (tid < tid_end)
block = lax.select(this_is_group, tid - tid_begin + start_block, block)
group = lax.select(this_is_group, jnp.int32(i), group)
group_start = lax.select(this_is_group, start, group_start)
group_end = lax.select(this_is_group, end, group_end)
block_start = block * tile
actual_start = jnp.maximum(group_start, block_start)
actual_end = jnp.minimum(group_end, block_start + tile)
start_within_block = actual_start - block_start
actual_size = actual_end - actual_start
return cls(
group_id=group,
block=block,
block_start=block_start,
actual_start=actual_start,
actual_end=actual_end,
start_within_block=start_within_block,
actual_size=actual_size,
)
def ragged_dot(
lhs, # (M, K)
rhs, # (G, K, N)
*,
group_sizes, # (G,)
block_m: int,
block_n: int,
block_k: int,
max_concurrent_steps: int,
grid_block_n: int,
transpose_rhs: bool = False,
load_group_sizes_to_register: bool = True,
) -> jax.Array:
if lhs.dtype != rhs.dtype:
raise NotImplementedError(
f"lhs and rhs must have the same dtype, got {lhs.dtype} and {rhs.dtype}"
)
m, k = lhs.shape
g, k2, n = rhs.shape
if transpose_rhs:
k2, n = n, k2
if group_sizes.shape[0] != g:
raise ValueError(
f"Expected group_sizes to have shape {g} but got {group_sizes.shape}"
)
if k != k2:
raise ValueError(f"lhs.shape={k} must match rhs.shape={k2}")
if k % block_k != 0:
raise ValueError(f"k={k} must be a multiple of block_k={block_k}")
def body(rows_per_expert_gmem, lhs_gmem, rhs_gmem, o_gmem):
grid_m = pl.cdiv(m, block_m) + g - 1
grid_n = pl.cdiv(n, block_n)
grid = (grid_m * grid_n,)
@plgpu.nd_loop(grid, collective_axes="sm")
def mn_loop(loop_info: plgpu.NDLoopInfo): # pylint: disable=unused-variable
mi, ni = plgpu.planar_snake(
loop_info.index[0],
(grid_m, grid_n),
1,
grid_block_n,
)
group_info = GroupInfo.create(rows_per_expert_gmem, block_m, mi)
def acc_scope(acc_ref):
plgpu.emit_pipeline(
lambda _, lhs_smem, rhs_smem: plgpu.wgmma(
acc_ref,
lhs_smem,
plgpu.transpose_ref(rhs_smem, (1, 0)) if transpose_rhs else rhs_smem,
),
grid=(k // block_k,),
in_specs=[
plgpu.BlockSpec(
(block_m, block_k),
lambda k: (group_info.block, k),
delay_release=1,
),
plgpu.BlockSpec(
(block_n, block_k) if transpose_rhs else (block_k, block_n),
lambda k: (ni, k) if transpose_rhs else (k, ni),
delay_release=1,
),
],
max_concurrent_steps=max_concurrent_steps,
)(lhs_gmem, rhs_gmem.at[group_info.group_id])
return acc_ref[...]
acc = pl.run_scoped(acc_scope, plgpu.ACC((block_m, block_n)))
@functools.partial(
pl.run_scoped,
o_smem=plgpu.SMEM((block_m, block_n), dtype=o_gmem.dtype)
)
def store_scope(o_smem): # pylint: disable=unused-variable
o_smem[...] = acc.astype(o_smem.dtype)
plgpu.commit_smem()
smem_start = group_info.start_within_block
remaining_rows = min(block_m, m)
# TMA descriptors need to be generated with static tile sizes along each
# axis, but we do not know at compile time how many rows we will need to
# store. We only know that the number of rows to store is bounded by
# min(block_m, m).
#
# In order to work around that, we construct a logarithmic ladder of
# TMA descriptors, where each descriptor can store 2**i rows for some
# i between 0 and log2(min(block_m, m)). This allows storing any
# number of rows we will need to store, so long as this number of rows
# is between `1` and `min(block_m, m)`.
#
# E.g., imagine we have block_m = 8, m = 16. The loop below will be
# unrolled into 4 iterations, where the first one will generate a TMA
# descriptor that can store 8 rows, the second one will generate a TMA
# descriptor that can store 4 rows, etc. all the way to 1 row.
#
# At run time, we finally know the actual number of rows we need to
# store as we go through the unrolled loop iterations. Let's imagine
# that we need to store 5 rows.
#
# The first unrolled iteration will check whether we can store 8 rows.
# Since we only need to store 5 rows, we won't store anything then.
#
# The second unrolled iteration will check whether we can store 4 rows.
# We're able to store 4 rows, and are left with a single remaining row.
#
# The fourth unrolled iteration will store the single remaining row, and
# we end up with a storing scheme as follows for our 5 rows:
#
# -----------------------------------------------------------
# 0 | |
# 1 | |
# 2 | Store 4 rows |
# 3 | |
# -----------------------------------------------------------
# 4 | Store 1 row |
# -----------------------------------------------------------
while remaining_rows > 0:
const_rows_len = 1 << int(math.log2(remaining_rows))
remaining_rows //= 2
@pl.when(group_info.actual_size & const_rows_len != 0)
def _():
o_smem_slice = o_smem.at[pl.ds(smem_start, const_rows_len)]
o_gref_slice = o_gmem.at[
pl.ds(group_info.block_start + smem_start, const_rows_len),
pl.ds(ni * block_n, block_n),
]
plgpu.copy_smem_to_gmem(o_smem_slice, o_gref_slice)
smem_start += group_info.actual_size & const_rows_len
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
# There are 132 SMs on a H100 SXM GPU.
num_sms = 132
kernel = plgpu.kernel(
body,
out_shape=jax.ShapeDtypeStruct((m, n), lhs.dtype),
grid=(num_sms,),
grid_names=("sm",),
compiler_params=plgpu.CompilerParams(
lowering_semantics=plgpu.LoweringSemantics.Warpgroup,
),
)
return kernel(group_sizes, lhs, rhs)
def main(unused_argv):
for transpose_rhs in [False, True]:
m, k, n, num_groups = 16 * 1024, 2048, 16 * 1024, 16
kx, ky, kz = random.split(random.key(1234), num=3)
lhs = jax.random.normal(kx, (m, k), jnp.float16)
if transpose_rhs:
rhs = jax.random.normal(ky, (num_groups, n, k), jnp.float16)
else:
rhs = jax.random.normal(ky, (num_groups, k, n), jnp.float16)
group_boundaries = jax.lax.sort(
jax.random.randint(kz, (num_groups - 1,), 0, m, jnp.int32)
)
group_starts = lax.concatenate(
[jnp.array([0], dtype=jnp.int32), group_boundaries], 0
)
group_ends = lax.concatenate(
[group_boundaries, jnp.array([m], dtype=jnp.int32)], 0
)
group_sizes = group_ends - group_starts
assert group_sizes.shape == (num_groups,)
block_m = block_n = (64, 128, 192)
block_k = (64,)
max_concurrent_steps = (2, 4, 5, 6)
grid_block_n = (1, 2, 4, 8, 16)
configs = itertools.product(
block_m, block_n, block_k, max_concurrent_steps, grid_block_n
)
names = (
"block_m", "block_n", "block_k", "max_concurrent_steps", "grid_block_n"
)
best_runtime = float("inf")
best_kwargs = {}
for config in configs:
kwargs = dict(zip(names, config))
if n % (kwargs["grid_block_n"] * kwargs["block_n"]):
continue
try:
f = functools.partial(
ragged_dot, group_sizes=group_sizes, transpose_rhs=transpose_rhs,
**kwargs
)
_, runtime = profiler.measure(f)(lhs, rhs)
except ValueError as e:
if "Mosaic GPU kernel exceeds available shared memory" not in str(e):
raise
runtime = float("inf")
# Enable this to get more detailed information.
else:
print(" ".join(f"{k}={v}" for k, v in kwargs.items()), int(runtime * 1000))
if runtime < best_runtime: # pytype: disable=unsupported-operands
best_runtime = runtime
best_kwargs = kwargs
if not best_kwargs:
raise ValueError("No valid configuration found")
def ref_ragged_dot(lhs, rhs, group_sizes):
if transpose_rhs:
rhs = jnp.transpose(rhs, (0, 2, 1))
return jax.lax.ragged_dot(lhs, rhs, group_sizes=group_sizes)
ref, ref_runtime = profiler.measure(ref_ragged_dot)(
lhs, rhs, group_sizes=group_sizes
)
result = ragged_dot(
lhs, rhs, group_sizes=group_sizes, transpose_rhs=transpose_rhs,
**best_kwargs
)
np.testing.assert_allclose(result, ref, atol=1e-3, rtol=1e-3)
tflops = float(2 * k * m * n) / (best_runtime / 1e3) / 1e12
ref_tflops = float(2 * k * m * n) / (ref_runtime / 1e3) / 1e12
print(f"Transpose RHS: {transpose_rhs}")
print(
"Best parameters: ", " ".join(f"{k}={v}" for k, v in best_kwargs.items())
)
print(f"Kernel: {best_runtime * 1000:.1f} us = {tflops:.1f} TFLOPS")
print(f"Reference: {ref_runtime * 1000:.1f} us = {ref_tflops:.1f} TFLOPS")
if __name__ == "__main__":
from absl import app
jax.config.config_with_absl()
app.run(main)
| {
"repo_id": "jax-ml/jax",
"file_path": "jax/experimental/pallas/ops/gpu/ragged_dot_mgpu.py",
"license": "Apache License 2.0",
"lines": 295,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
jax-ml/jax:jax/experimental/pallas/ops/gpu/transposed_ragged_dot_mgpu.py | # Copyright 2025 The JAX Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Transposed ragged dot Pallas-Mosaic-GPU implementation."""
import functools
import itertools
import jax
from jax import lax
from jax import numpy as jnp
from jax import random
from jax._src import test_util as jtu # noqa: F401
from jax.experimental import pallas as pl
from jax.experimental.mosaic.gpu import profiler
from jax.experimental.pallas import mosaic_gpu as plgpu
import numpy as np
def transposed_ragged_dot(
lhs, # (K, M)
rhs, # (K, N)
*,
group_sizes, # (G,)
block_m: int,
block_n: int,
block_k: int,
max_concurrent_steps: int,
grid_block_n: int,
) -> jax.Array:
if lhs.dtype != rhs.dtype:
raise NotImplementedError(
f"lhs and rhs must have the same dtype, got {lhs.dtype} and {rhs.dtype}"
)
k, m = lhs.shape
k2, n = rhs.shape
g = group_sizes.shape[0]
if k != k2:
raise ValueError(f"lhs.shape={k} must match rhs.shape={k2}")
if m % block_m != 0:
raise ValueError(f"m={m} must be a multiple of block_m={block_m}")
if n % block_n != 0:
raise ValueError(f"n={n} must be a multiple of block_n={block_n}")
group_sizes = group_sizes.astype(int)
group_starts = jnp.concatenate(
[jnp.zeros(1, dtype=int), jnp.cumsum(group_sizes)[:-1]]
).astype(int)
group_ends = jnp.cumsum(group_sizes)
group_block_starts = group_starts // block_k * block_k
group_block_ends = -(group_ends // -block_k) * block_k
group_num_blocks = (group_block_ends - group_block_starts) // block_k
swizzle = plgpu.find_swizzle(block_k * jnp.dtype(lhs.dtype).itemsize * 8)
swizzle_elems = swizzle // jnp.dtype(lhs.dtype).itemsize
transforms = (
plgpu.TilingTransform((8, swizzle_elems)), plgpu.SwizzleTransform(swizzle)
)
def body(
group_sizes_gmem,
group_starts_gmem,
group_ends_gmem,
group_num_blocks_gmem,
group_block_starts_gmem,
lhs_gmem,
rhs_gmem,
o_gmem,
):
grid_m = pl.cdiv(m, block_m)
grid_n = pl.cdiv(n, block_n)
@plgpu.nd_loop((g, grid_m * grid_n), collective_axes="sm")
def mn_loop(loop_info: plgpu.NDLoopInfo):
g_i = loop_info.index[0]
m_i, n_i = plgpu.planar_snake(
loop_info.index[1],
(grid_m, grid_n),
1,
grid_block_n,
)
# This slice is potentially out of bounds, but we never access the
# out of bound part in emit_pipeline.
gmem_slice = pl.ds(group_block_starts_gmem[g_i], k)
def acc_scope(acc_ref):
def block_matmul(block_idx, lhs_smem, rhs_smem):
block_idx = block_idx[0]
@pl.when(block_idx == 0)
def _():
# Handles the first block of the group, where there might be
# data from the previous group in the beginning of the block.
lhs_reg = lhs_smem[...]
start_index = lax.rem(group_starts_gmem[g_i], block_k)
indices = plgpu.layout_cast(
jax.lax.broadcasted_iota(jnp.int32, (block_k, block_m), 0),
plgpu.Layout.WGMMA
)
lhs_mask = (indices >= start_index).astype(lhs_smem.dtype)
lhs_reg = lhs_reg * lhs_mask
lhs_smem[...] = lhs_reg
plgpu.commit_smem()
@pl.when(block_idx == group_num_blocks_gmem[g_i] - 1)
def _():
# Handles the last block of the group, where there might be
# data from the next group in the end of the block.
lhs_reg = lhs_smem[...]
last_index = lax.rem(group_ends_gmem[g_i] - 1, block_k)
indices = plgpu.layout_cast(
jax.lax.broadcasted_iota(jnp.int32, (block_k, block_m), 0),
plgpu.Layout.WGMMA
)
lhs_mask = (indices <= last_index).astype(lhs_smem.dtype)
lhs_reg = lhs_reg * lhs_mask
lhs_smem[...] = lhs_reg
plgpu.commit_smem()
plgpu.wgmma(acc_ref, plgpu.transpose_ref(lhs_smem, (1, 0)), rhs_smem)
if max_concurrent_steps == 1:
# Without delayed release, we won't have at least two separate
# smem blocks in flight. Therefore, we cannot rely on the implicit
# wait of wgmma to gaurantee that the data in smem is ready to be
# overwritten by the next pipeline iteration.
plgpu.wgmma_wait(0)
@pl.when(group_sizes_gmem[g_i] > 0) # Skip the group if it is empty.
def _():
plgpu.emit_pipeline(
block_matmul,
grid=(group_num_blocks_gmem[g_i],),
in_specs=[
plgpu.BlockSpec(
(block_k, block_m),
lambda k_i: (k_i, m_i),
delay_release=1 if max_concurrent_steps > 1 else 0,
transforms=transforms,
),
plgpu.BlockSpec(
(block_k, block_n),
lambda k_i: (k_i, n_i),
delay_release=1 if max_concurrent_steps > 1 else 0,
transforms=transforms,
),
],
max_concurrent_steps=max_concurrent_steps,
)(lhs_gmem.at[gmem_slice, :], rhs_gmem.at[gmem_slice, :])
return acc_ref[...]
acc = pl.run_scoped(acc_scope, plgpu.ACC((block_m, block_n)))
@functools.partial(
pl.run_scoped,
o_smem=plgpu.SMEM(
(block_m, block_n),
dtype=o_gmem.dtype,
transforms=transforms,
)
)
def store_scope(o_smem):
o_smem[...] = acc.astype(o_smem.dtype)
plgpu.commit_smem()
plgpu.copy_smem_to_gmem(
o_smem, o_gmem.at[
g_i,
pl.ds(m_i * block_m, block_m),
pl.ds(n_i * block_n, block_n)
]
)
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
# There are 132 SMs on a H100 SXM GPU.
num_sms = jax.devices()[0].core_count
kernel = plgpu.kernel(
body,
out_shape=jax.ShapeDtypeStruct((g, m, n), lhs.dtype),
grid=(num_sms,),
grid_names=("sm",),
)
return kernel(
group_sizes,
group_starts,
group_ends,
group_num_blocks,
group_block_starts,
lhs,
rhs,
)
def ref_transposed_ragged_dot(lhs, rhs, group_sizes):
return jax.lax.ragged_dot_general(
lhs, rhs, group_sizes,
ragged_dot_dimension_numbers=jax.lax.RaggedDotDimensionNumbers(
dot_dimension_numbers=(((0,), (0,)), ((), ())),
lhs_ragged_dimensions=[0],
rhs_group_dimensions=[],
)
)
def main(unused_argv):
k, m, n, num_groups = 16 * 1024, 2048, 2048, 16
kx, ky, kz = random.split(random.key(1234), num=3)
lhs = jax.random.normal(kx, (k, m), jnp.float16)
rhs = jax.random.normal(ky, (k, n), jnp.float16)
group_boundaries = jax.lax.sort(
jax.random.randint(kz, (num_groups - 1,), 0, k, jnp.int32)
)
group_starts = lax.concatenate(
[jnp.array([0], dtype=jnp.int32), group_boundaries], 0
)
group_ends = lax.concatenate(
[group_boundaries, jnp.array([k], dtype=jnp.int32)], 0
)
group_sizes = group_ends - group_starts
assert group_sizes.shape == (num_groups,)
block_m = block_n = [64, 128]
block_k = [64, 128]
max_concurrent_steps = [1, 2, 4, 5, 6]
grid_block_n = [1, 2, 4, 8, 16]
configs = itertools.product(
block_m, block_n, block_k, max_concurrent_steps, grid_block_n
)
names = (
"block_m", "block_n", "block_k", "max_concurrent_steps", "grid_block_n",
)
best_runtime = float("inf")
best_kwargs = {}
for config in configs:
kwargs = dict(zip(names, config))
if n % kwargs["block_n"]:
continue
try:
f = functools.partial(
transposed_ragged_dot, group_sizes=group_sizes,
**kwargs
)
_, runtime = profiler.measure(f)(lhs, rhs)
except ValueError as e:
if "Mosaic GPU kernel exceeds available shared memory" not in str(e):
raise
runtime = float("inf")
# Enable this to get more detailed information.
else:
print(
" ".join(f"{k}={v}" for k, v in kwargs.items()),
f"{int(runtime * 1000):.1f} us",
)
if runtime < best_runtime: # pytype: disable=unsupported-operands
best_runtime = runtime
best_kwargs = kwargs
if not best_kwargs:
raise ValueError("No valid configuration found")
ref, ref_runtime = profiler.measure(ref_transposed_ragged_dot)(
lhs, rhs, group_sizes=group_sizes
)
result = transposed_ragged_dot(
lhs, rhs, group_sizes=group_sizes, **best_kwargs
)
tflops = float(2 * k * m * n) / (best_runtime / 1e3) / 1e12
ref_tflops = float(2 * k * m * n) / (ref_runtime / 1e3) / 1e12
print(
"Best parameters: ", " ".join(f"{k}={v}" for k, v in best_kwargs.items())
)
print(f"Kernel: {best_runtime * 1000:.1f} us = {tflops:.1f} TFLOPS")
print(f"Reference: {ref_runtime * 1000:.1f} us = {ref_tflops:.1f} TFLOPS")
np.testing.assert_allclose(result, ref, atol=1e-3, rtol=1e-3)
if __name__ == "__main__":
from absl import app
jax.config.config_with_absl()
app.run(main)
| {
"repo_id": "jax-ml/jax",
"file_path": "jax/experimental/pallas/ops/gpu/transposed_ragged_dot_mgpu.py",
"license": "Apache License 2.0",
"lines": 264,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
jax-ml/jax:jax/experimental/pallas/tpu_sc.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TPU SparseCore Extensions to Pallas."""
from jax._src.pallas.mosaic.sc_core import BlockSpec as BlockSpec
from jax._src.pallas.mosaic.sc_core import get_sparse_core_info as get_sparse_core_info
from jax._src.pallas.mosaic.sc_core import MemoryRef as MemoryRef
from jax._src.pallas.mosaic.sc_core import ScalarSubcoreMesh as ScalarSubcoreMesh
from jax._src.pallas.mosaic.sc_core import VectorSubcoreMesh as VectorSubcoreMesh
from jax._src.pallas.mosaic.sc_primitives import addupdate as addupdate
from jax._src.pallas.mosaic.sc_primitives import addupdate_compressed as addupdate_compressed
from jax._src.pallas.mosaic.sc_primitives import addupdate_scatter as addupdate_scatter
from jax._src.pallas.mosaic.sc_primitives import all_reduce_ffs as all_reduce_ffs
from jax._src.pallas.mosaic.sc_primitives import all_reduce_population_count as all_reduce_population_count
from jax._src.pallas.mosaic.sc_primitives import bitcast as bitcast
from jax._src.pallas.mosaic.sc_primitives import cummax as cummax
from jax._src.pallas.mosaic.sc_primitives import cumsum as cumsum
from jax._src.pallas.mosaic.sc_primitives import fetch_and_add as fetch_and_add
from jax._src.pallas.mosaic.sc_primitives import load_expanded as load_expanded
from jax._src.pallas.mosaic.sc_primitives import load_gather as load_gather
from jax._src.pallas.mosaic.sc_primitives import pack as pack
from jax._src.pallas.mosaic.sc_primitives import PackFormat as PackFormat
from jax._src.pallas.mosaic.sc_primitives import parallel_loop as parallel_loop
from jax._src.pallas.mosaic.sc_primitives import scan_count as scan_count
from jax._src.pallas.mosaic.sc_primitives import sort_key_val as sort_key_val
from jax._src.pallas.mosaic.sc_primitives import store_compressed as store_compressed
from jax._src.pallas.mosaic.sc_primitives import store_scatter as store_scatter
from jax._src.pallas.mosaic.sc_primitives import subcore_barrier as subcore_barrier
from jax._src.pallas.mosaic.sc_primitives import unpack as unpack
| {
"repo_id": "jax-ml/jax",
"file_path": "jax/experimental/pallas/tpu_sc.py",
"license": "Apache License 2.0",
"lines": 39,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
jax-ml/jax:jax/experimental/scheduling_groups.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from functools import partial
from jax._src import core
from jax._src import dispatch
from jax._src import linear_util as lu
from jax._src.api_util import debug_info
from jax._src.util import (safe_map, safe_zip, weakref_lru_cache, unzip2,
split_list)
from jax._src.tree_util import tree_flatten, tree_unflatten, FlatTree
from jax._src.interpreters import ad, mlir, partial_eval as pe, batching
from jax._src.lib.mlir.dialects import func as func_dialect
from jax._src.lib.mlir import ir
map, unsafe_map = safe_map, map
zip, unsafe_zip = safe_zip, zip
def scheduling_group(name):
return xla_metadata_call(scheduling_group=name)
def xla_metadata_call(f=None, **meta):
if f is None:
return lambda g: _xla_metadata_call(g, **meta)
return _xla_metadata_call(f, **meta)
# TODO(yashkatariya): Figure out a way to reuse code with compute_on2_p, fused_p
def _xla_metadata_call(fun, **meta):
def wrapped(*args, **kwargs):
dbg = debug_info('xla_metadata_call', fun, args, kwargs)
args_ft = FlatTree.flatten((args, kwargs))
in_avals = args_ft.map(core.shaped_abstractify)
jaxpr, out_avals = pe.trace_to_jaxpr(fun, in_avals, dbg)
outs_flat = xla_metadata_call_p.bind(*args_ft.vals, jaxpr=jaxpr, **meta)
return tree_unflatten(out_avals.tree, outs_flat)
return wrapped
xla_metadata_call_p = core.Primitive('xla_metadata_call')
xla_metadata_call_p.multiple_results = True
dispatch.simple_impl(xla_metadata_call_p)
def _xla_metadata_call_abstract_eval(*in_avals, jaxpr, **meta):
return jaxpr.out_avals
xla_metadata_call_p.def_abstract_eval(_xla_metadata_call_abstract_eval)
def attr_get(x):
if isinstance(x, str):
return ir.StringAttr.get(x)
else:
raise NotImplementedError(f'mlir attr handler for {type(x)=}')
def _xla_metadata_call_lowering(ctx, *args, jaxpr, **meta):
const_args_and_avals = core.jaxpr_const_args(jaxpr.jaxpr)
const_args, const_avals = unzip2(const_args_and_avals)
const_arg_values = [
mlir.ir_constant(c, const_lowering=ctx.const_lowering, aval=aval)
for c, aval in const_args_and_avals]
in_avals = (*const_avals, *ctx.avals_in)
func_op, output_types, effects = mlir.lower_called_computation(
"xla_metadata_call", jaxpr, ctx.module_context, len(const_args), in_avals,
ctx.avals_out, ctx.tokens_in)
symbol_name = func_op.name.value
flat_output_types = mlir.flatten_ir_types(output_types)
tokens = [ctx.tokens_in.get(eff) for eff in effects]
args = (*ctx.dim_var_values, *tokens, *const_arg_values, *args)
call = func_dialect.CallOp(
flat_output_types, ir.FlatSymbolRefAttr.get(symbol_name),
mlir.flatten_ir_values(args))
call.operation.attributes['mhlo.frontend_attributes'] = ir.DictAttr.get(
{k: attr_get(v) for k, v in meta.items()})
out_nodes = mlir.unflatten_ir_values_like_types(call.results, output_types)
tokens, out_nodes = split_list(out_nodes, [len(effects)])
tokens_out = ctx.tokens_in.update_tokens(mlir.TokenSet(zip(effects, tokens)))
ctx.set_tokens_out(tokens_out)
return out_nodes
mlir.register_lowering(xla_metadata_call_p, _xla_metadata_call_lowering)
def _xla_metadata_call_batcher(axis_data, vals_in, dims_in, *, jaxpr, **meta):
batched_jaxpr, dims_out = batching.batch_jaxpr2(jaxpr, axis_data, dims_in)
outs = xla_metadata_call_p.bind(*vals_in, jaxpr=batched_jaxpr, **meta)
return outs, dims_out
batching.fancy_primitive_batchers[xla_metadata_call_p] = _xla_metadata_call_batcher
def _xla_metadata_call_jvp(primals, tangents, *, jaxpr, **meta):
nzs = [not isinstance(t, ad.Zero) for t in tangents]
jaxpr_jvp, out_nzs = ad.jvp_jaxpr(jaxpr, nzs, False)
nz_tangents = [t for t in tangents if not isinstance(t, ad.Zero)]
outs = xla_metadata_call_p.bind(*primals, *nz_tangents, jaxpr=jaxpr_jvp, **meta)
primals_out, nz_tangents_out = outs[:len(out_nzs)], outs[len(out_nzs):]
nz_outs = iter(nz_tangents_out)
tangents_out = [next(nz_outs) if nz else ad.Zero(aval.to_tangent_aval())
for aval, nz in zip(jaxpr.out_avals, out_nzs)]
assert next(nz_outs, None) is None
return primals_out, tangents_out
ad.primitive_jvps[xla_metadata_call_p] = _xla_metadata_call_jvp
def _xla_metadata_call_lin(_is_vjp, nzs, *primals, jaxpr, **meta):
# TODO(mattjj,yashkatariya): should use ad.linearize_jaxpr here
jaxpr_jvp, out_nzs = ad.jvp_jaxpr(jaxpr, nzs, False)
lin_outs = [False] * len(out_nzs) + [True] * sum(out_nzs)
jaxpr_lin_, used_inputs = pe.dce_jaxpr(jaxpr_jvp.jaxpr, lin_outs, False)
jaxpr_lin = pe.close_jaxpr(jaxpr_lin_)
primals_out = xla_metadata_call_p.bind(*primals, jaxpr=jaxpr, **meta)
tangent_avals_out = [a.to_tangent_aval() for a in jaxpr.out_avals]
def xla_metadata_call_lin(primals, *tangents):
nz_tangents = [t for t in tangents if not isinstance(t, ad.Zero)]
inputs = [x for x, u in zip([*primals, *nz_tangents], used_inputs) if u]
nz_outs = xla_metadata_call_p.bind(*inputs, jaxpr=jaxpr_lin, **meta)
nz_outs_ = iter(nz_outs)
outs = [next(nz_outs_) if nz else ad.Zero(a)
for nz, a in zip(out_nzs, tangent_avals_out)]
assert next(nz_outs_, None) is None
return outs
return primals_out, out_nzs, primals, xla_metadata_call_lin
ad.primitive_linearizations[xla_metadata_call_p] = _xla_metadata_call_lin
pe.partial_eval_jaxpr_custom_rules[xla_metadata_call_p] = \
partial(pe.closed_call_partial_eval_custom_rule, 'jaxpr',
lambda _, __, ___, ____, _____, ______, x, y: (x, y))
@weakref_lru_cache
def _transpose_jaxpr(jaxpr, in_avals, in_tree):
cell = lambda: None
def transposed(*in_flat):
primals_in, cts_in = tree_unflatten(in_tree, in_flat)
out = ad.backward_pass(jaxpr.jaxpr, False, jaxpr.consts, primals_in, cts_in)
out = [ct if not isinstance(ct, ad.Zero) else None for ct in out]
cts_out, cell.out_tree = tree_flatten(out) # type: ignore
return cts_out
dbg = jaxpr.jaxpr.debug_info.with_unknown_names()
trans_jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(
lu.wrap_init(transposed, debug_info=dbg), in_avals)
return core.ClosedJaxpr(trans_jaxpr, consts), cell.out_tree # type: ignore
def _xla_metadata_call_transpose(cts_in, *primals_in, jaxpr, **meta):
in_flat, in_tree = tree_flatten((primals_in, cts_in))
in_avals = tuple(core.typeof(x) for x in in_flat)
trans_jaxpr, out_tree = _transpose_jaxpr(jaxpr, in_avals, in_tree)
cts_out = xla_metadata_call_p.bind(*in_flat, jaxpr=trans_jaxpr, **meta)
return tree_unflatten(out_tree, cts_out)
ad.primitive_transposes[xla_metadata_call_p] = _xla_metadata_call_transpose
def dce_jaxpr_xla_metadata_rule(used_outputs: list[bool], eqn: pe.JaxprEqn
) -> tuple[list[bool], pe.JaxprEqn | None]:
if not any(used_outputs) and not pe.has_effects(eqn):
return [False] * len(eqn.invars), None
jaxpr_ = eqn.params['jaxpr']
closed_jaxpr, used_inputs = pe._cached_closed_call_dce(
jaxpr_, tuple(used_outputs))
new_params = dict(eqn.params, jaxpr=closed_jaxpr)
new_eqn = pe.new_jaxpr_eqn(
[v for v, used in zip(eqn.invars, used_inputs) if used],
[v for v, used in zip(eqn.outvars, used_outputs) if used],
eqn.primitive, new_params, closed_jaxpr.effects, eqn.source_info, eqn.ctx)
return used_inputs, new_eqn
pe.dce_rules[xla_metadata_call_p] = dce_jaxpr_xla_metadata_rule
| {
"repo_id": "jax-ml/jax",
"file_path": "jax/experimental/scheduling_groups.py",
"license": "Apache License 2.0",
"lines": 151,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
jax-ml/jax:jax/extend/sharding.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# TODO(yashkatariya): Remove this after NamedSharding supports more complicated
# shardings like sub-axes, strided shardings, etc.
from jax._src.lib import xla_client
from jax._src.sharding_impls import GSPMDSharding as GSPMDSharding
def get_op_sharding_from_serialized_proto(
sharding: bytes) -> xla_client.OpSharding:
proto = xla_client.OpSharding()
proto.ParseFromString(sharding)
return proto
def get_hlo_sharding_from_serialized_proto(
sharding: bytes) -> xla_client.HloSharding:
return xla_client.HloSharding.from_proto(
get_op_sharding_from_serialized_proto(sharding))
def get_serialized_proto_from_hlo_sharding(
sharding: xla_client.HloSharding) -> bytes:
return sharding.to_proto().SerializeToString()
| {
"repo_id": "jax-ml/jax",
"file_path": "jax/extend/sharding.py",
"license": "Apache License 2.0",
"lines": 29,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
jax-ml/jax:jax/memory.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from jax._src.memory import Space as Space
| {
"repo_id": "jax-ml/jax",
"file_path": "jax/memory.py",
"license": "Apache License 2.0",
"lines": 14,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
jax-ml/jax:jax/ref.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__all__ = [
'AbstractRef', 'Ref', 'addupdate', 'free_ref', 'freeze', 'get', 'new_ref',
'empty_ref', 'set', 'swap'
]
from jax._src.core import Ref, empty_ref, free_ref, freeze
from jax._src.ref import new_ref
from jax._src.state.types import AbstractRef
from jax._src.state.primitives import (
ref_get as get,
ref_set as set,
ref_swap as swap,
ref_addupdate as addupdate,
)
_deprecations = {
# Remove in v0.10.0
"array_ref": (
"jax.array_ref was removed in JAX v0.9.0; use jax.new_ref instead.",
None
),
"ArrayRef": (
"jax.ArrayRef was removed in JAX v0.9.0; use jax.Ref instead.",
None
),
}
from jax._src.deprecations import deprecation_getattr as _deprecation_getattr
__getattr__ = _deprecation_getattr(__name__, _deprecations)
del _deprecation_getattr
| {
"repo_id": "jax-ml/jax",
"file_path": "jax/ref.py",
"license": "Apache License 2.0",
"lines": 40,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
jax-ml/jax:jax/scipy/stats/gumbel_r.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Note: import <name> as <name> is required for names to be exported.
# See PEP 484 & https://github.com/jax-ml/jax/issues/7570
from jax._src.scipy.stats.gumbel_r import (
logpdf as logpdf,
pdf as pdf,
logcdf as logcdf,
cdf as cdf,
ppf as ppf,
sf as sf,
logsf as logsf
)
| {
"repo_id": "jax-ml/jax",
"file_path": "jax/scipy/stats/gumbel_r.py",
"license": "Apache License 2.0",
"lines": 24,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
jax-ml/jax:jaxlib/cpu_sparse.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Any
from .cpu import _sparse
def registrations() -> dict[str, list[tuple[str, Any, int]]]:
api_version = 1
return {
"cpu": [
(name, value, api_version)
for name, value in _sparse.registrations().items()
]
}
| {
"repo_id": "jax-ml/jax",
"file_path": "jaxlib/cpu_sparse.py",
"license": "Apache License 2.0",
"lines": 23,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
jax-ml/jax:jaxlib/tools/build_mosaic_wheel.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Script that builds a jax cuda/rocm plugin wheel, intended to be run via bazel run
# as part of the jax cuda/rocm plugin build process.
# Most users should not run this script directly; use build.py instead.
import argparse
import functools
import os
import pathlib
import tempfile
from bazel_tools.tools.python.runfiles import runfiles
from jaxlib.tools import build_utils
parser = argparse.ArgumentParser(fromfile_prefix_chars="@")
parser.add_argument(
"--sources_path",
default=None,
help="Path in which the wheel's sources should be prepared. Optional. If "
"omitted, a temporary directory will be used.",
)
parser.add_argument(
"--output_path",
required=True,
help="Path to which the output wheel should be written. Required.",
)
parser.add_argument(
"--jaxlib_git_hash",
required=True,
help="Git hash. Required.",
)
parser.add_argument(
"--cpu", required=True, help="Target CPU architecture. Required."
)
parser.add_argument(
"--platform_version",
required=True,
help="Target CUDA version. Required.",
)
parser.add_argument(
"--editable",
action="store_true",
help="Create an 'editable' mosaic build instead of a wheel.",
)
parser.add_argument(
"--srcs", help="source files for the wheel", action="append"
)
parser.add_argument(
"--nvidia_wheel_versions_data",
default=None,
required=True,
help="NVIDIA wheel versions data",
)
# The jax_wheel target passes in some extra params, which we ignore
args, _ = parser.parse_known_args()
r = runfiles.Create()
def assemble_sources(
wheel_sources_path: pathlib.Path,
*,
cpu,
cuda_version,
wheel_sources,
nvidia_wheel_versions_data,
):
"""Assembles a source tree for the wheel in `wheel_sources_path`"""
source_file_prefix = build_utils.get_source_file_prefix(wheel_sources)
wheel_sources_map = build_utils.create_wheel_sources_map(
wheel_sources, root_packages=["jaxlib"]
)
mgpudir = wheel_sources_path / "mosaic_gpu"
copy_files = functools.partial(
build_utils.copy_file,
runfiles=r,
wheel_sources_map=wheel_sources_map,
)
copy_files(
dst_dir=wheel_sources_path,
src_files=[
f"{source_file_prefix}jaxlib/tools/LICENSE.txt",
f"{source_file_prefix}jaxlib/mosaic/gpu/wheel/setup.py",
],
)
copy_files(
dst_dir=mgpudir / f"mosaic_gpu_cuda{cuda_version}",
src_files=[
f"{source_file_prefix}jaxlib/mosaic/gpu/wheel/mosaic_gpu.so",
f"{source_file_prefix}jaxlib/mosaic/gpu/wheel/__init__.py",
f"{source_file_prefix}jaxlib/version.py",
],
)
# This sets the cuda version in setup.py
build_utils.update_setup_with_cuda_and_nvidia_wheel_versions(
wheel_sources_path, cuda_version, nvidia_wheel_versions_data
)
tag = build_utils.platform_tag(cpu)
with open(wheel_sources_path / "setup.cfg", "w") as f:
f.write(
f"""[metadata]
license_files = LICENSE.txt
[bdist_wheel]
plat_name={tag}
python_tag=py3
"""
)
tmpdir = None
sources_path = args.sources_path
if sources_path is None:
tmpdir = tempfile.TemporaryDirectory(prefix="mosaic_gpu")
sources_path = tmpdir.name
try:
os.makedirs(args.output_path, exist_ok=True)
package_name = "mosaic_gpu"
assemble_sources(
pathlib.Path(sources_path),
cpu=args.cpu,
cuda_version=args.platform_version,
wheel_sources=args.srcs,
nvidia_wheel_versions_data=args.nvidia_wheel_versions_data,
)
if args.editable:
build_utils.build_editable(sources_path, args.output_path, package_name)
else:
build_utils.build_wheel(
sources_path,
args.output_path,
package_name,
git_hash=args.jaxlib_git_hash,
)
finally:
if tmpdir:
tmpdir.cleanup()
| {
"repo_id": "jax-ml/jax",
"file_path": "jaxlib/tools/build_mosaic_wheel.py",
"license": "Apache License 2.0",
"lines": 140,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
jax-ml/jax:tests/absl_cpp_logging_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from absl.testing import absltest
import jax
from jax._src import test_util as jtu
from jax._src.lib import utils
# Note: This test modifies global logging library configuration knobs.
# We isolate it from other tests by running it as a separate test target.
@jtu.skip_under_pytest("Test must run in an isolated process")
class AbslCppLoggingTest(jtu.JaxTestCase):
def test_vlogging(self):
utils.absl_set_min_log_level(0) # INFO
with jtu.capture_stderr() as stderr:
jax.jit(lambda x: x + 1)(1)
self.assertNotIn("hlo_pass_pipeline.cc", stderr())
with jtu.capture_stderr() as stderr:
utils.absl_set_vlog_level("hlo_pass_pipeline", 1)
jax.jit(lambda x: x + 2)(1)
self.assertIn("hlo_pass_pipeline.cc", stderr())
if __name__ == "__main__":
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/absl_cpp_logging_test.py",
"license": "Apache License 2.0",
"lines": 32,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/buffer_callback_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from absl.testing import absltest
from absl.testing import parameterized
import numpy as np
import jax
import jax.numpy as jnp
from jax._src import test_util as jtu
from jax._src.lib import jaxlib_extension_version
from jax.experimental import buffer_callback
jax.config.parse_flags_with_absl()
class BufferCallbackTest(jtu.JaxTestCase):
def setUp(self):
super().setUp()
if jtu.test_device_matches(["tpu"]):
self.skipTest("Not supported on TPU.")
@parameterized.parameters(jtu.dtypes.all)
@jtu.run_on_devices("cpu")
def test_numpy(self, dtype):
def callback(ctx, out, arg):
with self.assertRaisesRegex(
jax.errors.JaxRuntimeError, "XLA FFI GPU context is not available"
):
ctx.stream
self.assertEqual(ctx.stage, buffer_callback.ExecutionStage.EXECUTE)
self.assertEqual(arg.shape, shape)
self.assertEqual(arg.dtype, dtype)
self.assertEqual(out.shape, shape)
self.assertEqual(out.dtype, dtype)
self.assertFalse(arg.writeable)
self.assertTrue(out.writeable)
x = np.asarray(arg)
self.assertArraysEqual(x, data)
y = np.asarray(out)
self.assertEqual(x.dtype, y.dtype)
self.assertEqual(x.shape, y.shape)
y[...] = x
rng = jtu.rand_default(self.rng())
shape = (3, 4)
data = rng(shape, dtype)
fun = buffer_callback.buffer_callback(
callback, jax.ShapeDtypeStruct(data.shape, data.dtype)
)
self.assertArraysEqual(fun(data), data)
@parameterized.parameters(jtu.dtypes.all)
@jtu.run_on_devices("cpu")
def test_dlpack(self, dtype):
if dtype == jnp.bfloat16:
self.skipTest("Numpy's DLPack implementation does not support bfloat16")
def callback(ctx, out, arg):
del ctx # unused
x = np.from_dlpack(arg)
self.assertArraysEqual(x, data)
y = np.from_dlpack(out)
self.assertEqual(x.dtype, y.dtype)
self.assertEqual(x.shape, y.shape)
rng = jtu.rand_default(self.rng())
shape = (3, 4)
data = rng(shape, dtype)
fun = buffer_callback.buffer_callback(
callback, jax.ShapeDtypeStruct(data.shape, data.dtype)
)
# We can't actually test the output because numpy doesn't support writable
# DLPack tensors.
jax.block_until_ready(fun(data))
@parameterized.product(
dtype=jtu.dtypes.all, command_buffer_compatible=[True, False]
)
@jtu.run_on_devices("gpu")
def test_cuda_array_interface(self, dtype, command_buffer_compatible):
if command_buffer_compatible and jaxlib_extension_version < 337:
self.skipTest("Requires jaxlib extension version of at least 337.")
def callback(ctx, out, arg):
ctx.stream # doesn't crash
self.assertEqual(ctx.stage, buffer_callback.ExecutionStage.EXECUTE)
self.assertEqual(arg.shape, shape)
self.assertEqual(arg.dtype, dtype)
self.assertEqual(out.shape, shape)
self.assertEqual(out.dtype, dtype)
obj = arg.__cuda_array_interface__
self.assertEqual(obj["shape"], data.shape)
self.assertEqual(obj["typestr"], data.dtype.str)
obj = out.__cuda_array_interface__
self.assertEqual(obj["shape"], data.shape)
self.assertEqual(obj["typestr"], data.dtype.str)
rng = jtu.rand_default(self.rng())
shape = (3, 4)
data = rng(shape, dtype)
fun = buffer_callback.buffer_callback(
callback, jax.ShapeDtypeStruct(data.shape, data.dtype),
command_buffer_compatible=command_buffer_compatible,
)
# TODO: There's an XLA:GPU/CUDA bug that causes a segfault when
# instantiating an empty CUDA graph. Once that bug is fixed or worked
# around, add a test that checks that the Python callback is only executed
# once.
jax.block_until_ready(fun(data))
@parameterized.parameters([
"sequential", "sequential_unrolled", "expand_dims", "broadcast_all"
])
@jtu.run_on_devices("cpu")
def test_batching(self, vmap_method):
def callback(ctx, out, *args):
del ctx # unused
x = np.asarray(args[0])
y = np.asarray(args[1])
z = np.asarray(out)
z[...] = x
z[...] += y
rng = jtu.rand_default(self.rng())
shape = (3, 4)
x = rng(shape, jnp.float32)
y = rng(shape, jnp.float32)
fun = buffer_callback.buffer_callback(
callback,
jax.ShapeDtypeStruct(x.shape[1:], x.dtype),
vmap_method=vmap_method,
)
self.assertArraysEqual(jax.vmap(fun)(x, y), x + y)
@jtu.run_on_devices("cpu")
def test_input_output_aliases(self):
def callback(ctx, out, arg):
del ctx # unused
x = np.asarray(arg)
y = np.asarray(out)
self.assertEqual(x.ctypes.data, y.ctypes.data)
rng = jtu.rand_default(self.rng())
shape = (3, 4)
data = rng(shape, jnp.float32)
fun = buffer_callback.buffer_callback(
callback, jax.ShapeDtypeStruct(data.shape, data.dtype),
input_output_aliases={0: 0},
)
jax.block_until_ready(fun(data))
@jtu.run_on_devices("cpu")
def test_buffer_callback_multi_mesh(self):
def no_op(*args, **kwargs):
pass
@jax.jit
def f(x, y):
z = x * y
output_shape = jax.ShapeDtypeStruct(x.shape, x.dtype)
buffer_call = buffer_callback.buffer_callback(
no_op, output_shape, command_buffer_compatible=True)
return buffer_call((z,))
mesh1 = jtu.create_mesh((1, 1), ('a', 'b'))
mesh2 = jtu.create_mesh((1, 1), ('x', 'y'))
x = jax.device_put(
jnp.ones((32, 32)), jax.NamedSharding(mesh1, jax.P('a', 'b')))
y = jax.device_put(
jnp.ones((32, 32)), jax.NamedSharding(mesh2, jax.P('x', 'y')))
f(x, y) # doesn't crash
def test_side_effect(self):
def callback(*_):
nonlocal called
called = True
called = False
fun = buffer_callback.buffer_callback(
callback, jax.ShapeDtypeStruct((), jnp.float32), has_side_effect=True)
jax.block_until_ready(fun())
self.assertTrue(called)
if __name__ == "__main__":
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/buffer_callback_test.py",
"license": "Apache License 2.0",
"lines": 174,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/custom_api_test.py | # Copyright 2018 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import collections
from collections.abc import Callable
import concurrent.futures
import functools
from functools import partial
import itertools as it
import re
import unittest
import textwrap
from absl.testing import absltest, parameterized
import numpy as np
import jax
import jax.numpy as jnp
from jax import float0, grad, jit
from jax import lax
from jax import tree_util
import jax.custom_batching
import jax.custom_derivatives
import jax.custom_transpose
import jax.experimental.custom_dce
from jax.errors import UnexpectedTracerError
from jax._src import api
from jax._src import api_util
from jax._src import config
from jax._src import core
from jax._src import custom_derivatives
from jax._src import test_util as jtu
from jax._src.interpreters import partial_eval as pe
config.parse_flags_with_absl()
class CustomJVPTest(jtu.JaxTestCase):
def test_basic(self):
@jax.custom_jvp
def f(x):
return jnp.sin(x)
def f_jvp(primals, tangents):
x, = primals
g, = tangents
return f(x), 2 * jnp.cos(x) * g
f.defjvp(f_jvp)
x = 3.
self.assertAllClose(f(x), jnp.sin(x))
self.assertAllClose(api.jvp(f, (x,), (1.,)),
(jnp.sin(x), 2 * jnp.cos(x)))
self.assertAllClose(api.grad(f)(x), 2 * jnp.cos(x))
def test_invariance(self):
@jax.custom_jvp
def f(x):
return jnp.cos(2 * x) / 2.
def f_jvp(primals, tangents):
x, = primals
g, = tangents
return (f(x), 3 * g)
f.defjvp(f_jvp)
def f2(x):
y, _ = api.jvp(f, (x,), (x,))
return y
def f3(x):
y, _ = api.jvp(f2, (x,), (x,))
return y
x = 1.
self.assertAllClose(api.jvp(f, (x,), (x,)),
api.jvp(f2, (x,), (x,)),
check_dtypes=False)
self.assertAllClose(api.jvp(f, (x,), (x,)),
api.jvp(f3, (x,), (x,)),
check_dtypes=False)
def test_python_control_flow(self):
@jax.custom_jvp
def f(x):
if x > 0:
return jnp.sin(x)
else:
return jnp.cos(x)
def f_jvp(primals, tangents):
x, = primals
g, = tangents
if x > 0:
return f(x), 2 * g
else:
return f(x), 3 * g
f.defjvp(f_jvp)
x = 2.
self.assertAllClose(f(x), jnp.sin(x))
self.assertAllClose(f(-x), jnp.cos(-x))
self.assertAllClose(api.jvp(f, (x,), (1.,)),
(jnp.sin(x), 2.),
check_dtypes=False)
self.assertAllClose(api.jvp(f, (-x,), (1.,)),
(jnp.cos(-x), 3.),
check_dtypes=False)
self.assertAllClose(api.grad(f)(x), 2., check_dtypes=False)
self.assertAllClose(api.grad(f)(-x), 3., check_dtypes=False)
def test_vmap(self):
@jax.custom_jvp
def f(x):
assert jnp.ndim(x) == 0
return jnp.sin(x)
def f_jvp(primals, tangents):
x, = primals
g, = tangents
assert jnp.ndim(x) == jnp.ndim(g) == 0
return f(x), 2 * jnp.cos(x) * g
f.defjvp(f_jvp)
x = jnp.arange(3.)
xx = jnp.arange(6.).reshape(2, 3)
# vmap of f
self.assertAllClose(api.vmap(f)(x), jnp.sin(x))
self.assertAllClose(api.vmap(api.vmap(f))(xx), jnp.sin(xx))
# vmap of jvp of f
self.assertAllClose(api.vmap(lambda x: api.jvp(f, (x,), (x,)))(x),
(jnp.sin(x), 2 * jnp.cos(x) * x))
self.assertAllClose(api.vmap(api.vmap(lambda x: api.jvp(f, (x,), (x,))))(xx),
(jnp.sin(xx), 2 * jnp.cos(xx) * xx))
# jvp of vmap of f
self.assertAllClose(api.jvp(api.vmap(f), (x,), (x,)),
(jnp.sin(x), 2 * jnp.cos(x) * x))
self.assertAllClose(api.jvp(api.vmap(api.vmap(f)), (xx,), (xx,)),
(jnp.sin(xx), 2 * jnp.cos(xx) * xx))
# vmap of jvp of vmap of f
self.assertAllClose(api.vmap(lambda x: api.jvp(api.vmap(f), (x,), (x,)))(xx),
(jnp.sin(xx), 2 * jnp.cos(xx) * xx))
def test_jit(self):
@jax.custom_jvp
def f(x):
return jnp.sin(x)
def f_jvp(primals, tangents):
x, = primals
g, = tangents
return f(x), 2 * jnp.cos(x) * g
f.defjvp(f_jvp)
x = 3.
# jit
self.assertAllClose(api.jit(f)(x), jnp.sin(x))
self.assertAllClose(api.jit(api.jit(f))(x), jnp.sin(x))
# jit of jvp
self.assertAllClose(api.jit(lambda x: api.jvp(f, (x,), (x,)))(x),
(jnp.sin(x), 2 * jnp.cos(x) * x),
check_dtypes=False)
# jvp of jit
self.assertAllClose(api.jvp(api.jit(f), (x,), (x,)),
(jnp.sin(x), 2 * jnp.cos(x) * x),
check_dtypes=False)
def test_pytrees(self):
@jax.custom_jvp
def f(x):
return {'b': jnp.sin(x['a'])}
def f_jvp(primals, tangents):
x, = primals
g, = tangents
return f(x), {'b': 2 * jnp.cos(x['a']) * g['a']}
f.defjvp(f_jvp)
x = {'a': 3.}
self.assertAllClose(f(x)['b'], jnp.sin(x['a']))
self.assertAllClose(api.jvp(f, (x,), (x,)),
({'b': jnp.sin(x['a'])},
{'b': 2 * jnp.cos(x['a']) * x['a']}),
check_dtypes=False)
def test_kwargs(self):
# from https://github.com/jax-ml/jax/issues/1938
@jax.custom_jvp
def my_fun(x, y, c=1.):
return c * (x + y)
def my_jvp(primals, tangents):
x, y, c = primals
t_x, t_y, t_c = tangents
return my_fun(x, y, c), t_c
my_fun.defjvp(my_jvp)
f = lambda x, y: jnp.square(my_fun(x, y, c=2.)).sum()
f(10., 5.) # doesn't crash
api.jvp(f, (10., 5.), (1., 1.)) # doesn't crash
def test_initial_style(self):
@jax.custom_jvp
def f(x):
return 3 * x
def f_jvp(primals, tangents):
x, = primals
g, = tangents
return f(x), 2 * g
f.defjvp(f_jvp)
def foo(x):
out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)
return out
ans = api.grad(foo)(3.)
expected = 2.
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.grad(api.jit(foo))(3.)
expected = 2.
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.jit(api.grad(foo))(3.)
expected = 2.
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.grad(api.grad(foo))(3.)
expected = 0.
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.grad(api.grad(api.jit(foo)))(3.)
expected = 0.
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.grad(api.jit(api.grad(foo)))(3.)
expected = 0.
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.jit(api.grad(api.grad(foo)))(3.)
expected = 0.
self.assertAllClose(ans, expected, check_dtypes=False)
def test_initial_style_vmap(self):
@jax.custom_jvp
def f(x):
assert jnp.ndim(x) == 0
return 3 * x
def f_jvp(primals, tangents):
x, = primals
g, = tangents
return f(x), 2 * g
f.defjvp(f_jvp)
def foo(x):
out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)
return out
ans = api.vmap(foo)(jnp.ones(3))
expected = 3. * jnp.ones(3)
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.vmap(api.jit(foo))(jnp.ones(3))
expected = 3. * jnp.ones(3)
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.jit(api.vmap(foo))(jnp.ones(3))
expected = 3. * jnp.ones(3)
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.grad(lambda x: api.vmap(foo)(x).sum())(jnp.ones(3))
expected = 2. * jnp.ones(3)
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.grad(lambda x: api.vmap(api.jit(foo))(x).sum())(jnp.ones(3))
expected = 2. * jnp.ones(3)
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.grad(lambda x: api.jit(api.vmap(foo))(x).sum())(jnp.ones(3))
expected = 2. * jnp.ones(3)
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.grad(api.jit(lambda x: api.vmap(foo)(x).sum()))(jnp.ones(3))
expected = 2. * jnp.ones(3)
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.jit(api.grad(lambda x: api.vmap(foo)(x).sum()))(jnp.ones(3))
expected = 2. * jnp.ones(3)
self.assertAllClose(ans, expected, check_dtypes=False)
def test_initial_style_vmap_with_collective(self):
@jax.custom_jvp
def f(x):
return lax.psum(x, 'foo')
@f.defjvp
def f_jvp(xs, ts):
x, = xs
t, = ts
return lax.psum(x, 'foo'), t
def g(x):
jaxpr = api.make_jaxpr(f)(x)
return core.eval_jaxpr(jaxpr.jaxpr, [], x)[0]
v = api.vmap(lambda _, x: g(x), axis_name='foo', in_axes=(0, None),
out_axes=None)(jnp.arange(4.), 2.)
self.assertAllClose(v, 8.)
def test_closed_over_tracers_error_message(self):
def f(x):
@jax.custom_jvp
def g(y):
return x + y
def g_jvp(primals, tangents):
return g(x), 2 * primals[0]
g.defjvp(g_jvp)
return g(1.)
self.assertRaises(UnexpectedTracerError, lambda: api.jvp(f, (3.,), (1.,)))
self.assertRaises(UnexpectedTracerError, lambda: api.grad(f)(3.))
def test_nondiff_argnums(self):
@partial(jax.custom_jvp, nondiff_argnums=(0,))
def app(f, x):
return f(x)
def app_jvp(f, primals, tangents):
(x,), (t,) = primals, tangents
return app(f, x), 3 * t
app.defjvp(app_jvp)
ans = app(lambda x: 2 * x, 1)
expected = 2
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.jvp(lambda x: app(lambda y: 2 * y, x), (1.,), (1.,))
expected = (2., 3.)
self.assertAllClose(ans, expected, check_dtypes=False)
def test_nondiff_argnames(self):
@partial(jax.custom_jvp, nondiff_argnames=('f',))
def app(f, x):
return f(x)
def app_jvp(f, primals, tangents):
(x,), (t,) = primals, tangents
return app(f, x), 3 * t
app.defjvp(app_jvp)
ans = app(lambda x: 2 * x, 1)
expected = 2
self.assertAllClose(ans, expected, check_dtypes=False)
def test_nondiff_arg_jit_tracer(self):
# This test would pass with "final-style" JIT tracing, but that was
# misleading: it doesn't work with "initial-style" staging, i.e. control
# flow primitives like jax.lax.scan or even pjit. The behavior isn't very
# useful either: instead of using nondiff_argnums here, a user can just pass
# such inputs as ordinary arguments, and ignore the corresponding tangents.
# Then nondiff_argnums can be reserved for (1) non jaxtype data (like a
# string- or callable-valued argument which parameterizes the function or
# rule) or (2) static data (e.g. integers which parameterize shapes).
raise unittest.SkipTest("behavior no longer supported")
@partial(jax.custom_jvp, nondiff_argnums=(0,))
def f(x, y):
return x * y
def f_jvp(x, primals, tangents):
(y,), (t_y,) = primals, tangents
return f(x, y), 5 * t_y
f.defjvp(f_jvp)
@jit
def g(x, y):
return f(x, y)
ans = api.jvp(lambda y: g(2., y), (3.,), (1.,))
expected = (6., 5.)
self.assertAllClose(ans, expected, check_dtypes=False)
def test_nondiff_arg_vmap_tracer(self):
@partial(jax.custom_jvp, nondiff_argnums=(0,))
def f(x, y):
return x * y
def f_jvp(x, primals, tangents):
(y,), (t_y,) = primals, tangents
return f(x, y), 5 * t_y
f.defjvp(f_jvp)
g = jax.vmap(f)
ans = api.jvp(lambda y: g(jnp.array([2.]), y),
(jnp.array([3.]),), (jnp.array([1.]),))
expected = (jnp.array([6.]), jnp.array([5.]))
self.assertAllClose(ans, expected, check_dtypes=False)
def test_nondiff_arg_hiding_jvp_tracer(self):
def f(x):
@partial(jax.custom_jvp, nondiff_argnums=(0,))
def g(h, x):
return h(x)
@g.defjvp
def g_jvp(h, primals, tangents):
x, = primals
t, = tangents
return g(h, x), 2. * t
h = lambda y: x + y # capture x
return g(h, x)
with self.assertRaises(UnexpectedTracerError):
api.jvp(f, (2.,), (1.,))
def test_vmap_axes(self):
raise unittest.SkipTest("TODO") # TODO(mattjj): write test
def test_pmap(self):
raise unittest.SkipTest("TODO") # TODO(mattjj): write test
def test_missing_jvp_rule_error_message(self):
@jax.custom_jvp
def foo(x):
return x ** 2
self.assertRaisesRegex(
AttributeError,
r"No JVP defined for custom_jvp function foo using defjvp.",
lambda: foo(2))
self.assertRaisesRegex(
AttributeError,
r"No JVP defined for custom_jvp function foo using defjvp.",
lambda: api.jvp(foo, (2.,), (1.,)))
self.assertRaisesRegex(
AttributeError,
r"No JVP defined for custom_jvp function foo using defjvp.",
lambda: api.grad(foo)(2.))
def test_jvp_rule_inconsistent_pytree_structures_error_message(self):
@jax.custom_jvp
def f(x):
return (x**2,)
@f.defjvp
def foo_jvp(primals, tangents):
x, = primals
t, = tangents
return f(x), [2 * x * t, x]
f(2.) # doesn't crash
self.assertRaisesRegex(
TypeError,
re.escape(
"Custom JVP rule foo_jvp for function f "
"must produce primal and tangent outputs "
"with equal container (pytree) structures, but got "
"{} and {} respectively.".format(
jax.tree.structure((1,)),
jax.tree.structure([1, 2]))
),
lambda: api.jvp(f, (2.,), (1.,)))
def test_primal_tangent_aval_disagreement_error_message(self):
@jax.custom_jvp
def f(x):
return x ** 2
@f.defjvp
def foo_jvp(primals, tangents):
x, = primals
t, = tangents
return f(x), jnp.reshape(t, (1,))
f(2.) # doesn't crash
self.assertRaisesRegex(
TypeError,
re.escape(
"Custom JVP rule must produce primal and tangent outputs "
"with corresponding shapes and dtypes. "
"Expected float32[] (tangent type of float32[]) but got float32[1]."),
lambda: api.jvp(f, (jnp.float32(2.),), (jnp.float32(1.),)))
def test_jvp_rule_doesnt_return_pair_error_message(self):
# https://github.com/jax-ml/jax/issues/2516
@jax.custom_jvp
def f(x):
return x ** 2
@f.defjvp
def foo_jvp(primals, tangents):
x, = primals
t, = tangents
return t
f(2.) # doesn't crash
self.assertRaisesRegex(
TypeError,
re.escape(
"Custom JVP rule foo_jvp for function f "
"must produce a pair (list or tuple of length two) "
"representing primal and tangent outputs, but got 1.0"),
lambda: api.jvp(f, (2.,), (1.,)))
def test_jvp_rule_primal_out_type_doesnt_match_primal_error_message(self):
# https://github.com/lucidrains/flash-attention-jax/issues/7
def scan_apply(f, x):
y, _ = jax.lax.scan(lambda x, _: (f(x), None), x, None, length=1)
return y
@jax.custom_jvp
def f(x):
return x
@f.defjvp
def f_jvp(primals, tangents):
(x,), (xdot,) = primals, tangents
return (x, x), (xdot, xdot)
x = jnp.float32(1.)
self.assertRaisesRegex(
TypeError,
re.escape(
"Custom JVP rule f_jvp for function f must produce a pair "
"(list or tuple of length two) where the first element represents "
"the primal output (equal in value to the output of the "
"custom_jvp-decorated function f, and in particular of the "
"same container/pytree structure), but instead the JVP rule "
"output's first element had container/pytree structure:\n"
" (float32[], float32[])\n"
"while the custom_jvp-decorated function f had output "
"container/pytree structure:\n"
" float32[]."
),
lambda: jax.jvp(lambda x: scan_apply(f, x), (x,), (x,)))
@f.defjvp
def f_jvp2(primals, tangents):
(x,), (xdot,) = primals, tangents
return jnp.zeros((3, *x.shape), x.dtype), xdot
self.assertRaisesRegex(
TypeError,
re.escape(
"Custom JVP rule f_jvp2 for function f must produce a pair "
"(list or tuple of length two) where the first element represents "
"the primal output (equal in value to the output of the "
"custom_jvp-decorated function f, and in particular "
"with leaves of the same shape/dtype), but instead the JVP rule "
"output's first element had shapes/dtypes of:\n"
" float32[3]\n"
"while the custom_jvp-decorated function f had output shapes/dtypes"
" of:\n"
" float32[]"
),
lambda: jax.jvp(lambda x: scan_apply(f, x), (x,), (x,)))
def test_multiple_rule_invocations(self):
@jax.custom_jvp
def expit(x):
return 1 / (1 + lax.exp(-x))
@expit.defjvp
def _expit_jvp(primals, tangents):
(x,), (t,) = primals, tangents
ans = expit(x)
t_out = t * ans * (1 - ans)
return ans, t_out
def scanned_fun(c, _):
return [expit(c[0])] + [c[i-1] + c[i] for i in range(1, len(c))], None
def foo(x):
zero = jnp.zeros_like(x)
c, _ = lax.scan(scanned_fun, [x, zero, zero, zero, zero], None, length=10)
return c[-1]
# just make sure these don't crash
foo(3.)
grad(foo)(3.)
grad(lambda x: jax.vmap(foo)(x).sum())(jnp.arange(3.))
def test_hard_stuff(self):
arr = jnp.ones((5, 2, 2))
api.jit(jax.vmap(jnp.linalg.det))(arr) # doesn't crash
def test_hard_stuff2(self):
@jax.custom_jvp
def f(x):
return np.zeros(x.shape, x.dtype)
@f.defjvp
def f_jvp(primals, tangents):
x, = primals
t, = tangents
return f(x), t
# don't crash
jax.jit(jax.vmap(f))(jnp.arange(3.))
jax.jit(jax.vmap(jax.grad(f)))(jnp.arange(3.))
jax.jit(jax.grad(lambda x: jax.vmap(f)(x).sum()))(jnp.arange(3.))
jax.grad(lambda x: jax.vmap(f)(x).sum())(jnp.arange(3.))
jax.jvp(jax.vmap(f), (jnp.arange(3.),), (jnp.ones(3),))
def test_hard_stuff3(self):
@jax.custom_jvp
def relu(x):
return jnp.maximum(x, 0)
@relu.defjvp
def _relu_jvp(primals, tangents):
x, = primals
t, = tangents
return relu(x), lax.select(x > 0, t, lax.full_like(t, 0))
def scanned_fun(c, _):
return [relu(c[0])] + [c[i-1] + c[i] for i in range(1, len(c))], None
def f(x):
zero = jnp.zeros_like(x)
c, _ = lax.scan(scanned_fun, [x, zero, zero, zero, zero], None, length=10)
return c[-1]
# don't crash
jax.jit(jax.vmap(f))(jnp.arange(3.))
jax.jit(jax.vmap(jax.grad(f)))(jnp.arange(3.))
jax.jit(jax.grad(lambda x: jax.vmap(f)(x).sum()))(jnp.arange(3.))
jax.grad(lambda x: jax.vmap(f)(x).sum())(jnp.arange(3.))
jax.jvp(jax.jit(jax.vmap(f)), (jnp.arange(3.),), (jnp.ones(3),))
def test_eval_shape(self):
@jax.custom_jvp
def expit(x):
return 1 / (1 + lax.exp(-x))
@expit.defjvp
def _expit_jvp(primals, tangents):
(x,), (t,) = primals, tangents
ans = expit(x)
t_out = t * ans * (1 - ans)
return ans, t_out
# don't crash
api.eval_shape(expit, jnp.ones((2, 3)))
api.eval_shape(api.grad(lambda x: expit(x).sum()), jnp.ones((2, 3)))
def test_jaxpr_zeros(self):
# from https://github.com/jax-ml/jax/issues/2657
@jax.custom_jvp
def f(A, b):
return A @ b
def f_jvp(primals, tangents):
A, b = primals
dA, db = tangents
z = f(A, b)
dz = A @ db + dA @ b
return z, dz
f.defjvp(f_jvp)
def experiment(theta):
def step(q, _):
z = f(jnp.eye(3), jnp.ones(3) * theta)
q += z[0]
return q, q
q = 0.
q, _ = lax.scan(step, q, None, 4)
return q
grad(experiment)(1.) # doesn't crash
def test_linear_in_scan(self):
@jax.custom_jvp
def f(x):
return -x
@f.defjvp
def f_jvp(primals, tangents):
x, = primals
x_dot, = tangents
return f(x), f(x_dot)
def foo(x):
out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)
return out
ans = api.grad(foo)(3.)
expected = -1.
self.assertAllClose(ans, expected, check_dtypes=False)
def test_custom_jvps_first_rule_is_none(self):
# https://github.com/jax-ml/jax/issues/3389
@jax.custom_jvp
def f(x, y):
return x ** 2 * y
f.defjvps(None, lambda x_dot, primal_out, x, y: 2 * x * y * x_dot)
ans = grad(f, 1)(2., 3.) # doesn't crash
expected = 12.
self.assertAllClose(ans, expected, check_dtypes=False)
def test_concurrent_initial_style(self):
# https://github.com/jax-ml/jax/issues/3843
def unroll(param, sequence):
def scan_f(prev_state, inputs):
return prev_state, jax.nn.sigmoid(param * inputs)
return jnp.sum(jax.lax.scan(scan_f, None, sequence)[1])
def run():
return jax.grad(unroll)(jnp.array(1.0), jnp.array([1.0]))
expected = run()
# we just don't want this to crash
n_workers = 2
with concurrent.futures.ThreadPoolExecutor(max_workers=n_workers) as e:
futures = []
for _ in range(n_workers):
futures.append(e.submit(run))
results = [f.result() for f in futures]
for ans in results:
self.assertAllClose(ans, expected)
def test_nondiff_argnums_vmap_tracer(self):
# https://github.com/jax-ml/jax/issues/3964
@partial(jax.custom_jvp, nondiff_argnums=(0, 2))
def sample(shape, param, seed):
return jax.random.uniform(key=seed, shape=shape, minval=param)
@sample.defjvp
def sample_jvp(shape, seed, primals, tangents):
param, = primals
dparam, = tangents
dparam = jnp.broadcast_to(dparam, shape)
samples = sample(shape, param, seed)
return samples, samples * dparam # dummy jvp for proof of concept
# check these don't crash
jax.vmap(lambda seed: sample((2,3), 1., seed))(
jax.random.split(jax.random.key(1), 10))
jax.jvp(lambda x: sample((2, 3), x, jax.random.key(1)),
(1.,), (1.,))
def test_fun_with_nested_calls_2(self):
def call(f, *args):
f = jax.custom_jvp(f)
f.defjvp(lambda primals, tangents: (f(*primals), sum(tangents)))
return f(*args)
def fun_with_nested_calls_2(x):
def bar(y):
def baz(w):
q = call(lambda x: y, x)
q = q + call(lambda: y)
q = q + call(lambda y: w + y, y)
q = call(lambda w: call(jnp.sin, x) * y, 1.0) + q
return q
return api.jit(baz)(x)
return call(bar, x)
# test these don't crash
self.assertAllClose(api.jit(fun_with_nested_calls_2)(3.),
fun_with_nested_calls_2(3.))
api.vmap(fun_with_nested_calls_2)(jnp.arange(3.))
def test_closure_with_vmap(self):
# https://github.com/jax-ml/jax/issues/3822
alpha = np.float32(2.)
def sample(seed):
@jax.custom_jvp
def f(alpha):
return jax.random.gamma(seed, alpha, shape=[])
@f.defjvp
def f_jvp(primal, tangent):
alpha = primal
dalpha = tangent
sample = f(alpha)
partial_alpha = lax.random_gamma_grad(alpha, sample)
return sample, partial_alpha * dalpha
return f(alpha)
api.vmap(sample)(jax.random.split(jax.random.key(1), 3)) # don't crash
def test_closure_with_vmap2(self):
# https://github.com/jax-ml/jax/issues/8783
def h(z):
def f(x):
@jax.custom_jvp
def g(y):
return x * y
# NOTE: rule closes over vmap tracer
@g.defjvp
def g_jvp(primals, tangents):
(y,), (ydot,) = primals, tangents
return x * y, x * ydot
return g(z) # NOTE: no vmapped arg
return jax.vmap(f)(jnp.arange(3., dtype='float32'))
primals, tangents = jax.jvp(h, (jnp.float32(1.),), (jnp.float32(2.),))
self.assertAllClose(primals , jnp.arange(3., dtype='float32'))
self.assertAllClose(tangents, 2 * jnp.arange(3., dtype='float32'))
def test_float0(self):
scalar_float0 = jnp.zeros((), dtype=float0)
@jax.custom_jvp
def f(x, y):
return x, y
def f_jvp(primals, _):
x, y = primals
return (x, y), (2., jax.custom_derivatives.zero_from_primal(y))
f.defjvp(f_jvp)
primals = (2., 3)
tangents = (np.ones(()), scalar_float0)
expected_tangents = (2., scalar_float0)
self.assertAllClose(api.jvp(f, primals, tangents),
(primals, expected_tangents))
def test_float0_initial_style(self):
scalar_float0 = jnp.zeros((), dtype=float0)
@jax.custom_jvp
def f(x, y):
return x, y
def f_jvp(primals, _):
x, y = primals
return (x, y), (2., jax.custom_derivatives.zero_from_primal(y))
f.defjvp(f_jvp)
def foo(x, y):
out, _ = lax.scan(lambda c, _: (f(*c), None), (x, y), None, length=1)
return out
primals = (2., 3)
tangents = (np.ones(()), scalar_float0)
expected_tangents = (2., scalar_float0)
self.assertAllClose(api.jvp(foo, primals, tangents),
(primals, expected_tangents))
def test_remat(self):
@jax.custom_jvp
def f(x):
return jnp.sin(x)
def f_jvp(primals, tangents):
x, = primals
g, = tangents
return f(x), 2 * jnp.cos(x) * g
f.defjvp(f_jvp)
@jax.remat
def g(x):
return f(f(x))
ans = g(2.)
expected = np.sin(np.sin(2.))
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.grad(g)(2.)
expected = 4. * api.grad(lambda x: jnp.sin(jnp.sin(x)))(2.)
self.assertAllClose(ans, expected, check_dtypes=False)
def test_remat_higher_order(self):
@jax.custom_jvp
def f(x):
return jnp.sin(x)
def f_jvp(primals, tangents):
x, = primals
g, = tangents
return f(x), 2 * jnp.cos(x) * g
f.defjvp(f_jvp)
def g(x):
return f(f(x))
ans = api.grad(api.grad(jax.checkpoint(g)))(2.)
expected = api.grad(api.grad(g))(2.)
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.grad(jax.checkpoint(api.grad(g)))(2.)
expected = api.grad(api.grad(g))(2.)
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.grad(api.grad(api.grad(jax.checkpoint(g))))(2.)
expected = api.grad(api.grad(api.grad(g)))(2.)
self.assertAllClose(ans, expected, check_dtypes=False)
def test_initial_style_vmap_2(self):
# This is like test_initial_style_vmap except the primal function closes
# over an array constant.
y = jnp.arange(1., 4.)
@jax.custom_jvp
def f(x):
assert jnp.ndim(x) == 0
return 3 * x * jnp.sum(y)
def f_jvp(primals, tangents):
x, = primals
g, = tangents
return f(x), 2 * g
f.defjvp(f_jvp)
def foo(x):
out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)
return out
ans = api.grad(lambda x: api.vmap(foo)(x).sum())(jnp.ones(3))
expected = 2. * jnp.ones(3)
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.grad(lambda x: api.vmap(api.jit(foo))(x).sum())(jnp.ones(3))
expected = 2. * jnp.ones(3)
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.grad(lambda x: api.jit(api.vmap(foo))(x).sum())(jnp.ones(3))
expected = 2. * jnp.ones(3)
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.grad(api.jit(lambda x: api.vmap(foo)(x).sum()))(jnp.ones(3))
expected = 2. * jnp.ones(3)
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.jit(api.grad(lambda x: api.vmap(foo)(x).sum()))(jnp.ones(3))
expected = 2. * jnp.ones(3)
self.assertAllClose(ans, expected, check_dtypes=False)
def test_custom_jvp_vmap_broadcasting_interaction(self):
# https://github.com/jax-ml/jax/issues/6452
def f2(y, z):
v1 = z
v2 = jnp.sum(y) + z
return jnp.logaddexp(v1, v2)
def f1(y, z):
v = api.vmap(lambda _y: f2(_y, z))(y)
return jnp.sum(v)
y = jnp.ones((3, 2))
f = lambda z: f1(y, z)
z = 0.1
val, g = api.value_and_grad(f)(z)
self.assertEqual(val.shape, ())
self.assertEqual(g.shape, ())
def test_custom_jvp_vmap_broadcasting_interaction_2(self):
# https://github.com/jax-ml/jax/issues/5849
@jax.custom_jvp
def transform(box, R):
if jnp.isscalar(box) or box.size == 1:
return R * box
elif box.ndim == 2:
return jnp.einsum('ij,j->i', box, R)
raise ValueError()
@transform.defjvp
def transform_jvp(primals, tangents):
box, R = primals
dbox, dR = tangents
return (transform(box, R), dR + transform(dbox, R))
def periodic_general(box):
def displacement_fn(Ra, Rb, **kwargs):
_box = kwargs.get('box', box)
return transform(_box, Ra - Rb)
return displacement_fn
N = 250
scalar_box = 1.0
displacement = periodic_general(scalar_box)
key = jax.random.key(0)
R = jax.random.uniform(key, (N, 2))
def energy_fn(box):
d = partial(displacement, box=box)
d = api.vmap(api.vmap(d, (None, 0)), (0, None))
return jnp.sum(d(R, R) ** 2)
self.assertEqual(grad(energy_fn)(scalar_box).shape, ())
def test_custom_jvp_implicit_broadcasting(self):
# https://github.com/jax-ml/jax/issues/6357
if config.enable_x64.value:
raise unittest.SkipTest("test only applies when x64 is disabled")
@jax.custom_jvp
def projection_unit_simplex(x: jax.Array) -> jax.Array:
"""Projection onto the unit simplex."""
s = 1.0
n_features = x.shape[0]
u = jnp.sort(x)[::-1]
cssv = jnp.cumsum(u) - s
ind = jnp.arange(n_features, dtype=x.dtype) + 1
cond = u - cssv / ind > 0
idx = jnp.count_nonzero(cond)
threshold = cssv[idx - 1] / idx.astype(x.dtype)
return jax.nn.relu(x - threshold)
@projection_unit_simplex.defjvp
def projection_unit_simplex_jvp(primals, tangents):
x, = primals
x_dot, = tangents
primal_out = projection_unit_simplex(x)
supp = (primal_out > 0).astype(x_dot.dtype)
card = jnp.count_nonzero(supp).astype(x_dot.dtype)
tangent_out = supp * x_dot - (jnp.dot(supp, x_dot) / card) * supp
return primal_out, tangent_out
rng = self.rng()
x = rng.rand(5).astype(np.float32)
J_rev = jax.jacrev(projection_unit_simplex)(x)
J_fwd = jax.jacfwd(projection_unit_simplex)(x)
p = projection_unit_simplex(x)
support = (p > 0).astype(jnp.float32)
cardinality = jnp.count_nonzero(support).astype(support.dtype)
J_true = jnp.diag(support) - jnp.outer(support, support) / cardinality
self.assertAllClose(J_true, J_fwd)
self.assertAllClose(J_true, J_rev)
proj = jax.vmap(projection_unit_simplex)
def fun(X):
return jnp.sum(proj(X) ** 2)
rng = self.rng()
X = rng.rand(4, 5).astype(np.float32)
U = rng.rand(4, 5)
U /= np.sqrt(np.sum(U ** 2))
U = U.astype(np.float32)
eps = 1e-3
dir_deriv_num = (fun(X + eps * U) - fun(X - eps * U)) / (2 * eps)
dir_deriv = jnp.vdot(jax.grad(fun)(X), U)
self.assertAllClose(dir_deriv, dir_deriv_num, atol=1e-3)
def test_vmap_inside_defjvp(self):
# https://github.com/jax-ml/jax/issues/3201
seed = 47
key = jax.random.key(seed)
mat = jax.random.normal(key, (2, 3))
@jax.custom_jvp
def f(mat, aux):
num_rows, num_cols = mat.shape
return jnp.ones((num_rows, 1)) / num_cols
@f.defjvp
def f_jvp(primals, tangents):
mat, aux = primals
vec, _ = tangents
output = f(*primals)
num_rows, num_cols = mat.shape
size = num_rows * num_cols
# -----
bd_mat = mat.reshape(1, 1, num_rows, num_cols)
bd_mat = jnp.tile(bd_mat, reps=(num_rows, num_cols))
bd_mat = bd_mat.reshape(size, num_rows, num_cols)
# -----
rowsum = jnp.sum(mat, axis=1, keepdims=True)
colsum = jnp.sum(mat, axis=0, keepdims=True)
bd_rowsum = jnp.tile(rowsum, reps=(1, num_rows))
bd_colsum = jnp.tile(colsum, reps=(num_cols, 1))
# -----
bd_vec = vec.reshape(size, 1)
# -----
def operate(mx, val):
buf = 0
for i in range(2):
buf = buf + jnp.matmul(mx, bd_colsum) / jnp.power(aux, i)
buf = jnp.matmul(bd_rowsum, buf)
return buf * val[None, :]
# -----
# Vertorizing will raise shape error
bd_buf = jax.vmap(operate, in_axes=(0, 0), out_axes=0)(bd_mat, bd_vec)
# -----
bd_buf = bd_buf / aux
jvp = jnp.sum(bd_buf, axis=0)
jvp = jnp.mean(jvp, axis=1, keepdims=True)
# -----
# JVP ends successfully, but still raise an error
return (output, jvp)
jax.grad(lambda mat, aux: jnp.sum(f(mat, aux)))(mat, 0.5) # doesn't crash
def test_custom_jvp_unbroadcasting(self):
# https://github.com/jax-ml/jax/issues/3056
a = jnp.array([1., 1.])
@jax.custom_jvp
def f(x):
return a * x
@f.defjvp
def f_jvp(primals, tangents):
x, = primals
dx, = tangents
return a * x, a * dx
shape = grad(lambda x: jnp.sum(f(x)))(jnp.array(1.)).shape
self.assertEqual(shape, ())
def test_maybe_perturbed_internal_helper_function(self):
# This is a unit test for an internal API. We include it so as not to
# regress https://github.com/jax-ml/jax/issues/9567. For an explanation of
# this helper function, see https://github.com/jax-ml/jax/issues/6415.
def f(x):
def g(y, _):
z = y * x
self.assertTrue(custom_derivatives._maybe_perturbed(z))
return y, None
g(1, None)
return lax.scan(g, 1, xs=None, length=1)[0]
jax.jvp(f, (1.0,), (1.0,)) # assertions inside f
def test_maybe_perturbed_int_regression(self):
# see https://github.com/jax-ml/jax/discussions/9951
@jax.jit
def f():
x = jnp.array(1)
_, aux_args = custom_derivatives.closure_convert(lambda: x)
self.assertEmpty(aux_args)
f()
def test_sinc_constant_function_batching(self):
# https://github.com/jax-ml/jax/pull/10756
batch_data = jnp.arange(15.).reshape(5, 3)
@jax.vmap
def f(x):
return jax.lax.map(jnp.sinc, x)
g = lambda param: f(param * batch_data).sum()
@jax.vmap
def f_ref(x):
return jnp.stack([jnp.sinc(x_) for x_ in x])
g_ref = lambda param: f_ref(param * batch_data).sum()
grad = jax.grad(g )(0.1) # doesn't crash
grad_ref = jax.grad(g_ref)(0.1)
self.assertAllClose(grad, grad_ref, check_dtypes=False)
@parameterized.named_parameters(
('jit_vmap', True, True),
('jit', True, False),
('vmap', False, True),
('', False, False),
)
def test_symbolic_zero_custom_jvp(self, maybe_jit, maybe_vmap):
def f(static_scalar, static_array, dyn_scalar, dyn_array):
out1 = static_scalar + dyn_scalar
out2 = static_array + dyn_array
return out1, out2
def _pack(x):
return lax.broadcast(x, (1,))
def _unpack(x):
(x,) = x
return x
def _vmap(fun):
def _fun(*args):
args = jax.tree.map(_pack, args)
out = jax.vmap(fun)(*args)
out = jax.tree.map(_unpack, out)
return out
return _fun
f = jax.custom_jvp(f)
@partial(f.defjvp, symbolic_zeros=True)
def f_jvp(primals, tangents):
static_scalar, *_ = primals
t_static, t_static_arr, t_dyn_scalar, t_dyn_array = tangents
self.assertIs(type(t_static) , jax.custom_derivatives.SymbolicZero)
self.assertIs(type(t_static_arr), jax.custom_derivatives.SymbolicZero)
self.assertEqual(t_static.shape, ())
self.assertEqual(t_static_arr.shape, (2,))
return f(*primals), (static_scalar + 90, t_dyn_array + 91)
def g(dyn_scalar, dyn_array):
if maybe_vmap:
f_ = _vmap(f)
else:
f_ = f
return f_(1., jnp.array([2., 3.]), dyn_scalar, dyn_array)
def run(primal_ins, tangent_ins):
return jax.jvp(g, primal_ins, tangent_ins)
if maybe_jit:
run = jax.jit(run)
primal_ins = (4., jnp.array([5., 6.]))
tangent_ins = (7., jnp.array([8., 9.]))
primal_outs, tangent_outs = run(primal_ins, tangent_ins)
primal_out1, primal_out2 = primal_outs
tangent_out1, tangent_out2 = tangent_outs
scalar_type = jax.Array if maybe_jit or maybe_vmap else float
self.assertIsInstance(primal_out1, scalar_type)
self.assertAllClose(primal_out1, 5.)
self.assertIsInstance(tangent_out1, scalar_type)
self.assertAllClose(tangent_out1, 91.)
self.assertIsInstance(primal_out2, jax.Array)
self.assertArraysAllClose(primal_out2, jnp.array([7., 9.]))
self.assertIsInstance(tangent_out2, jax.Array)
self.assertArraysAllClose(tangent_out2, jnp.array([99., 100.]))
def test_symbolic_zero_custom_jvp_vmap_output(self):
@jax.custom_jvp
def f(x, y):
return x * y
@partial(f.defjvp, symbolic_zeros=True)
def f_jvp(primals, tangents):
x, y = primals
x_dot, y_dot = tangents
self.assertIs(type(y_dot), jax.custom_derivatives.SymbolicZero)
return f(x, y), y_dot
jax.grad(lambda x, y: jax.vmap(f)(x, y).sum())(jnp.ones(3), jnp.ones(3))
def test_symbolic_zeros_memoization_caching(self):
# Tests multiple zero patterns for partial_eval._memoize, and also tests
# that we're okay with stores being occupied with equal values.
@jax.custom_jvp
def f(x, y):
return x * y
@partial(f.defjvp, symbolic_zeros=True)
def f_jvp(primals, tangents):
x, y = primals
x_dot, y_dot = tangents
return f(x, y), y_dot
f_ = core.jaxpr_as_fun(jax.make_jaxpr(f)(2., 3.))
_ = jax.linearize(f_, 2., 3.)
_ = jax.linearize(lambda x: f_(x, 3.), 2.) # don't crash!
def test_symbolic_zeros_under_jit(self):
# https://github.com/jax-ml/jax/issues/14833
Zero = jax.custom_derivatives.SymbolicZero
@jax.custom_jvp
def f(x, y):
return x * y
@partial(f.defjvp, symbolic_zeros=True)
def fjvp(primals, tangents):
x, y = primals
tx, ty = tangents
assert type(tx) is not Zero or type(ty) is not Zero
return f(x, y), (
ty if type(tx) is Zero else
tx if type(ty) is Zero else
tx + ty)
jax.jacfwd(jax.jit(f))(0.1, 0.2) # don't crash
def test_custom_jvp_functools_partial(self):
def fun(x, y, a):
return x + y * a
fun_wrapped = functools.partial(fun, a = 0.1)
def jvp_fn(primals, tangents):
return jax.jvp(fun_wrapped, primals, tangents)
fn = jax.custom_jvp(fun_wrapped)
fn.defjvp(jvp_fn)
self.assertEqual((1.0, 0.1), jax.grad(lambda args: fn(*args))((1.0, 2.0)))
def test_run_rules_more_than_once(self):
# https://github.com/jax-ml/jax/issues/16614
@jax.custom_jvp
def f(x, y):
return x
@partial(f.defjvp, symbolic_zeros=True)
def f_jvp(primals, tangents):
x, _ = primals
x_dot, _ = tangents
return x, x_dot
def body(x_y, _):
x, y = x_y
return (f(x, y), x), None
@jax.grad
def g(x):
(out, _), _ = lax.scan(body, (x, 1.), xs=None, length=2)
return out
g(1.) # doesn't crash
def test_dce(self):
@jax.custom_jvp
def f(x, y):
return jnp.sin(x), x + jnp.cos(y)
@f.defjvp
def f_jvp(primals, tangents):
x, y = primals
dx, dy = tangents
return f(x, y), (2.0 * jnp.cos(x) * dx, 1.5 * dx - 0.5 * jnp.sin(y) * dy)
def check_jaxpr(jaxpr, used_outs, includes, excludes):
dce_jaxpr, _ = pe.dce_jaxpr(jaxpr, used_outs)
if not dce_jaxpr.eqns:
assert not includes
return
call_jaxpr = dce_jaxpr.eqns[0].params["call_jaxpr"]
for prim in includes:
assert any(eqn.primitive == prim for eqn in call_jaxpr.eqns)
for prim in excludes:
assert all(eqn.primitive != prim for eqn in call_jaxpr.eqns)
x, y = 0.1, -1.3
jaxpr = jax.make_jaxpr(f)(x, y).jaxpr
check_jaxpr(jaxpr, [True, True], [lax.sin_p, lax.cos_p], [])
check_jaxpr(jaxpr, [True, False], [lax.sin_p], [lax.cos_p])
check_jaxpr(jaxpr, [False, True], [lax.cos_p], [lax.sin_p])
check_jaxpr(jaxpr, [False, False], [], [lax.sin_p, lax.cos_p])
def dce_jaxpr_as_fun(jaxpr, used_outs):
jaxpr_, _ = pe.dce_jaxpr(jaxpr, used_outs)
fun = core.jaxpr_as_fun(pe.close_jaxpr(jaxpr_))
return lambda *args: fun(*args)[0]
f0 = dce_jaxpr_as_fun(jaxpr, [True, False])
f1 = dce_jaxpr_as_fun(jaxpr, [False, True])
self.assertAllClose(
api.jvp(f0, (x, y), (1.0, 0.0)), (f0(x, y), 2.0 * jnp.cos(x)))
self.assertAllClose(
api.jvp(f0, (x, y), (0.0, 1.0)), (f0(x, y), 0.0))
self.assertAllClose(
api.jvp(f1, (x, y), (1.0, 0.0)), (f1(x, y), 1.5))
self.assertAllClose(
api.jvp(f1, (x, y), (0.0, 1.0)), (f1(x, y), -0.5 * jnp.sin(y)))
def test_dce_symbolic_zeros(self):
# https://github.com/jax-ml/jax/issues/31448
@jax.custom_jvp
def f(x):
return x
@partial(f.defjvp, symbolic_zeros=True)
def f_jvp(primals, tangents):
x, = primals
tx, = tangents
return f(x), tx
@jax.jacfwd
@jax.jacrev
def f_wrapped(x):
return jax.jit(f)((x, 3.))
f_wrapped(jnp.zeros(2)) # doesn't crash
def test_resolve_kwargs_error_message(self):
@jax.custom_jvp
def f(x, y, *, z=None):
return jnp.sin(x), x + jnp.cos(y)
@f.defjvp
def f_jvp(primals, tangents):
self.fail("should not be executed")
with self.assertRaisesRegex(
TypeError,
r"The input arguments to the custom_jvp-decorated function f(.*)\n"
r"missing a required argument: 'y'"
):
f(0.5)
with self.assertRaisesRegex(
TypeError,
r"The input arguments to the custom_jvp-decorated function f(.*)\n"
"The following keyword arguments could not be resolved to positions: z"
):
f(0.5, 0.1, z=1.0)
def test_symbolic_zero_custom_jvp_vmap_doesnt_instantiate(self):
@jax.custom_jvp
def f(x, y):
return y
def f_jvp(primals, tangents):
(_x, y), (_x_dot, y_dot) = primals, tangents
assert type(y_dot) is jax.custom_derivatives.SymbolicZero
return y, y_dot
f.defjvp(f_jvp, symbolic_zeros=True)
def g(x):
return f(x, f(x, 1.))
jax.jvp(jax.vmap(g), (jnp.ones(3),), (jnp.ones(3),)) # don't crash
def test_symbolic_zero_under_vmap_of_jit(self):
# https://github.com/jax-ml/jax/issues/28144
@jax.custom_jvp
def f(x):
return x + 1
@f.defjvp
def f_jvp(x, t):
(x,) = x
(t,) = t
z = jax.custom_derivatives.zero_from_primal(x, symbolic_zeros=True)
return f(x), z
x = jnp.arange(3.0)
jax.jvp(jax.vmap(jax.jit(f)), (x,), (x,)) # doesn't crash
def test_pretty_print(self):
@jax.custom_jvp
def f(x):
return x + 1
@f.defjvp
def f_jvp(primals, tangents):
return f(*primals), tangents[0]
x = jnp.array([4.2], dtype=jnp.float32)
jaxpr = jax.make_jaxpr(f)(x)
actual = jaxpr.pretty_print(use_color=False)
expected = textwrap.dedent(
"""
{ lambda ; a:f32[1]. let
b:f32[1] = custom_jvp_call[
name=f
call_jaxpr={ lambda ; c:f32[1]. let d:f32[1] = add c 1.0:f32[] in (d,) }
jvp=f_jvp
symbolic_zeros=False
] a
in (b,) }
""").strip()
self.assertEqual(actual, expected)
def test_custom_jvp_transpose_vjp3(self):
@jax.custom_jvp
def div(x, y):
return x / y
@div.defjvp
def sin_jvp(primals, tangents):
(x, y), (x_dot, y_dot) = primals, tangents
del y_dot # ignore lol
return div(x, y), div(x_dot, y)
_, f_vjp = api.vjp(lambda x: div(x, 2.), 1.)
ans, = f_vjp(1.)
self.assertAllClose(ans, 1./2, check_dtypes=False)
def test_ensure_compile_time_eval(self):
@jax.custom_jvp
def f(x):
assert x == 0. # concrete!
return x
@f.defjvp
def f_jvp(primals, tangents):
(x,), (_x_dot,) = primals, tangents
assert x == 0. # concrete!
@jax.jit
def g():
with jax.ensure_compile_time_eval():
return f(0.)
g() # don't crash
# TODO(mattjj): do we want to support autodiff here too?
# def h(x):
# @jax.jit
# def hh():
# with jax.ensure_compile_time_eval():
# return f(x)
# return hh()
# jax.grad(h)(0.) # don't crash
class CustomVJPTest(jtu.JaxTestCase):
def test_basic(self):
@jax.custom_vjp
def f(x):
return jnp.sin(x)
def f_fwd(x):
return f(x), jnp.cos(x)
def f_rev(cos_x, g):
return (2 * cos_x * g,)
f.defvjp(f_fwd, f_rev)
x = 3.
self.assertAllClose(f(x), jnp.sin(x))
self.assertAllClose(api.grad(f)(x), 2 * jnp.cos(x))
self.assertAllClose(api.value_and_grad(f)(x),
(jnp.sin(x), 2 * jnp.cos(x)))
def test_invariance(self):
@jax.custom_vjp
def f(x):
return jnp.cos(2 * x) / 2.
def f_fwd(x):
return (f(x), x)
def f_rev(x, g):
return (g * 3,)
f.defvjp(f_fwd, f_rev)
def f2(x):
y, _ = api.value_and_grad(f)(x)
return y
def f3(x):
y, _ = api.value_and_grad(f2)(x)
return y
x = 1.
self.assertAllClose(f(x), f2(x), check_dtypes=False)
self.assertAllClose(f(x), f3(x), check_dtypes=False)
self.assertAllClose(api.grad(f)(x), api.grad(f2)(x),
check_dtypes=False)
self.assertAllClose(api.grad(f)(x), api.grad(f3)(x),
check_dtypes=False)
def test_python_control_flow(self):
@jax.custom_vjp
def f(x):
if x > 0:
return jnp.sin(x)
else:
return jnp.cos(x)
def f_fwd(x):
if x > 0:
return f(x), x
else:
return f(x), x
def f_rev(x, g):
if x > 0:
return (2 * g,)
else:
return (3 * g,)
f.defvjp(f_fwd, f_rev)
x = 2.
self.assertAllClose(f(x), jnp.sin(x))
self.assertAllClose(f(-x), jnp.cos(-x))
self.assertAllClose(api.value_and_grad(f)(x), (jnp.sin(x), 2.),
check_dtypes=False)
self.assertAllClose(api.value_and_grad(f)(-x), (jnp.cos(-x), 3.),
check_dtypes=False)
def test_python_control_flow_bwd(self):
@jax.custom_vjp
def f(x):
return jax.lax.cond(x > 0, jnp.sin, jnp.cos, x) # no primal control flow
def f_fwd(x):
if x > 0:
return jnp.sin(x), x
else:
return jnp.cos(x), x
def f_rev(x, g):
if x > 0:
return (2 * g,)
else:
return (3 * g,)
f.defvjp(f_fwd, f_rev)
x = 2.
self.assertAllClose(f(x), jnp.sin(x))
self.assertAllClose(f(-x), jnp.cos(-x))
self.assertAllClose(api.value_and_grad(f)(x), (jnp.sin(x), 2.),
check_dtypes=False)
self.assertAllClose(api.value_and_grad(f)(-x), (jnp.cos(-x), 3.),
check_dtypes=False)
def test_vmap(self):
@jax.custom_vjp
def f(x):
assert jnp.ndim(x) == 0
return jnp.sin(x)
def f_fwd(x):
assert jnp.ndim(x) == 0
return f(x), jnp.cos(x)
def f_rev(cos_x, g):
return (2 * cos_x * g,)
f.defvjp(f_fwd, f_rev)
x = jnp.arange(3.)
xx = jnp.arange(6.).reshape(2, 3)
# vmap of f
self.assertAllClose(api.vmap(f)(x), jnp.sin(x))
self.assertAllClose(api.vmap(api.vmap(f))(xx), jnp.sin(xx))
# vmap of grad of f
self.assertAllClose(api.vmap(api.grad(f))(x), 2 * jnp.cos(x))
self.assertAllClose(api.vmap(api.value_and_grad(f))(x),
(jnp.sin(x), 2 * jnp.cos(x)))
self.assertAllClose(api.vmap(api.vmap(api.grad(f)))(xx), 2 * jnp.cos(xx))
self.assertAllClose(api.vmap(api.vmap(api.value_and_grad(f)))(xx),
(jnp.sin(xx), 2 * jnp.cos(xx)))
# grad of vmap of f
self.assertAllClose(api.grad(lambda x: api.vmap(f)(x).sum())(x),
2 * jnp.cos(x))
self.assertAllClose(api.grad(lambda x: api.vmap(api.vmap(f))(x).sum())(xx),
2 * jnp.cos(xx))
# vmap of grad of vmap of f
self.assertAllClose(api.vmap(api.grad(lambda x: api.vmap(f)(x).sum()))(xx),
2 * jnp.cos(xx))
def test_jit(self):
@jax.custom_vjp
def f(x):
return jnp.sin(x)
def f_fwd(x):
return f(x), jnp.cos(x)
def f_rev(cos_x, g):
return (2 * cos_x * g,)
f.defvjp(f_fwd, f_rev)
x = 3.
# jit
self.assertAllClose(api.jit(f)(x), jnp.sin(x))
self.assertAllClose(api.jit(api.jit(f))(x), jnp.sin(x))
# jit of grad
self.assertAllClose(api.jit(api.grad(f))(x), 2 * jnp.cos(x),
check_dtypes=False)
# grad of jit
self.assertAllClose(api.grad(api.jit(f))(x), 2 * jnp.cos(x),
check_dtypes=False)
def test_pytrees(self):
@jax.custom_vjp
def f(x):
return {'b': jnp.sin(x['a'])}
def f_fwd(x):
return f(x), {'r': jnp.cos(x['a'])}
def f_bwd(res, g):
cos_x = res['r']
return ({'a': 2 * cos_x * g['b']},)
f.defvjp(f_fwd, f_bwd)
x = {'a': 3.}
self.assertAllClose(f(x)['b'], jnp.sin(x['a']))
self.assertAllClose(api.grad(lambda x: f(x)['b'])(x),
{'a': 2 * jnp.cos(x['a'])})
def test_jvp_error(self):
@jax.custom_vjp
def f(x):
return jnp.sin(x)
def f_fwd(x):
return f(x), jnp.cos(x)
def f_rev(cos_x, g):
return (2 * cos_x * g,)
f.defvjp(f_fwd, f_rev)
self.assertRaisesRegex(
TypeError,
r"can't apply forward-mode autodiff \(jvp\) to a custom_vjp function.",
lambda: api.jvp(f, (3.,), (1.,)))
self.assertRaisesRegex(
TypeError,
r"can't apply forward-mode autodiff \(jvp\) to a custom_vjp function.",
lambda: api.jvp(api.vmap(f), (jnp.arange(3.),), (jnp.ones(3),)))
self.assertRaisesRegex(
TypeError,
r"can't apply forward-mode autodiff \(jvp\) to a custom_vjp function.",
lambda: api.jvp(jit(f), (3.,), (1.,)))
def test_kwargs(self):
# from https://github.com/jax-ml/jax/issues/1938
@jax.custom_vjp
def my_fun(x, y, c=1.):
return c * (x + y)
my_fun.defvjp(lambda x, y, c=1.: (my_fun(c, y, c), None),
lambda _, g: (g, g, g))
f = lambda x, y: jnp.square(my_fun(x, y, c=2.)).sum()
f(10., 5.) # doesn't crash
api.grad(f)(10., 5.) # doesn't crash
def test_initial_style(self):
@jax.custom_vjp
def f(x):
return jnp.sin(x)
def f_fwd(x):
return f(x), jnp.cos(x)
def f_rev(cos_x, g):
return (2 * cos_x * g,)
f.defvjp(f_fwd, f_rev)
def foo(x):
out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)
return out
ans = api.grad(foo)(3.)
expected = 2. * jnp.cos(3.)
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.grad(api.grad(foo))(3.)
expected = -2. * jnp.sin(3.)
self.assertAllClose(ans, expected)
def test_initial_style_vmap(self):
@jax.custom_vjp
def f(x):
assert jnp.ndim(x) == 0
return 3 * x
def f_fwd(x):
return f(x), jnp.cos(x)
def f_rev(cos_x, g):
return (2 * cos_x * g,)
f.defvjp(f_fwd, f_rev)
def foo(x):
out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)
return out
ans = api.vmap(foo)(jnp.arange(3.))
expected = 3. * jnp.arange(3.)
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.grad(lambda x: api.vmap(foo)(x).sum())(jnp.arange(3.))
expected = 2. * jnp.cos(jnp.arange(3.))
self.assertAllClose(ans, expected, check_dtypes=False)
def test_nondiff_argnums(self):
@partial(jax.custom_vjp, nondiff_argnums=(0,))
def app(f, x):
return f(x)
def app_fwd(f, x):
return app(f, x), jnp.cos(x)
def app_rev(f, cos_x, g):
return (cos_x * g,)
app.defvjp(app_fwd, app_rev)
ans = app(lambda x: 2 * x, 1)
expected = 2
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.value_and_grad(lambda x: app(lambda y: 2 * y, x))(1.)
expected = (2., jnp.cos(1.))
self.assertAllClose(ans, expected, check_dtypes=False)
def test_nondiff_argnames(self):
@partial(jax.custom_vjp, nondiff_argnames=('f',))
def app(f, x):
return f(x)
def app_fwd(f, x):
return app(f, x), jnp.cos(x)
def app_rev(f, cos_x, g):
return (cos_x * g,)
app.defvjp(app_fwd, app_rev)
ans = app(lambda x: 2 * x, 1)
expected = 2
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.value_and_grad(lambda x: app(lambda y: 2 * y, x))(1.)
expected = (2., jnp.cos(1.))
self.assertAllClose(ans, expected, check_dtypes=False)
def test_nondiff_argnums_argnames(self):
@partial(jax.custom_vjp, nondiff_argnums=(0,), nondiff_argnames=('g',))
def app(f, g, x):
return f(x) + g(x)
def app_fwd(f, g, x):
return app(f, g, x), jnp.cos(x)
def app_rev(f, g, cos_x, v):
return (cos_x * v,)
app.defvjp(app_fwd, app_rev)
f = lambda x: 2 * x
g = lambda x: 2 * x
ans = app(f, g, 1)
expected = 4
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.value_and_grad(lambda x: app(f, g, x))(1.)
expected = (4., jnp.cos(1.))
self.assertAllClose(ans, expected, check_dtypes=False)
def test_closed_over_jit_tracer(self):
# See the comment in CustomJVPTest.test_nondiff_arg_jit_tracer.
raise unittest.SkipTest("behavior no longer supported")
# This test is similar to test_nondiff_arg_tracer except it uses lexical
# closure rather than the nondiff_argnums mechanism. We decided to disallow
# tracers in nondiff_argnums to greatly simplify bookkeeping while still
# supporting the cases for which it is necessary.
def outer(x):
@jax.custom_vjp
def f(y):
return x * y
def f_fwd(y):
return f(y), jnp.cos(y)
def f_rev(cos_y, g):
return (cos_y * g,)
f.defvjp(f_fwd, f_rev)
return f
@jit
def g(x, y):
return outer(x)(y)
ans = g(2, 3.)
expected = 6.
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.grad(g, 1)(2., 3.)
expected = jnp.cos(3.)
self.assertAllClose(ans, expected, check_dtypes=False)
def test_closed_over_vmap_tracer(self):
def outer(x):
@jax.custom_vjp
def f(y):
return x * y
def f_fwd(y):
return f(y), jnp.cos(y)
def f_rev(cos_y, g):
return (cos_y * g,)
f.defvjp(f_fwd, f_rev)
return f
@api.vmap
def g(x):
return outer(x)(3.)
ans = g(np.arange(3.))
expected = np.arange(3.) * 3
self.assertAllClose(ans, expected, check_dtypes=False)
def test_closed_over_tracer3(self):
def outer(x):
@jax.custom_vjp
def f(y):
return x * y
def f_fwd(y):
return f(y), (x, jnp.cos(y))
def f_rev(res, g):
x, cos_y = res
return (cos_y * g * x,)
f.defvjp(f_fwd, f_rev)
return api.grad(f)
@api.vmap
def g(x):
return outer(x)(3.)
ans = g(np.arange(3.))
expected = np.cos(3.) * np.arange(3.)
self.assertAllClose(ans, expected, check_dtypes=False)
def test_nondiff_arg_tracer_error(self):
# This is similar to the old (now skipped) test_nondiff_arg_tracer, except
# we're testing for the error message that usage pattern now raises.
@partial(jax.custom_vjp, nondiff_argnums=(0,))
def f(x, y):
return x * y
def f_fwd(x, y):
return f(x, y), jnp.cos(y)
def f_rev(x, cos_y, g):
return (cos_y * g,)
f.defvjp(f_fwd, f_rev)
@jit
def g(x, y):
return f(x, y)
with self.assertRaisesRegex(UnexpectedTracerError, "custom_vjp"):
_ = g(2, 3.)
with self.assertRaisesRegex(UnexpectedTracerError, "custom_vjp"):
_ = api.grad(g, 1)(2., 3.)
def test_vmap_axes(self):
raise unittest.SkipTest("TODO") # TODO(mattjj): write test
def test_pmap(self):
raise unittest.SkipTest("TODO") # TODO(mattjj): write test
def test_missing_vjp_rule_error(self):
@jax.custom_vjp
def foo(x):
return x ** 2
self.assertRaisesRegex(
AttributeError,
r"No VJP defined for custom_vjp function foo using defvjp.",
lambda: foo(2))
self.assertRaisesRegex(
AttributeError,
r"No VJP defined for custom_vjp function foo using defvjp.",
lambda: api.grad(foo)(2.))
def test_vjp_rule_inconsistent_pytree_structures_error(self):
@jax.custom_vjp
def f(x):
return x
def foo_fwd(x):
return x, None
def foo_bwd(_, g):
return (g, g)
f.defvjp(foo_fwd, foo_bwd)
f(2) # doesn't crash
with self.assertRaisesRegex(Exception, "Custom VJP bwd rule .*must produce"):
api.grad(f)(2.)
def test_vjp_bwd_returns_non_tuple_error(self):
@jax.custom_vjp
def f(x):
return x
def foo_fwd(x):
return x, None
def foo_bwd(_, g):
return 2. * g # Should be a tuple
f.defvjp(foo_fwd, foo_bwd)
with self.assertRaisesRegex(TypeError, "Custom VJP bwd rule .* must produce a tuple"):
api.grad(f)(3.)
def test_fwd_rule_primal_out_type_doesnt_match_primal_error_message(self):
# https://github.com/lucidrains/flash-attention-jax/issues/7
def scan_apply(f, x):
y, _ = jax.lax.scan(lambda x, _: (f(x), None), x, None, length=1)
return y
@jax.custom_vjp
def f(x):
return x
def f_fwd(x):
return (x, x), None
def f_bwd(_, y_bar):
return (y_bar,)
f.defvjp(f_fwd, f_bwd)
self.assertRaisesRegex(
TypeError,
"Custom VJP fwd rule f_fwd for function f must produce a pair ",
lambda: jax.grad(lambda x: scan_apply(f, x))(jnp.float32(1.)))
def f_fwd2(x):
return jnp.zeros((3, *x.shape), x.dtype), None
def f_bwd2(_, y_bar):
return (y_bar,)
f.defvjp(f_fwd2, f_bwd2)
self.assertRaisesRegex(
TypeError,
re.escape(
"Custom VJP fwd rule f_fwd2 for function f must produce a pair "
"(list or tuple of length two) where the first element represents "
"the primal output (equal to the output of the "
"custom_vjp-decorated function f) and the second element "
"represents residuals (i.e. values stored from the forward "
"pass for use on the backward pass), but instead the fwd rule "
"output's first element had shapes/dtypes of:\n"
" float32[3]\n"
"while the custom_vjp-decorated function f had output "
"shapes/dtypes of:\n"
" float32[]"
),
lambda: jax.grad(lambda x: scan_apply(f, x))(jnp.float32(1.)))
def test_issue2511(self):
arr = jnp.ones((5, 2, 2))
foo = lambda x: api.vmap(jnp.linalg.det, (0,))(x)
api.jit(foo)(arr) # doesn't crash
def test_lowering_out_of_traces(self):
# https://github.com/jax-ml/jax/issues/2578
class F(collections.namedtuple("F", ["a"])):
def __call__(self, x):
return jax.nn.relu(self.a) * x
@jax.jit
def g(f, x):
return f(x)
jax.grad(g, argnums=(1,))(F(2.0), 0.) # doesn't crash
def test_clip_gradient(self):
# https://github.com/jax-ml/jax/issues/2784
@jax.custom_vjp
def _clip_gradient(lo, hi, x):
return x # identity function when not differentiating
def clip_gradient_fwd(lo, hi, x):
return x, (lo, hi,)
def clip_gradient_bwd(res, g):
lo, hi = res
return (None, None, jnp.clip(g, lo, hi),)
_clip_gradient.defvjp(clip_gradient_fwd, clip_gradient_bwd)
def clip_gradient(x):
lo = -0.1
hi = x + 0.1
return _clip_gradient(lo, hi, x)
g = jax.grad(clip_gradient)(0.1) # doesn't crash
self.assertAllClose(g, jnp.array(0.2))
def test_nestable_vjp(self):
# Verify that https://github.com/jax-ml/jax/issues/3667 is resolved.
def f(x):
return x ** 2
@jax.custom_vjp
def g(x):
return f(x)
def g_fwd(x):
y, f_vjp = api.vjp(f, x)
return y, f_vjp
def g_bwd(f_vjp, y_bar):
return f_vjp(y_bar)
g.defvjp(g_fwd, g_bwd)
# Check that VJP can be nested in simple situations. For this to pass,
# vjp has to return a PyTree.
_, g_vjp = api.vjp(g, 1.0)
y, = g_vjp(1.0)
self.assertAllClose(y, jnp.array(2.0))
# Check that VJP can be nested in complex situations. For this to pass,
# vjp can't treat the closed-over tracer x as a static argument.
@jit
def z(x):
_, g_vjp = api.vjp(g, x)
return g_vjp
y, = z(1.0)(3.0)
self.assertAllClose(y, jnp.array(6.0))
def test_initial_style_vmap_2(self):
# https://github.com/jax-ml/jax/issues/4173
x = jnp.ones((10, 3))
# Create the custom function
@jax.custom_vjp
def custom_fun(x):
return x.sum()
def forward(x):
return x.sum(), (jnp.ones_like(x),)
def backward(res, g):
return g * res[0],
custom_fun.defvjp(forward, backward)
def train_fun(x):
def summed_fun(x):
return api.vmap(custom_fun)(x).sum()
return api.grad(summed_fun)(x)
def scan_body(carry, inputs):
x = carry
return carry, train_fun(x)
scan_range = jnp.arange(4)
lax.scan(scan_body, x, scan_range) # don't crash
def test_initial_style_vmap_3(self):
# This is like test_initial_style_vmap except the primal function closes
# over an array constant.
y = jnp.arange(1., 4.)
@jax.custom_vjp
def f(x):
assert jnp.ndim(x) == 0
return 3 * x * jnp.sum(y)
def f_fwd(x):
return f(x), jnp.cos(x)
def f_rev(cos_x, g):
return (2 * cos_x * g,)
f.defvjp(f_fwd, f_rev)
def foo(x):
out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)
return out
ans = api.vmap(foo)(jnp.arange(3.))
expected = 3. * jnp.arange(3.) * 6
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.grad(lambda x: api.vmap(foo)(x).sum())(jnp.arange(3.))
expected = 2. * jnp.cos(jnp.arange(3.))
self.assertAllClose(ans, expected, check_dtypes=False)
def test_initial_style_vmap_with_collective(self):
@jax.custom_vjp
def f(x):
return lax.psum(x, 'foo')
def f_fwd(x):
return lax.psum(x, 'foo'), None
def f_bwd(res, dx):
return dx
f.defvjp(f_fwd, f_bwd)
def g(x):
jaxpr = api.make_jaxpr(f)(x)
return core.eval_jaxpr(jaxpr.jaxpr, [], x)[0]
out = api.vmap(lambda _, x: g(x), axis_name='foo', in_axes=(0, None),
out_axes=None)(jnp.arange(4.), 2.)
self.assertAllClose(out, 8.)
def test_bwd_closes_over_tracer(self):
def f(y):
@jax.custom_vjp
def f(x):
return 2. * jnp.sin(x)
def fwd(x):
return f(x), ()
def bwd(_, g):
return (2. * jnp.cos(y) * g,) # capture!
f.defvjp(fwd, bwd)
return jax.grad(f)(1.)
ans = jax.jit(f)(2.)
self.assertAllClose(ans, 2. * jnp.cos(2.))
ans = jax.vmap(f)(jnp.arange(3.))
self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))
ans = jax.jit(jax.vmap(f))(jnp.arange(3.))
self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))
ans = jax.vmap(jax.jit(f))(jnp.arange(3.))
self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))
ans = jax.grad(f)(4.)
self.assertAllClose(ans, -2. * jnp.sin(4.))
def test_fwd_closes_over_tracer(self):
def f(y):
@jax.custom_vjp
def f(x):
return 2. * jnp.sin(x)
def fwd(x):
return f(x), y
def bwd(y, g):
return (2. * jnp.cos(y) * g,) # capture!
f.defvjp(fwd, bwd)
return jax.grad(f)(1.)
ans = jax.jit(f)(2.)
self.assertAllClose(ans, 2. * jnp.cos(2.))
ans = jax.vmap(f)(jnp.arange(3.))
self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))
ans = jax.jit(jax.vmap(f))(jnp.arange(3.))
self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))
ans = jax.vmap(jax.jit(f))(jnp.arange(3.))
self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))
ans = jax.grad(f)(4.)
self.assertAllClose(ans, -2. * jnp.sin(4.))
def test_float0(self):
@jax.custom_vjp
def f(x, _):
return x
def f_fwd(x, _):
# we need a defined (non-float0) tangent to trigger the rule
return x, (2., 1)
def f_rev(*_):
return (2., 1)
f.defvjp(f_fwd, f_rev)
x = 2.
y = 3
self.assertEqual(api.grad(f, allow_int=True, argnums=(0, 1))(x, y),
(2., np.zeros(shape=(), dtype=float0)))
def test_float0_initial_style(self):
@jax.custom_vjp
def f(x):
return x
def f_fwd(x):
return x, (2., x)
def f_rev(*_):
return ((2., jnp.zeros(shape=(), dtype=float0)),)
f.defvjp(f_fwd, f_rev)
def foo(x, y):
out, _ = lax.scan(lambda c, _: (f(c), None), (x, y), None, length=1)
return out[0]
x = 2.
y = 3
self.assertEqual(api.grad(foo, allow_int=True, argnums=(0, 1))(x, y),
(2., np.zeros(shape=(), dtype=float0)))
def test_remat(self):
@jax.custom_vjp
def f(x):
return jnp.sin(x)
def f_fwd(x):
return f(x), jnp.cos(x)
def f_rev(cos_x, g):
return (2 * cos_x * g,)
f.defvjp(f_fwd, f_rev)
@jax.remat
def g(x):
return f(f(x))
ans = g(2.)
expected = np.sin(np.sin(2.))
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.grad(g)(2.)
expected = 4. * api.grad(lambda x: jnp.sin(jnp.sin(x)))(2.)
self.assertAllClose(ans, expected, check_dtypes=False)
def test_remat_higher_order(self):
@jax.custom_vjp
def f(x):
return jnp.sin(x)
def f_fwd(x):
return f(x), jnp.cos(x)
def f_rev(cos_x, g):
return (2 * cos_x * g,)
f.defvjp(f_fwd, f_rev)
def g(x):
return f(f(x))
ans = api.grad(api.grad(jax.remat(g)))(2.)
expected = api.grad(api.grad(g))(2.)
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.grad(jax.remat(api.grad(g)))(2.)
expected = api.grad(api.grad(g))(2.)
self.assertAllClose(ans, expected, check_dtypes=False)
ans = api.grad(api.grad(api.grad(jax.remat(g))))(2.)
expected = api.grad(api.grad(api.grad(g)))(2.)
self.assertAllClose(ans, expected, check_dtypes=False)
def test_bwd_nones(self):
@jax.custom_vjp
def f(x, y):
return x * jnp.sin(y)
def f_fwd(x, y):
return f(x, y), jnp.cos(y)
def f_rev(cos, g):
return (None, 2 * cos * g)
f.defvjp(f_fwd, f_rev)
ans = api.grad(lambda x: f(x, x))(3.)
expected = 2 * jnp.cos(3.)
self.assertAllClose(ans, expected, check_dtypes=False)
def test_bwd_nones_vmap(self):
@jax.custom_vjp
def f(x, y):
return x * jnp.sin(y)
def f_fwd(x, y):
return f(x, y), jnp.cos(y)
def f_rev(cos, g):
return (None, 2 * cos * g)
f.defvjp(f_fwd, f_rev)
ans = api.grad(lambda x: api.vmap(f)(x, x).sum())(jnp.arange(3.))
expected = 2 * jnp.cos(jnp.arange(3.))
self.assertAllClose(ans, expected, check_dtypes=False)
def test_bwd_nones_pytree(self):
@jax.custom_vjp
def f(xs, y):
x1, x2 = xs
return x1 * x2 * jnp.sin(y)
def f_fwd(xs, y):
return f(xs, y), jnp.cos(y)
def f_rev(cos, g):
return (None, 2 * cos * g)
f.defvjp(f_fwd, f_rev)
ans = api.grad(lambda x: f((x, x), x))(3.)
expected = 2 * jnp.cos(3.)
self.assertAllClose(ans, expected, check_dtypes=False)
def test_custom_vjp_closure_4521(self):
# https://github.com/jax-ml/jax/issues/4521
@jax.custom_vjp
def g(x, y):
return None
def g_fwd(x, y):
return None, y
def g_bwd(residuals, z_bar):
assert False
g.defvjp(g_fwd, g_bwd)
def f(xs, y):
v_g = api.vmap(g, in_axes=(0, None), out_axes=None)
v_g(xs, y)
def scan_body(xs, _):
y = jnp.zeros(1)
_, vjp_f = api.vjp(f, xs, y)
vjp_f(None)
return xs, None
lax.scan(scan_body, jnp.ones(5), None, 100) # doesn't crash
def test_float0_bwd_none(self):
@jax.custom_vjp
def f(i, x):
return jnp.sin(x)
def f_fwd(i, x):
return f(i, x), jnp.cos(x)
def f_rev(cos_x, g):
return (None, 2 * cos_x * g)
f.defvjp(f_fwd, f_rev)
ans = api.grad(f, 1)(jnp.array([1, 2]), 3.) # doesn't crash
expected = 2 * jnp.cos(3.)
self.assertAllClose(ans, expected, check_dtypes=False)
def test_custom_gradient(self):
@jax.custom_gradient
def f(x):
return x ** 2, lambda g: (g * x,)
self.assertAllClose(f(3.), 9., check_dtypes=False)
self.assertAllClose(api.grad(f)(3.), 3., check_dtypes=False)
self.assertAllClose(api.grad(api.grad(f))(3.), 1., check_dtypes=False)
def test_custom_gradient_2(self):
@jax.custom_gradient
def f(x, y):
return x * y, lambda g: (y, x)
self.assertAllClose(f(3., 4.), 12., check_dtypes=False)
self.assertAllClose(api.grad(f, argnums=(0, 1))(3., 4.), (4., 3.),
check_dtypes=False)
def test_custom_gradient_3(self):
@jax.custom_gradient
def f(x):
vjp = lambda g: (jnp.cos(x) * jnp.arange(3., 6.),)
return jnp.sum(jnp.sin(x)), vjp
self.assertAllClose(f(jnp.arange(3)), jnp.sum(jnp.sin(jnp.arange(3.))),
check_dtypes=False)
self.assertAllClose(
api.grad(f)(jnp.arange(3.)),
api.grad(lambda x: jnp.sum(jnp.sin(x)))(jnp.arange(3.)) * jnp.arange(3., 6.),
check_dtypes=False)
def test_custom_gradient_can_return_singleton_value_in_vjp(self):
@jax.custom_gradient
def f(x):
return x ** 2, lambda g: g * x
self.assertAllClose(f(3.), 9., check_dtypes=False)
self.assertAllClose(api.grad(f)(3.), 3., check_dtypes=False)
self.assertAllClose(api.grad(api.grad(f))(3.), 1., check_dtypes=False)
def test_closure_convert(self):
def cos_after(fn, x):
converted_fn, aux_args = jax.closure_convert(fn, x)
self.assertLessEqual(len(aux_args), 1)
return _cos_after(converted_fn, x, *aux_args)
@partial(jax.custom_vjp, nondiff_argnums=(0,))
def _cos_after(fn, x, *args):
return jnp.cos(fn(x, *args))
def fwd(fn, x, *args):
y = _cos_after(fn, x, *args)
return y, (x, args)
def rev(fn, res, g):
x, args = res
x_bar = 17. * x
args_bars = [42. * a for a in args]
return (x_bar, *args_bars)
_cos_after.defvjp(fwd, rev)
def dist(c, x):
return jnp.sum((x - c) ** 2.)
def solve(c, x):
def closure(x):
return dist(c, x)
return cos_after(closure, x)
c, x = 2. * jnp.ones(2), jnp.ones(2)
expected = jnp.cos(dist(c, x))
self.assertAllClose(solve(c, x), expected, check_dtypes=False)
g_c, g_x = api.grad(solve, argnums=(0, 1))(c, x)
self.assertAllClose(g_c, 42. * c, check_dtypes=False)
self.assertAllClose(g_x, 17. * x, check_dtypes=False)
def test_closure_convert_mixed_consts(self):
# Like test_closure_convert, but close over values that
# participate in AD as well as values that do not.
# See https://github.com/jax-ml/jax/issues/6415
def cos_after(fn, x):
converted_fn, aux_args = jax.closure_convert(fn, x)
self.assertLessEqual(len(aux_args), 1)
return _cos_after(converted_fn, x, *aux_args)
@partial(jax.custom_vjp, nondiff_argnums=(0,))
def _cos_after(fn, x, *args):
return jnp.cos(fn(x, *args))
def fwd(fn, x, *args):
y = _cos_after(fn, x, *args)
return y, (x, args)
def rev(fn, res, g):
x, args = res
x_bar = 17. * x
args_bars = [42. * a for a in args]
return (x_bar, *args_bars)
_cos_after.defvjp(fwd, rev)
def dist(c, s, x):
return jnp.sum(s * (x - c) ** 2.)
def solve(c, s, x):
def closure(x):
return dist(c, s, x)
return cos_after(closure, x)
c, s, x = 2. * jnp.ones(2), 3. * jnp.ones(2), jnp.ones(2)
expected = jnp.cos(dist(c, s, x))
self.assertAllClose(solve(c, s, x), expected, check_dtypes=False)
g_c, g_x = api.grad(solve, argnums=(0, 2))(c, s, x)
self.assertAllClose(g_c, 42. * c, check_dtypes=False)
self.assertAllClose(g_x, 17. * x, check_dtypes=False)
def test_closure_convert_pytree_mismatch(self):
# See https://github.com/jax-ml/jax/issues/23588
def f(x, z):
return z * x
x, z = 2.0, 3.0
_, vjp = api.vjp(f, x, z)
vjp_pure, vjp_aux_args = jax.closure_convert(vjp, x)
vjp_pure(x, *vjp_aux_args)
with self.assertRaisesRegex(
TypeError, "The inputs to the closure produced by closure_convert"):
vjp_pure(x, vjp_aux_args)
def test_float0_cotangents_automatically_handled(self):
@jax.custom_vjp
def f(x, y):
return x
def f_fwd(x, y):
return x, None
def f_bwd(_, zbar):
return (0., 1)
f.defvjp(f_fwd, f_bwd)
jax.jit(lambda x: jax.vjp(f, 0., x)[1](1.))(1) # doesn't crash
def test_custom_vjp_scan_batching_edge_case(self):
# https://github.com/jax-ml/jax/issues/5832
@jax.custom_vjp
def mul(x, coeff): return x * coeff
def mul_fwd(x, coeff): return mul(x, coeff), (x, coeff)
def mul_bwd(res, g):
x, coeff = res
g_x = g * coeff
g_coeff = (x * g).sum()
return g_x, g_coeff
mul.defvjp(mul_fwd, mul_bwd)
def scan_over_mul(x, coeff):
def f_(x, t):
return mul(x, coeff), None
y, _ = jax.lax.scan(f_, x, jnp.arange(3))
return y
key = jax.random.key(0)
key1, key2 = jax.random.split(key, 2)
x_batch = jax.random.normal(key1, (3, 2))
covector_batch = jax.random.normal(key2, (3, 2))
coeff = jnp.array(1., dtype=x_batch.dtype)
batched_scan_over_mul = jax.vmap(scan_over_mul, in_axes=(0, None), out_axes=0)
res, vjp_fun = jax.vjp(batched_scan_over_mul, x_batch, coeff)
vjp_fun(covector_batch) # doesn't crash
jtu.check_grads(batched_scan_over_mul, (x_batch, coeff), order=2,
modes=['rev'])
def test_closure_with_vmap2(self):
# https://github.com/jax-ml/jax/issues/8783
def h(z):
def f(x):
@jax.custom_vjp
def g(y):
return x * y
def g_fwd(y):
return x * y, (x, x * y, y)
def g_rev(res, w_bar):
x, *_ = res
return (x * w_bar,)
g.defvjp(g_fwd, g_rev)
return g(z)
return jax.vmap(f)(jnp.arange(3., dtype='float32')).sum()
jtu.check_grads(h, (jnp.float32(3.14),), order=1, modes=['rev'])
def test_pytrees_not_required_to_contain_nones(self):
class A(list):
pass
def unflatten(_, children):
assert children[0] is not None
return A(children)
tree_util.register_pytree_node(A, lambda x: (x, None), unflatten)
@jax.custom_vjp
def f(x):
return x[0]
def f_fwd(x):
return x[0], None
def f_bwd(_, g):
return A([g]),
f.defvjp(f_fwd, f_bwd)
jax.grad(f)(A([1.])) # doesn't crash
def test_vmap_vjp_called_twice(self):
# https://github.com/jax-ml/jax/pull/14728
@jax.custom_vjp
def f(x):
return x
f.defvjp(lambda x: (x, None), lambda _, y_bar: (y_bar,))
_, f_vjp = jax.vjp(jax.vmap(f), jnp.array([3.]))
f_vjp(jnp.array([3.]))
f_vjp(jnp.array([3.])) # doesn't crash
def test_symbolic_zero_custom_vjp_basic(self):
ZERO = jax.custom_derivatives.SymbolicZero
@jax.custom_vjp
def f(x, y, z):
return x, x
def fwd(x, y, z):
self.assertIsInstance(x, jax.custom_derivatives.CustomVJPPrimal)
self.assertIsInstance(y, jax.custom_derivatives.CustomVJPPrimal)
self.assertIsInstance(z, jax.custom_derivatives.CustomVJPPrimal)
self.assertTrue(x.perturbed)
self.assertFalse(y.perturbed)
self.assertFalse(z.perturbed)
return (x.value, x.value), None
def fwd_all(x, y, z):
self.assertIsInstance(x, jax.custom_derivatives.CustomVJPPrimal)
self.assertIsInstance(y, jax.custom_derivatives.CustomVJPPrimal)
self.assertIsInstance(z, jax.custom_derivatives.CustomVJPPrimal)
self.assertTrue(x.perturbed)
self.assertTrue(y.perturbed)
self.assertTrue(z.perturbed)
return (x.value, x.value), None
def bwd_all(_, g):
x1, x2 = g
self.assertFalse(type(x1) is ZERO)
self.assertFalse(type(x2) is ZERO)
return x1, x1, x2
def bwd_fst(_, g):
x1, x2 = g
self.assertFalse(type(x1) is ZERO)
self.assertIs(type(x2), ZERO)
return x1, x1, x2
def bwd_snd(_, g):
x1, x2 = g
self.assertIs(type(x1), ZERO)
self.assertFalse(type(x2) is ZERO)
return x1, x1, x2
x, y, z = 4., 5., 6.
i = np.array(7, np.int32)
zero = np.array(0.)
f.defvjp(fwd, bwd_all, symbolic_zeros=True)
h = jax.jit(f)
jax.jacrev(h)(x, y, z)
jax.jacrev(lambda x: h(x, y, z))(x)
jax.jacrev(h, argnums=(0, 1, 2), allow_int=True)(x, i, i)
f.defvjp(fwd_all, bwd_fst, symbolic_zeros=True)
fst_f = lambda *xs: f(*xs)[0]
_, vjp = jax.vjp(fst_f, x, y, z)
_, _, gz = vjp(x)
self.assertArraysAllClose(gz, zero)
f.defvjp(fwd_all, bwd_snd, symbolic_zeros=True)
snd_f = lambda *xs: f(*xs)[1]
_, vjp = jax.vjp(snd_f, x, y, z)
gx, gy, _ = vjp(x)
self.assertArraysAllClose(gx, zero)
self.assertArraysAllClose(gy, zero)
f.defvjp(fwd, bwd_snd, symbolic_zeros=True)
_, vjp = jax.vjp(lambda x: snd_f(x, y, z), x)
gx, = vjp(x)
self.assertArraysAllClose(gx, zero)
def test_symbolic_zero_custom_vjp_bwd_shape_error(self):
@jax.custom_vjp
def f(x, y, z):
return x, y, z
def fwd(x, y, z):
return f(x.value, y.value, z.value), None
def bwd(_, gs):
x_bar, y_bar, z_bar = gs
return y_bar, x_bar, z_bar # swapped!
f.defvjp(fwd, bwd, symbolic_zeros=True)
with self.assertRaisesRegex(
ValueError,
r'Consider just returning a None here'):
jax.grad(lambda x, y, z: f(x, y, z)[2].sum())(
jnp.ones(1), jnp.ones(2), jnp.ones(3))
@parameterized.named_parameters(
('jit_vmap', True, True),
('jit', True, False),
('vmap', False, True),
('', False, False),
)
def test_symbolic_zero_custom_vjp(self, maybe_jit, maybe_vmap):
# below:
# * static_scalar will be static in and out
# * static_array will be static in, but dynamic out
# * dyn_scalar and dyn_array will be dynamic in and out
ZERO = jax.custom_derivatives.SymbolicZero
def f(static_scalar, static_array, dyn_scalar, dyn_array):
out1 = static_scalar + dyn_scalar
out2 = static_array + dyn_array
return static_scalar, static_array, out1, out2
def _pack(x):
return lax.broadcast(x, (1,))
def _unpack(x):
(x,) = x
return x
def _vmap(fun):
def _fun(*args):
args = jax.tree.map(_pack, args)
out = jax.vmap(fun)(*args)
out = jax.tree.map(_unpack, out)
return out
return _fun
f = jax.custom_vjp(f)
def fwd(*args):
xs, pert = [x.value for x in args], [x.perturbed for x in args]
self.assertFalse(pert[0])
self.assertFalse(pert[1])
self.assertTrue(pert[2])
self.assertTrue(pert[3])
return f(*xs), xs
def bwd(res, g):
static_scalar, *_ = res
t_static, t_static_arr, t_dyn_scalar, t_dyn_array = g
self.assertIs(type(t_static), ZERO)
self.assertFalse(type(t_static_arr) is ZERO)
self.assertFalse(type(t_dyn_scalar) is ZERO)
self.assertFalse(type(t_dyn_array) is ZERO)
self.assertEqual(t_static.shape, ())
self.assertEqual(t_static_arr.shape, (2,))
return (static_scalar + 90,
t_static_arr + 91,
t_dyn_scalar + 92,
t_dyn_array + 93)
f.defvjp(fwd, bwd, symbolic_zeros=True)
def g(dyn_scalar, dyn_array):
if maybe_vmap:
f_ = _vmap(f)
else:
f_ = f
outs = f_(1., jnp.array([2., 3.]), dyn_scalar, dyn_array)
return outs[1:]
def run(primal_ins, cotangent_outs):
primal_outs, vjp = jax.vjp(g, *primal_ins)
cotangent_ins = vjp(cotangent_outs)
return primal_outs, cotangent_ins
if maybe_jit:
run = jax.jit(run)
scalar_type = jax.Array if maybe_jit or maybe_vmap else float
primal_ins = (4., jnp.array([5., 6.]))
cotangent_outs = (jnp.array([10., 11.]), 7., jnp.array([8., 9.]))
primal_outs, cotangent_ins = run(primal_ins, cotangent_outs)
primal_out1, primal_out2, primal_out3 = primal_outs
self.assertIsInstance(primal_out1, jax.Array)
self.assertAllClose(primal_out1, jnp.array([2., 3.]))
if self.__class__ is CustomVJPTest:
# TODO(mattjj): we don't yet support this behavior for CustomVJPTraced
self.assertIsInstance(primal_out2, scalar_type)
self.assertAllClose(primal_out2, 5.)
self.assertIsInstance(primal_out3, jax.Array)
self.assertAllClose(primal_out3, jnp.array([7., 9.]))
ct_in1, ct_in2 = cotangent_ins
self.assertIsInstance(ct_in1, scalar_type)
self.assertAllClose(ct_in1, 99.)
self.assertIsInstance(ct_in2, jax.Array)
self.assertArraysAllClose(ct_in2, jnp.array([101., 102.]))
def test_symbolic_zero_custom_vjp_vmap_output(self):
@jax.custom_vjp
def f(x, y):
return x, y
def fwd(x, y):
self.assertTrue(x.perturbed)
self.assertFalse(y.perturbed)
return f(x.value, y.value), None
def bwd(_, g):
_, ct_y = g
self.assertIs(type(ct_y), jax.custom_derivatives.SymbolicZero)
return g
f.defvjp(fwd, bwd, symbolic_zeros=True)
jax.grad(lambda x, y: jax.vmap(f)(x, y)[0].sum())(jnp.ones(3), jnp.ones(3))
def test_symbolic_zero_custom_vjp_custom_pytree(self):
tree_values = jax.custom_derivatives.custom_vjp_primal_tree_values
@tree_util.register_pytree_node_class
class Box:
def __init__(self_, strict, val):
if strict:
# make sure we aren't getting special arguments that should only
# come up when symbolic_zeros is True
self.assertFalse(hasattr(val, 'perturbed'))
self_.strict = strict
self_.x = val
def tree_flatten(self_):
return [self_.x], self_.strict
@classmethod
def tree_unflatten(cls, strict, xs):
x, = xs
return cls(strict, x)
x, y = Box(False, jnp.array(72.)), jnp.array(73.)
@jax.custom_vjp
def f(box, y):
return box.x * y
def fwd0(box, y):
self.assertTrue(box.x.perturbed)
self.assertFalse(y.perturbed)
box, y = map(tree_values, [box, y])
return f(box, y), (box, y)
def bwd0(res, g):
box, y = res
return y * g, box.x * g
def fwd1(box, y):
self.assertFalse(box.x.perturbed)
self.assertTrue(y.perturbed)
box, y = map(tree_values, [box, y])
return f(box, y), (box, y)
def bwd1(res, g):
box, y = res
return y * g, box.x * g
f.defvjp(fwd0, bwd0, symbolic_zeros=True)
jax.grad(f, argnums=0)(x, y)
f.defvjp(fwd1, bwd1, symbolic_zeros=True)
jax.grad(f, argnums=1)(x, y)
def fwd_strict(box, y):
return f(box, y), (box, y)
def bwd_strict(res, g):
box, y = res
return y * g, box.x * g
f.defvjp(fwd_strict, bwd_strict)
jax.grad(f)(x, y)
def test_symbolic_zeros_memoization_caching(self):
# Tests multiple zero patterns for partial_eval._memoize, and also tests
# that we're okay with stores being occupied with equal values.
@jax.custom_vjp
def f(x, y):
return x * y
def f_fwd(x, y):
return x.value, None
def f_bwd(_, z_bar):
return z_bar, None
f.defvjp(f_fwd, f_bwd, symbolic_zeros=True)
f_ = core.jaxpr_as_fun(jax.make_jaxpr(f)(2., 3.))
_ = jax.vjp(f_, 2., 3.)
_ = jax.vjp(lambda x: f_(x, 3.), 2.) # don't crash!
def test_run_rules_more_than_once(self):
# https://github.com/jax-ml/jax/issues/16614
@jax.custom_vjp
def f(x, y):
return x + y
def f_fwd(x, y):
if y.perturbed:
res = None
else:
res = []
return x.value + y.value, res
def f_bwd(res, ct):
return ct, ct
f.defvjp(f_fwd, f_bwd, symbolic_zeros=True)
def body(x_y, _):
x, y = x_y
return (f(x, y), x), None
@jax.grad
def g(x):
(out, _), _ = lax.scan(body, (x, 1.), xs=None, length=2)
return out
g(1.) # doesn't crash
def test_symbolic_zeros_remat(self):
@jax.custom_vjp
def f(x):
return x
def f_fwd(x):
return f(x.value), None
def f_bwd(_, g):
return g,
f.defvjp(f_fwd, f_bwd, symbolic_zeros=True)
@jax.remat
def foo(x):
return f(f(x))
jax.grad(foo)(3.)
def test_nones_representing_zeros_in_subtrees_returned_by_bwd(self):
# https://github.com/jax-ml/jax/issues/8356
@jax.custom_vjp
def f(x):
return x[0]
def f_fwd(x):
return f(x), None
def f_bwd(_, z_bar):
return (z_bar, (None, None)),
f.defvjp(f_fwd, f_bwd)
jax.grad(f)((1.0, (2.0, 3.0))) # don't crash
def test_pytree_nones_returned_by_bwd(self):
@jax.custom_vjp
def f(x):
return x[0]
def f_fwd(x):
return f(x), None
def f_bwd(_, z_bar):
return (z_bar, (None, None)),
f.defvjp(f_fwd, f_bwd)
jax.grad(f)((1.0, (2.0, None))) # don't crash
def test_bwd_rule_shape_mismatch(self):
@jax.custom_vjp
def foo(x, y):
return x
def foo_fwd(x, y):
return x, None
def foo_bwd(_, g):
return jnp.zeros(3), jnp.zeros(3)
foo.defvjp(foo_fwd, foo_bwd)
with self.assertRaisesRegex(
ValueError,
r'output\[1\] the bwd rule produced an output of type f.*\[3\]'):
jax.grad(lambda x, y: foo(x, y * y).sum(), 1)(jnp.ones(3), jnp.ones(4))
def test_bwd_rule_shape_mismatch_disable(self):
# TODO(mattjj): remove this test when the config option is removed
@jax.custom_vjp
def foo(x, y):
return x
def foo_fwd(x, y):
return x, None
def foo_bwd(_, g):
return jnp.zeros(3), jnp.zeros(3)
foo.defvjp(foo_fwd, foo_bwd)
with config.disable_bwd_checks(True):
jax.grad(lambda x, y: foo(x, y).sum(), 1)(jnp.ones(3), jnp.ones(4))
def test_bwd_rule_can_produce_list_or_tuple(self):
@jax.custom_vjp
def f(x, y):
return x * y
def f_fwd(x, y):
return f(x, y), (x, y)
def f_bwd(xy, g):
x, y = xy
return [g * y, x * g] # list, not tuple
f.defvjp(f_fwd, f_bwd)
jax.grad(f)(1., 2.) # don't crash
def test_optimize_remat(self):
def fun(x):
# This array is included to make sure that we handle consts appropriately
return np.array([1.0])*x
def fwd(x):
return np.array([2.0])*x*x/np.array([1.0]), (2 * x,)
x = jnp.linspace(0, 5.0, 10)
fwd = custom_derivatives.optimize_remat_of_custom_vjp_fwd(
fun, api_util.debug_info("custom_vjp fun", fun, (x,), {}),
fwd, api_util.debug_info("custom_vjp fwd", fwd, (x,), {}))
self.assertAllClose(jax.jit(fwd)(x)[0], 2*x*x) # Shouldn't hit custom DCE
self.assertAllClose(jax.jit(lambda x: fwd(x)[0])(x), x) # Should be DCEed
def test_optimize_remat_vmap(self):
def fun(x):
return (np.array([1.0])*x)[0]
def fwd(x):
return (np.array([2.0])*x*x/np.array([1.0]))[0], (2 * x,)
x = jnp.linspace(0, 5.0, 10)
fwd = custom_derivatives.optimize_remat_of_custom_vjp_fwd(
fun, api_util.debug_info("custom_vjp fun", fun, (x,), {}),
fwd, api_util.debug_info("custom_vjp fwd", fwd, (x,), {}))
self.assertAllClose(jax.jit(jax.vmap(fwd))(x)[0], 2*x*x)
self.assertAllClose(jax.jit(lambda x: jax.vmap(fwd)(x)[0])(x), x)
def test_optimize_remat_cond(self):
def fun(x):
return x
def fwd(x):
return x*x, (2 * x,)
x = jnp.linspace(0, 5.0, 10)
fwd = custom_derivatives.optimize_remat_of_custom_vjp_fwd(
fun, api_util.debug_info("custom_vjp fun", fun, (x,), {}),
fwd, api_util.debug_info("custom_vjp fwd", fwd, (x,), {}))
def g(x):
return jax.lax.cond(True, fwd, lambda x: (2.0 * x, (x,)), x)
self.assertAllClose(jax.jit(g)(x)[0], x*x)
self.assertAllClose(jax.jit(lambda x: g(x)[0])(x), x)
def test_optimize_remat_jvp(self):
def fun(x):
return x**2
def fwd_(x):
return x*x, (2 * x,)
fwd = custom_derivatives.optimize_remat_of_custom_vjp_fwd(
fun, api_util.debug_info("custom_vjp fun", fun, (3.2,), {}),
fwd_, api_util.debug_info("custom_vjp fwd", fwd_, (3.2,), {}))
calc = jax.jvp(fwd, (3.2,), (1.0,))
expected = jax.jvp(fwd_, (3.2,), (1.0,))
self.assertAllClose(calc, expected)
@jax.jit
def g(x, t):
(y, r), (y_dot, r_dot) = jax.jvp(fwd, (x,), (t,))
return y, y_dot
calc = g(3.2, 1.0)
expected = jax.jvp(fun, (3.2,), (1.0,))
self.assertAllClose(calc, expected)
def test_optimize_remat_gh21303(self):
@jax.custom_vjp
def f(x):
return jnp.tan(x)
def f_fwd(x):
return jnp.sin(x), (x,)
def f_bwd(res, g):
x, = res
cos_x = jnp.cos(x)
return (cos_x * g,)
f.defvjp(f_fwd, f_bwd, optimize_remat=True)
def temp(x):
out = jax.remat(f)(x)
out = out ** 2
return out
v, g = jax.value_and_grad(temp)(3.2)
self.assertAllClose(v, jnp.tan(3.2)**2)
def test_optimize_remat_multiple_args(self):
def f_(x, y):
return jnp.sin(x) * y
@jax.custom_vjp
def f(x, y):
return f_(x, y)
def f_fwd(x, y):
return f(x, y), (jnp.cos(x), jnp.sin(x), y)
def f_bwd(res, g):
cos_x, sin_x, y = res
return (cos_x * g * y, sin_x * g)
f.defvjp(f_fwd, f_bwd, optimize_remat=True)
x, y = 3.2, 1.0
self.assertAllClose(jax.grad(f)(x, y), jax.grad(f_)(x, y))
def test_optimize_remat_kwargs(self):
@jax.custom_vjp
def f(x, y):
return jnp.sin(x) * y
def f_fwd(x, y, *, keyword=False):
del keyword
return f(x, y), (jnp.cos(x), jnp.sin(x), y)
def f_bwd(res, g):
cos_x, sin_x, y = res
return (cos_x * g * y, sin_x * g)
f.defvjp(f_fwd, f_bwd, optimize_remat=True)
x, y = 3.2, 1.0
jax.grad(f)(x, y) # Doesn't error
def test_optimize_remat_custom_vmap(self):
# See https://github.com/jax-ml/jax/pull/23000
@jax.custom_vjp
def f(x, y):
return jnp.sin(x) * y
@jax.custom_batching.custom_vmap
def f_fwd(x, y):
return f(x, y), (jnp.cos(x), jnp.sin(x), y)
@f_fwd.def_vmap
def f_fwd_vmap(_, in_batched, x, y):
# Insert a new const here to test the optimize_remat batching rule.
out = np.array([2.0])*f(x, y)
out_batched = (True, (True, True, True))
return (out, (jnp.cos(x), jnp.sin(x), y)), out_batched
def f_bwd(res, g):
cos_x, sin_x, y = res
return (cos_x * g * y, sin_x * g)
f.defvjp(f_fwd, f_bwd, optimize_remat=True)
x, y = jnp.linspace(0.0, 1.0, 5), jnp.linspace(2.0, 5.0, 5)
jax.jit(jax.vmap(jax.grad(f)))(x, y) # Doesn't error
def test_dce(self):
@jax.custom_vjp
def f(x, y):
return jnp.sin(x), x + jnp.cos(y)
def f_fwd(x, y):
return f(x, y), (jnp.cos(x), jnp.sin(y))
def f_bwd(res, cts):
cos_x, sin_y = res
ct_a, ct_b = cts
return 2.0 * cos_x * ct_a + 1.5 * ct_b, -0.5 * sin_y * ct_b
f.defvjp(f_fwd, f_bwd)
def check_jaxpr(jaxpr, used_outs, includes, excludes):
dce_jaxpr, _ = pe.dce_jaxpr(jaxpr, used_outs)
if not dce_jaxpr.eqns:
assert not includes
return
call_jaxpr = dce_jaxpr.eqns[0].params["call_jaxpr"]
for prim in includes:
assert any(eqn.primitive == prim for eqn in call_jaxpr.eqns)
for prim in excludes:
assert all(eqn.primitive != prim for eqn in call_jaxpr.eqns)
x, y = 0.1, -1.3
jaxpr = jax.make_jaxpr(f)(x, y).jaxpr
check_jaxpr(jaxpr, [True, True], [lax.sin_p, lax.cos_p], [])
check_jaxpr(jaxpr, [True, False], [lax.sin_p], [lax.cos_p])
check_jaxpr(jaxpr, [False, True], [lax.cos_p], [lax.sin_p])
check_jaxpr(jaxpr, [False, False], [], [lax.sin_p, lax.cos_p])
def dce_jaxpr_as_fun(jaxpr, used_outs):
jaxpr_, _ = pe.dce_jaxpr(jaxpr, used_outs)
fun = core.jaxpr_as_fun(pe.close_jaxpr(jaxpr_))
return lambda *args: fun(*args)[0]
f0 = dce_jaxpr_as_fun(jaxpr, [True, False])
f1 = dce_jaxpr_as_fun(jaxpr, [False, True])
self.assertAllClose(
api.grad(f0, argnums=(0, 1))(x, y), (2.0 * jnp.cos(x), 0.0))
self.assertAllClose(
api.grad(f1, argnums=(0, 1))(x, y), (1.5, -0.5 * jnp.sin(y)))
def test_resolve_kwargs_error_message(self):
@jax.custom_vjp
def f(x, y, *, z=None):
return jnp.sin(x), x + jnp.cos(y)
def f_fwd(x, y):
self.fail("should not be executed")
def f_bwd(res, cts):
self.fail("should not be executed")
f.defvjp(f_fwd, f_bwd)
with self.assertRaisesRegex(
TypeError,
r"missing a required argument: 'y'"
):
f(0.5)
with self.assertRaisesRegex(
TypeError,
"The following keyword arguments could not be resolved to positions: z"
):
f(0.5, 0.1, z=1.0)
def test_pretty_print(self):
@jax.custom_vjp
def f(x):
return x + 1
def f_fwd(x):
return f(x), ()
def f_bwd(_, g):
return g
f.defvjp(f_fwd, f_bwd)
x = jnp.array([4.2], dtype=jnp.float32)
jaxpr = jax.make_jaxpr(f)(x)
actual = jaxpr.pretty_print(use_color=False)
expected = textwrap.dedent(
"""
{ lambda ; a:f32[1]. let
b:f32[1] = custom_vjp_call[
name=f
bwd=f_bwd
call_jaxpr={ lambda ; c:f32[1]. let d:f32[1] = add c 1.0:f32[] in (d,) }
fwd=f_fwd
symbolic_zeros=False
] a
in (b,) }
""").strip()
self.assertEqual(actual, expected)
def test_custom_lin_pretty_print(self):
@jax.custom_vjp
def f(x):
return x + 1
def f_fwd(x):
return f(x), ()
def f_bwd(_, g):
return g
f.defvjp(f_fwd, f_bwd)
x = jnp.array([4.2], dtype=jnp.float32)
jaxpr = jax.make_jaxpr(lambda x: jax.jvp(f, (x,), (x,)))(x)
jaxpr, _ = pe.dce_jaxpr(jaxpr.jaxpr, [False, True])
actual = jaxpr.pretty_print(use_color=False)
expected = textwrap.dedent(
"""
{ lambda ; a:f32[1]. let
b:f32[1] = custom_lin[
bwd=f_bwd
in_zeros=[False]
num_res=0
symbolic_zeros=False
] a
in (b,) }
""").strip()
self.assertEqual(actual, expected)
@jtu.with_config(jax_custom_vjp3=True)
class CustomVJP3Test(CustomVJPTest):
# regress these, hope no one cares
def test_python_control_flow(self): pass
def test_pytrees_not_required_to_contain_nones(self): pass
def test_symbolic_zero_custom_vjp_bwd_shape_error(self): pass
def test_symbolic_zeros_remat(self): pass
def test_dce(self): pass
def test_pretty_print(self): pass
def test_custom_lin_pretty_print(self): pass
# vmap closure: don't support anymore, but raise good errors
def test_closed_over_vmap_tracer(self):
def outer(x):
@jax.custom_vjp
def f(y):
return x * y
def f_fwd(y):
return f(y), jnp.cos(y)
def f_rev(cos_y, g):
return (cos_y * g,)
f.defvjp(f_fwd, f_rev)
return f
@api.vmap
def g(x):
return outer(x)(3.)
with self.assertRaisesRegex(UnexpectedTracerError, "can't close over"):
g(np.arange(3.))
def test_closed_over_tracer3(self):
def outer(x):
@jax.custom_vjp
def f(y):
return x * y
def f_fwd(y):
return f(y), (x, jnp.cos(y))
def f_rev(res, g):
x, cos_y = res
return (cos_y * g * x,)
f.defvjp(f_fwd, f_rev)
return api.grad(f)
@api.vmap
def g(x):
return outer(x)(3.)
with self.assertRaisesRegex(UnexpectedTracerError, "can't close over"):
g(np.arange(3.))
def test_closure_with_vmap2(self):
# https://github.com/jax-ml/jax/issues/8783
def h(z):
def f(x):
@jax.custom_vjp
def g(y):
return x * y
def g_fwd(y):
return x * y, (x, x * y, y)
def g_rev(res, w_bar):
x, *_ = res
return (x * w_bar,)
g.defvjp(g_fwd, g_rev)
return g(z)
return jax.vmap(f)(jnp.arange(3., dtype='float32')).sum()
with self.assertRaisesRegex(UnexpectedTracerError, "can't close over"):
jtu.check_grads(h, (jnp.float32(3.14),), order=1, modes=['rev'])
# improved error message
def test_fwd_rule_primal_out_type_doesnt_match_primal_error_message(self):
def scan_apply(f, x):
y, _ = jax.lax.scan(lambda x, _: (f(x), None), x, None, length=1)
return y
@jax.custom_vjp
def f(x):
return x
def f_fwd(x):
return (x, x), None
def f_bwd(_, y_bar):
return (y_bar,)
f.defvjp(f_fwd, f_bwd)
self.assertRaisesRegex(
TypeError,
"Custom VJP fwd rule f_fwd for function f must produce a pair ",
lambda: jax.grad(lambda x: scan_apply(f, x))(jnp.float32(1.)))
def f_fwd2(x):
return jnp.zeros((3, *x.shape), x.dtype), None
def f_bwd2(_, y_bar):
return (y_bar,)
f.defvjp(f_fwd2, f_bwd2)
self.assertRaisesRegex(
TypeError,
r"got fwd output type float32\[3\] which doesn't match",
lambda: jax.grad(lambda x: scan_apply(f, x))(jnp.float32(1.)))
def transpose_unary(f, x_example):
def transposed(y):
x, = api.linear_transpose(f, x_example)(y)
return x
return transposed
# This class wraps jax.custom_transpose.custom_transpose in order to pass in a
# particular tree of output type on each call. Otherwise it forwards
# all attribute access.
class _custom_transpose:
def __init__(self, out_types, fun):
self.out_types = out_types
self.fun = jax.custom_transpose.custom_transpose(fun)
def __getattr__(self, name):
return getattr(self.fun, name)
def __call__(self, *args):
return self.fun(self.out_types, *args)
# This function is meant to be used as a decorator that delegates to
# custom_transpose but makes it easy to specify output argument types
# by example. If used directly a decorator (i.e. not invoked with
# example arguments), assumes a scalar-valued function.
#
# TODO(frostig): remove this (and its uses) once custom_transpose offers
# an option of inferring output types.
def custom_transpose(example_out):
if isinstance(example_out, Callable):
out_type = core.get_aval(0.).to_tangent_aval()
return _custom_transpose(out_type, example_out)
return partial(
_custom_transpose,
jax.tree.map(
lambda x: core.get_aval(x).to_tangent_aval(), example_out))
class CustomTransposeTest(jtu.JaxTestCase):
def test_linear_call(self):
def f(x, y):
def fn(r, x): return x / r
def tp(r, t): return t / r
return x + jax.custom_derivatives.linear_call(fn, tp, y, x)
def f_ref(x, y):
return x + x / y
x = jnp.ones(2) * 6.
y = jnp.ones(2) * 3.
self.assertAllClose(f(x, y), f_ref(x, y))
f1 = lambda x: f(x, y)
f1_ref = lambda x: f_ref(x, y)
self.assertAllClose(transpose_unary(f1, x)(x),
transpose_unary(f1_ref, x)(x))
def test_linear_call_incorrect_transpose(self):
def f(x, y):
def fn(r, x): return x / r
def tp(r, t): return t / (2. * r) # nb: not the true transpose
return x + jax.custom_derivatives.linear_call(fn, tp, y, x)
def f_ref(x, y):
return x + x / y
x = jnp.ones(2) * 6.
y = jnp.ones(2) * 3.
self.assertAllClose(f(x, y), f_ref(x, y))
f1 = lambda x: f(x, y)
f1_ref = lambda x: f_ref(x, 2. * y) # nb: double the reference divisor
self.assertAllClose(transpose_unary(f1, x)(x),
transpose_unary(f1_ref, x)(x))
def test_linear_call_transpose_transpose_transpose(self):
def fn(r, x): return x / r
def tp(r, t): return t / (2. * r) # nb: untrue transpose
def f_(x, y):
return x + jax.custom_derivatives.linear_call(fn, tp, y, x)
x = jnp.ones(2) * 6.
y = jnp.ones(2) * 3.
f = lambda x: f_(x, y)
ft = transpose_unary(f, x)
ftt = transpose_unary(ft, x)
fttt = transpose_unary(ftt, x)
self.assertAllClose(ft(x), x + tp(y, x))
self.assertAllClose(f(x), ftt(x))
self.assertAllClose(ft(x), fttt(x))
def test_linear_call_scalar_to_vector(self):
def f(c, x):
def fn(_, x):
return [x, x]
def tp(_, t):
t1, t2 = t
return t1 + t2
return jax.custom_derivatives.linear_call(fn, tp, (), c * x)
def f_ref(c, x):
return [c * x, c * x]
c, x = 2., 3.
t = [4., 5.]
self.assertAllClose(f(c, x), f_ref(c, x))
self.assertAllClose(transpose_unary(partial(f, c), x)(t),
transpose_unary(partial(f_ref, c), x)(t))
def test_linear_call_nested(self):
# identity function with an untrue transpose of 0
def id_(x):
def f(_, x): return x
def t(_, t): return 0.
return jax.custom_derivatives.linear_call(f, t, (), x)
# identity function with an untrue transpose of 7, and where both
# forward and transpose have custom transpositions that should
# never end up invoked.
def f(x):
def f_(_, x): return id_(x)
def t_(_, t): return id_(7.)
return jax.custom_derivatives.linear_call(f_, t_, (), x)
x = 5.
id_t = transpose_unary(id_, x)
id_tt = transpose_unary(id_t, x)
ft = transpose_unary(f, x)
ftt = transpose_unary(ft, x)
fttt = transpose_unary(ftt, x)
self.assertAllClose(id_(x), x)
self.assertAllClose(id_t(x), 0.)
self.assertAllClose(id_tt(x), x)
self.assertAllClose(f(x), x)
self.assertAllClose(ft(x), 7.)
self.assertAllClose(ftt(x), x)
self.assertAllClose(fttt(x), 7.)
def test_linear_call_jit(self):
def f(x, y):
def fn(r, x): return x / r
def tp(r, t): return t / r
return x + jax.custom_derivatives.linear_call(fn, tp, y, x)
x = jnp.ones(2) * 6.
y = jnp.ones(2) * 3.
self.assertAllClose(f(x, y), jax.jit(f)(x, y))
f1 = lambda x: f(x, y)
self.assertAllClose(transpose_unary(f1, x)(x),
jax.jit(transpose_unary(f1, x))(x))
def test_linear_call_type_mismatch(self):
def f(x, y):
def fn(r, x): return x / r
def tp(r, t): return None
return x + jax.custom_derivatives.linear_call(fn, tp, y, x)
x = jnp.ones(2) * 6.
y = jnp.ones(2) * 3.
f1 = lambda x: f(x, y)
with self.assertRaisesRegex(TypeError, "transpose output pytree"):
transpose_unary(f1, x)(x)
def test_linear_call_recursion(self):
def f(x):
def fn(_, x): return x
def tp(_, t): return f(t)
return jax.custom_derivatives.linear_call(fn, tp, None, x)
jax.jit(f)(0.1)
def test_linear_call_grad(self):
def f(x, y):
def fn(r, x): return x / r
def tp(r, t): return t / r
return x + jax.custom_derivatives.linear_call(fn, tp, y, x)
def f_ref(x, y):
return x + x / y
x = jnp.array(6.)
y = jnp.array(3.)
self.assertAllClose(jax.grad(f)(x, y), jax.grad(f_ref)(x, y))
def test_basic(self):
def f(x, y):
@custom_transpose(jnp.ones(2))
def fn(r, x): return x / r
@fn.def_transpose
def tp(r, t): return t / r
return x + fn(y, x)
def f_ref(x, y):
return x + x / y
x = jnp.ones(2) * 6.
y = jnp.ones(2) * 3.
self.assertAllClose(f(x, y), f_ref(x, y))
f1 = lambda x: f(x, y)
f1_ref = lambda x: f_ref(x, y)
self.assertAllClose(transpose_unary(f1, x)(x),
transpose_unary(f1_ref, x)(x))
def test_incorrect_transpose(self):
def f(x, y):
@custom_transpose(jnp.ones(2))
def fn(r, x): return x / r
@fn.def_transpose
def tp(r, t): return t / (2. * r) # nb: not the true transpose
return x + fn(y, x)
def f_ref(x, y):
return x + x / y
x = jnp.ones(2) * 6.
y = jnp.ones(2) * 3.
self.assertAllClose(f(x, y), f_ref(x, y))
f1 = lambda x: f(x, y)
f1_ref = lambda x: f_ref(x, 2. * y) # nb: double the reference divisor
self.assertAllClose(transpose_unary(f1, x)(x),
transpose_unary(f1_ref, x)(x))
def test_transpose_transpose_transpose(self):
@custom_transpose(jnp.ones(2))
def fn(r, x): return x / r
@custom_transpose(jnp.ones(2))
def tp(r, t): return t / (2. * r) # nb: untrue transpose
fn.def_transpose(tp)
tp.def_transpose(fn)
def f_(x, y):
return x + fn(y, x)
x = jnp.ones(2) * 6.
y = jnp.ones(2) * 3.
f = lambda x: f_(x, y)
ft = transpose_unary(f, x)
ftt = transpose_unary(ft, x)
fttt = transpose_unary(ftt, x)
self.assertAllClose(ft(x), x + tp(y, x))
self.assertAllClose(f(x), ftt(x))
self.assertAllClose(ft(x), fttt(x))
def test_scalar_to_vector(self):
def f(c, x):
@custom_transpose([0., 0.])
def fn(_, x):
return [x, x]
@fn.def_transpose
def tp(_, t):
t1, t2 = t
return t1 + t2
return fn((), c * x)
def f_ref(c, x):
return [c * x, c * x]
c, x = 2., 3.
t = [4., 5.]
self.assertAllClose(f(c, x), f_ref(c, x))
self.assertAllClose(transpose_unary(partial(f, c), x)(t),
transpose_unary(partial(f_ref, c), x)(t))
def test_nested(self):
# identity function with an untrue transpose of 0
def id_(x):
f = custom_transpose(lambda _, x: x)
t = custom_transpose(lambda _, t: 0.)
f.def_transpose(t)
t.def_transpose(f)
return f((), x)
# identity function with an untrue transpose of 7, and where both
# forward and transpose have custom transpositions that should
# never end up invoked.
def f(x):
f_ = custom_transpose(lambda _, x: id_(x))
t_ = custom_transpose(lambda _, t: id_(7.))
f_.def_transpose(t_)
t_.def_transpose(f_)
return f_((), x)
x = 5.
id_t = transpose_unary(id_, x)
id_tt = transpose_unary(id_t, x)
ft = transpose_unary(f, x)
ftt = transpose_unary(ft, x)
fttt = transpose_unary(ftt, x)
self.assertAllClose(id_(x), x)
self.assertAllClose(id_t(x), 0.)
self.assertAllClose(id_tt(x), x)
self.assertAllClose(f(x), x)
self.assertAllClose(ft(x), 7.)
self.assertAllClose(ftt(x), x)
self.assertAllClose(fttt(x), 7.)
def test_one_degree(self):
T = lambda f: transpose_unary(f, 0.)
@custom_transpose
def f(_, z): return 2. * z
@f.def_transpose
def ft(_, z): return 3. * z
f = partial(f, ())
self.assertAllClose(2., f(1.))
self.assertAllClose(3., T(f)(1.))
self.assertAllClose(3., T(T(f))(1.))
self.assertAllClose(3., T(T(T(f)))(1.))
self.assertAllClose(3., T(T(T(T(f))))(1.)) # ...
def test_two_degrees(self):
T = lambda f: transpose_unary(f, 0.)
@custom_transpose
def f(_, z): return 2. * z
@f.def_transpose
@custom_transpose
def ft(_, z): return 3. * z
@ft.def_transpose
def ftt(_, z): return 7. * z
f = partial(f, ())
self.assertAllClose(2., f(1.))
self.assertAllClose(3., T(f)(1.))
self.assertAllClose(7., T(T(f))(1.))
self.assertAllClose(7., T(T(T(f)))(1.))
self.assertAllClose(7., T(T(T(T(f))))(1.)) # ...
def test_symmetric(self):
T = lambda f: transpose_unary(f, 0.)
@custom_transpose
def f(_, z): return 2. * z
@custom_transpose
def g(_, z): return 3. * z
f.def_transpose(g)
g.def_transpose(f)
f = partial(f, ())
self.assertAllClose(2., f(1.))
self.assertAllClose(3., T(f)(1.))
self.assertAllClose(2., T(T(f))(1.))
self.assertAllClose(3., T(T(T(f)))(1.))
self.assertAllClose(2., T(T(T(T(f))))(1.)) # ...
def test_recursive(self):
T = lambda f: transpose_unary(f, 0.)
@custom_transpose
def f(c, z): return c * z
@f.def_transpose
def ft(c, z): return f(c + 1., z)
g = partial(f, 1.)
self.assertAllClose(1., g(1.))
self.assertAllClose(2., T(g)(1.))
self.assertAllClose(3., T(T(g))(1.))
self.assertAllClose(4., T(T(T(g)))(1.))
self.assertAllClose(5., T(T(T(T(g))))(1.)) # ...
def test_jvp_lin(self):
def f(x, y):
@custom_transpose(jnp.ones(2))
def fn(r, x): return x / r
@fn.def_transpose
def tp(r, t): return t / r
return x + fn(y, x)
def f_ref(x, y): return x + x / y
x, y, tx = 6., 3., 1.
g = lambda x: f(x, y)
g_ref = lambda x: f_ref(x, y)
self.assertAllClose(api.jvp(g, [x], [tx]), api.jvp(g_ref, [x], [tx]))
def test_jvp_res(self):
raise unittest.SkipTest('unimplemented') # TODO(frostig)
def f(x, y):
@custom_transpose(jnp.ones(2))
def fn(r, x): return x / r
@fn.def_transpose
def tp(r, t): return t / r
return x + fn(y, x)
def f_ref(x, y): return x + x / y
x, y, ty = 6., 3., 1.
g = lambda y: f(x, y)
g_ref = lambda y: f_ref(x, y)
self.assertAllClose(api.jvp(g, [y], [ty]), api.jvp(g_ref, [y], [ty]))
def test_jvp_both(self):
raise unittest.SkipTest('unimplemented') # TODO(frostig)
def f(x, y):
@custom_transpose(jnp.ones(2))
def fn(r, x): return x / r
@fn.def_transpose
def tp(r, t): return t / r
return x + fn(y, x)
def f_ref(x, y): return x + x / y
x, y, tx, ty = 6., 3., 1., 1.
self.assertAllClose(api.jvp(f, [x, y], [tx, ty]),
api.jvp(f_ref, [x, y], [tx, ty]))
def test_make_jaxpr(self):
def f(x, y):
@custom_transpose(jnp.ones(2))
def fn(r, x): return x / r
@fn.def_transpose
def tp(r, t): return 2 * t / r
return x + fn(y, x)
x = jnp.ones(2) * 6.
y = jnp.ones(2) * 3.
f_ = lambda x: f(x, y)
f_t = transpose_unary(f_, x)
jaxpr = api.make_jaxpr(f_)(x)
self.assertIn('custom_transpose_call', str(jaxpr))
jaxpr_t = api.make_jaxpr(f_t)(x)
self.assertNotIn('custom_transpose_call', str(jaxpr_t))
def test_jit(self):
def f(x, y):
@custom_transpose(jnp.ones(2))
def fn(r, x): return x / r
@fn.def_transpose
def tp(r, t): return 2 * t / r
return x + fn(y, x)
x = jnp.ones(2) * 6.
y = jnp.ones(2) * 3.
self.assertAllClose(f(x, y), jax.jit(f)(x, y))
f_ = lambda x: f(x, y)
f_t = transpose_unary(f_, x)
g_ = jax.jit(f_)
g_t = transpose_unary(g_, x)
self.assertAllClose(f_(x), jax.jit(f_)(x))
self.assertAllClose(f_t(x), jax.jit(f_t)(x))
self.assertAllClose(f_(x), g_(x))
self.assertAllClose(f_t(x), g_t(x))
def test_jit_recursive(self):
def f(x, y):
@custom_transpose(jnp.ones(2))
def fn(r, x): return x / r
@fn.def_transpose
def tp(r, t): return 2 * fn(r, t)
return x + fn(y, x)
x = jnp.ones(2) * 6.
y = jnp.ones(2) * 3.
self.assertAllClose(f(x, y), jax.jit(f)(x, y))
f_ = lambda x: f(x, y)
f_t = transpose_unary(f_, x)
g_ = jax.jit(f_)
g_t = transpose_unary(g_, x)
self.assertAllClose(f_(x), jax.jit(f_)(x))
self.assertAllClose(f_t(x), jax.jit(f_t)(x))
self.assertAllClose(f_(x), g_(x))
self.assertAllClose(f_t(x), g_t(x))
def test_cond(self):
def f(x, y):
@custom_transpose(jnp.ones(2))
def fn(r, x): return x / r
@fn.def_transpose
def tp(r, t): return 2 * t / r
return x + fn(y, x)
def cond_wrap(f):
return lambda i, x: lax.cond(i > 0, f, lambda x: x, x)
i = 7.
x = jnp.ones(2) * 6.
y = jnp.ones(2) * 3.
f_ = lambda x: f(x, y)
f_t = transpose_unary(f_, x)
g_ = partial(cond_wrap(f_), i)
g_t = transpose_unary(g_, x)
self.assertAllClose(f_(x), g_(x))
self.assertAllClose(f_t(x), g_t(x))
def test_cond_recursive(self):
def f(x, y):
@custom_transpose(jnp.ones(2))
def fn(r, x): return x / r
@fn.def_transpose
def tp(r, t): return 2 * fn(r, t)
return x + fn(y, x)
def cond_wrap(f):
return lambda i, x: lax.cond(i > 0, f, lambda x: x, x)
i = 7.
x = jnp.ones(2) * 6.
y = jnp.ones(2) * 3.
f_ = lambda x: f(x, y)
f_t = transpose_unary(f_, x)
g_ = partial(cond_wrap(f_), i)
g_t = transpose_unary(g_, x)
self.assertAllClose(f_(x), g_(x))
self.assertAllClose(f_t(x), g_t(x))
def test_compose_custom_jvp(self):
@jax.custom_jvp
def f(x):
return jnp.sin(x)
@f.defjvp
def f_jvp(primals, tangents):
x, = primals
dx, = tangents
return f(x), g(x, dx)
@custom_transpose
def g(x, dx):
return jnp.cos(x) * dx
@g.def_transpose
def gt(x, t):
return jnp.cos(x) * t
with config.use_direct_linearize(True):
self.assertAllClose(jax.grad(f)(0.5), jnp.cos(0.5))
def test_input_none(self):
# ref: https://github.com/jax-ml/jax/issues/29009
@jax.custom_jvp
def f(x, y): return y
@f.defjvp
def f_jvp(p, t): return f(*p), g(p, t)
@custom_transpose(jnp.float32(0))
def g(r, x): return x[1]
@g.def_transpose
def gt(r, t): return None, jnp.zeros_like(r[1])
jax.grad(f, argnums=(1,))(None, jnp.float32(2)) # doesn't crash
class CustomDceTest(jtu.JaxTestCase):
def test_basic(self):
@jax.experimental.custom_dce.custom_dce
def f(x):
return jnp.sin(x), jnp.cos(x)
@f.def_dce
def rule(used_outs, x):
return (
jnp.exp(x) if used_outs[0] else None,
jnp.sqrt(x) if used_outs[1] else None,
)
x = jnp.array(1.1234)
self.assertAllClose(jax.jit(lambda x: f(x)[0])(x), jnp.exp(x))
self.assertAllClose(jax.jit(lambda x: f(x)[1])(x), jnp.sqrt(x))
def test_recursive(self):
@jax.experimental.custom_dce.custom_dce
def f(x):
return jnp.exp(x), 10 * jnp.sqrt(x)
@f.def_dce
def f_dce(used_outs, x):
return [2 * v if used else None for used, v in zip(used_outs, f(x))]
x = 1.1234
expected = f(x)
self.assertAllClose(jax.jit(lambda x: f(x)[0])(x), 2 * expected[0])
self.assertAllClose(jax.jit(lambda x: f(x)[1])(x), 2 * expected[1])
def test_multiple_rounds(self):
@jax.experimental.custom_dce.custom_dce
def f(x, y, z):
return jnp.sin(x), jnp.sin(y), jnp.sin(z)
@f.def_dce
def rule(used_outs, x, y, z):
patterns.append(used_outs)
outs = [
jnp.cos(v) if used else None for used, v in zip(used_outs, (x, y, z))
]
return outs
patterns = []
x, y, z = jnp.array(1.), jnp.array(2.), jnp.array(3.)
jaxpr = jax.make_jaxpr(f)(x, y, z).jaxpr
new_jaxpr, used_ins = pe.dce_jaxpr(jaxpr, [True, False, True])
assert used_ins == [True, False, True]
new_jaxpr, used_ins = pe.dce_jaxpr(new_jaxpr, [True, False])
assert used_ins == [True, False]
assert patterns == [(True, False, True), (True, False, False)], patterns
def test_batching(self):
@jax.experimental.custom_dce.custom_dce
def f(x, y):
return jnp.sin(x), jnp.sin(y)
@f.def_dce
def rule(used_outs, x, y):
return (
jnp.cos(x) if used_outs[0] else None,
jnp.cos(y) if used_outs[1] else None,
)
x = jnp.linspace(-0.1, 0.2, 5)
y = jnp.linspace(3.0, 4.0, 5)
self.assertAllClose(jax.vmap(f)(x, y), f(x, y))
self.assertAllClose(
jax.jit(lambda *args: jax.vmap(f)(*args)[0])(x, y), jnp.cos(x)
)
self.assertAllClose(
jax.vmap(jax.jit(lambda *args: f(*args)[0]))(x, y), jnp.cos(x)
)
self.assertAllClose(
jax.jit(lambda *args: jax.vmap(f)(*args)[1])(x, y), jnp.cos(y)
)
self.assertAllClose(
jax.vmap(jax.jit(lambda *args: f(*args)[1]))(x, y), jnp.cos(y)
)
def test_composes_with_custom_vjp(self):
# custom_dce must be the "outer" decorator (for now!) because custom_vjp
# doesn't pass through DCE.
@jax.experimental.custom_dce.custom_dce
@jax.custom_vjp
def f(x, y):
return jnp.sin(x) * y, x * jnp.sin(y)
@f.def_dce
def f_dce_rule(used_outs, x, y):
return (
jnp.cos(x) * y if used_outs[0] else None,
x * jnp.cos(y) if used_outs[1] else None,
)
def f_fwd(x, y):
return f(x, y), (x, jnp.cos(x), jnp.sin(x), y, jnp.cos(y), jnp.sin(y))
def f_bwd(res, g):
ga, gb = g
x, cos_x, sin_x, y, cos_y, sin_y = res
return (cos_x * ga * y + sin_y * gb, sin_x * ga + x * cos_y * gb)
f.defvjp(f_fwd, f_bwd)
x, y = jnp.array(1.), jnp.array(2.)
self.assertAllClose(jax.jit(lambda *args: f(*args)[0])(x, y),
jnp.cos(x) * y)
jax.grad(lambda *args: f(*args)[0])(x, y) # Doesn't crash.
def test_can_optimize_remat(self):
@jax.custom_vjp
def f(x):
return jnp.tan(x)
@jax.experimental.custom_dce.custom_dce
def f_fwd(x):
return jnp.sin(x), (x,)
@f_fwd.def_dce
def f_dce_rule(used_outs, x):
used_prim, used_res = used_outs
used_res, = used_res
if not used_res:
return f(x), None
prim, res = f_fwd(x)
return prim if used_prim else None, res
def f_bwd(res, g):
x, = res
cos_x = jnp.cos(x)
return (cos_x * g,)
f.defvjp(f_fwd, f_bwd)
def temp(x):
out = jax.remat(f)(x)
out = out ** 2
return out
v, g = jax.value_and_grad(temp)(3.2)
self.assertAllClose(v, jnp.tan(3.2)**2)
def test_static_argnums(self):
@partial(jax.experimental.custom_dce.custom_dce, static_argnums=(0,))
def g(f, x):
return f(x), 10 * f(x)
@g.def_dce
def g_dce(f, used_outs, x): # note: static_argnums are always passes first
self.assertTrue(callable(f))
return [2 * v if used else None for used, v in zip(used_outs, g(f, x))]
x = 1.1234
f = lambda x: jnp.exp(x)
expected = g(f, x)
self.assertAllClose(jax.jit(lambda x: g(f, x)[0])(x), 2 * expected[0])
self.assertAllClose(jax.jit(lambda x: g(f, x)[1])(x), 2 * expected[1])
def test_shape_mismatch_error(self):
@jax.experimental.custom_dce.custom_dce
def f(x):
return jnp.stack((x, x)), jnp.cos(x)
@f.def_dce
def rule(used_outs, x):
return (
jnp.exp(x) if used_outs[0] else None,
x.astype(jnp.int32) if used_outs[1] else None,
)
x = jnp.array(1.1234)
with self.assertRaisesRegex(
ValueError,
r'Custom DCE rule .* same shapes/dtypes .* output\[0\]',
):
jax.jit(lambda x: f(x)[0])(x)
with self.assertRaisesRegex(
ValueError,
r'Custom DCE rule .* same shapes/dtypes .* output\[1\]',
):
jax.jit(lambda x: f(x)[1])(x)
def test_missing_output_error(self):
@jax.experimental.custom_dce.custom_dce
def f(x):
return jnp.sin(x), jnp.cos(x)
@f.def_dce
def rule(used_outs, x):
return None, None
x = jnp.array(1.1234)
with self.assertRaisesRegex(
ValueError,
r'Custom DCE rule .* produce values for all .* output\[0\]',
):
jax.jit(lambda x: f(x)[0])(x)
def test_consts(self):
@jax.experimental.custom_dce.custom_dce
def f(x):
return np.eye(1) * jnp.sin(x), jnp.cos(x)
@f.def_dce
def rule(used_outs, x):
return (
np.full((1, 1), 2.0) * jnp.exp(x) if used_outs[0] else None,
jnp.sqrt(x) if used_outs[1] else None,
)
x = jnp.array(1.1234)
expected = rule([True, True], x)
self.assertAllClose(jax.jit(lambda x: f(x)[0])(x), expected[0])
self.assertAllClose(jax.jit(lambda x: f(x)[1])(x), expected[1])
def test_resolve_kwargs_error_message(self):
@jax.experimental.custom_dce.custom_dce
def f(x, y, *, z=None):
return jnp.sin(x) * y, x * jnp.sin(y)
@f.def_dce
def f_dce_rule(used_outs, x, y):
self.fail("should not be executed")
with self.assertRaisesRegex(
TypeError,
r"The input arguments to the custom_dce-decorated function f(.*)\n"
r"missing a required argument: 'y'"
):
f(0.5)
with self.assertRaisesRegex(
TypeError,
r"The input arguments to the custom_dce-decorated function f(.*)\n"
"The following keyword arguments could not be resolved to positions: z"
):
f(0.5, 0.1, z=1.0)
class CustomVmapTest(jtu.JaxTestCase):
def test_basic(self):
@jax.custom_batching.custom_vmap
def f(x): return jnp.sin(x)
@f.def_vmap
def rule(axis_size, in_batched, xs):
xs_batched, = in_batched
self.assertEqual(xs_batched, True)
self.assertEqual(axis_size, xs.shape[0])
return jnp.cos(xs), xs_batched
x, xs = jnp.array(1.), jnp.arange(3)
y = f(x)
self.assertAllClose(y, jnp.sin(x))
ys = api.vmap(f)(xs)
self.assertAllClose(ys, jnp.cos(xs))
@jax.numpy_dtype_promotion('standard')
def test_closure(self):
z = jnp.array([2., 1., 3.])
@jax.custom_batching.custom_vmap
def f(x): return z + jnp.sin(x)
@f.def_vmap
def rule(axis_size, in_batched, *args):
self.assertEqual(len(in_batched), 1)
self.assertEqual(len(args), 1)
xs, = args
xs_batched, = in_batched
self.assertEqual(xs_batched, True)
self.assertEqual(axis_size, xs.shape[0])
return z + jnp.cos(xs), xs_batched
x, xs = jnp.array(1.), jnp.arange(3)
y = f(x)
self.assertAllClose(y, z + jnp.sin(x))
ys = api.vmap(f)(xs)
self.assertAllClose(ys, z + jnp.cos(xs))
def test_rule_multi_output(self):
@jax.custom_batching.custom_vmap
def f(x): return jnp.sin(x), jnp.cos(x)
@f.def_vmap
def rule(axis_size, in_batched, xs):
return (jnp.cos(xs), jnp.sin(xs)), tuple(in_batched * 2)
x, xs = jnp.array(1.), jnp.arange(3)
y1, y2 = f(x)
self.assertAllClose(y1, jnp.sin(x))
self.assertAllClose(y2, jnp.cos(x))
ys1, ys2 = api.vmap(f)(xs)
self.assertAllClose(ys1, jnp.cos(xs))
self.assertAllClose(ys2, jnp.sin(xs))
def test_nary(self):
@jax.custom_batching.custom_vmap
def f(x, y): return jnp.sin(x) + y ** 2.
@f.def_vmap
def rule(axis_size, in_batched, xs, ys):
self.assertEqual(in_batched, [True, True])
self.assertEqual(axis_size, 3)
self.assertEqual(axis_size, xs.shape[0])
self.assertEqual(axis_size, ys.shape[0])
return jnp.cos(xs) + ys ** 2., True
xs, ys = jnp.arange(3.0), jnp.arange(3.0)
zs = api.vmap(f)(xs, ys)
self.assertAllClose(zs, jnp.cos(xs) + ys ** 2.)
def test_nary_mixed_batching(self):
@jax.custom_batching.custom_vmap
def vector_dot(u, v):
self.assertEqual(u.ndim, 1)
self.assertEqual(v.ndim, 1)
return u @ v
size = 4
vlen = 3
in_batched_log = []
@vector_dot.def_vmap
def vector_dot_vmap_rule(axis_size, in_batched, u, v):
in_batched_log.append(in_batched)
self.assertEqual(axis_size, size)
u_batched, v_batched = in_batched
if u_batched:
self.assertEqual(u.ndim, 2)
self.assertEqual(u.shape[0], size)
else:
self.assertEqual(u.ndim, 1)
self.assertEqual(u.shape[0], vlen)
if v_batched:
self.assertEqual(v.ndim, 2)
self.assertEqual(v.shape[0], size)
else:
self.assertEqual(v.ndim, 1)
self.assertEqual(v.shape[0], vlen)
if u_batched and v_batched:
out = jnp.sum(u * v, axis=1)
else:
out = u @ v if u_batched else v @ u
return out, u_batched or v_batched
f = vector_dot
v = lambda *shape: jnp.ones(shape)
y = api.vmap(f, in_axes=(0, None))(v(4, 3), v(3))
self.assertAllClose(y, v(4, 3) @ v(3))
y = api.vmap(f, in_axes=(1, None))(v(3, 4), v(3))
self.assertAllClose(y, v(3, 4).T @ v(3))
y = api.vmap(f, in_axes=(None, 0))(v(3), v(4, 3))
self.assertAllClose(y, v(3) @ v(4, 3).T)
y = api.vmap(f, in_axes=(0, 0))(v(4, 3), v(4, 3))
self.assertAllClose(y, jnp.sum(v(4, 3) * v(4, 3), axis=1))
self.assertEqual(in_batched_log[0], [True, False])
self.assertEqual(in_batched_log[1], [True, False])
self.assertEqual(in_batched_log[2], [False, True])
self.assertEqual(in_batched_log[3], [True, True])
def test_rule_input_signature(self):
@jax.custom_batching.custom_vmap
def f(x): return jnp.sin(x)
rule_args = []
@f.def_vmap
def rule(axis_size, in_batched, xs):
rule_args.append((axis_size, in_batched))
return jnp.cos(xs), in_batched[0]
xs = jnp.arange(3)
_ = api.vmap(f)(xs)
(axis_size, in_batched), = rule_args
self.assertIs(type(axis_size), int)
self.assertIs(type(in_batched), list)
self.assertEqual(len(in_batched), 1)
def test_rule_output_vs_batching_output_mismatch(self):
@jax.custom_batching.custom_vmap
def f(x): return jnp.sin(x)
@f.def_vmap
def test_rule_abc(axis_size, in_batched, xs):
return [jnp.sin(xs), jnp.cos(xs)], in_batched
xs = jnp.arange(3)
self.assertRaisesRegex(
ValueError,
'structure of output value and output batching specification '
r'returned by custom vmap rule \(test_rule_abc\) do not match.*',
lambda: api.vmap(f)(xs))
def test_rule_vs_call_output_mismatch(self):
@jax.custom_batching.custom_vmap
def f(x): return jnp.sin(x)
@f.def_vmap
def test_rule_abc2(axis_size, in_batched, xs):
return [jnp.sin(xs)], in_batched
xs = jnp.arange(3)
self.assertRaisesRegex(
ValueError,
r'structure of output returned by custom vmap rule \(test_rule_abc2\) '
r'does not match that of original custom-vmapped function.*',
lambda: api.vmap(f)(xs))
def test_jvp_basic(self):
@jax.custom_batching.custom_vmap
def f(x): return jnp.sin(x)
@f.def_vmap
def rule(axis_size, in_batched, xs):
self.assertEqual(axis_size, 3)
self.assertEqual(in_batched, [True])
return jnp.cos(xs), in_batched[0]
f_jvp = lambda x, tx: api.jvp(f, [x], [tx])
x, tx = jnp.array(1.), jnp.array(2.)
xs, txs = jnp.arange(3.), jnp.arange(3.) * 2.
y, ty = f_jvp(x, tx)
self.assertAllClose(y, jnp.sin(x))
self.assertAllClose(ty, jnp.cos(x) * tx)
ys, tys = api.vmap(f_jvp)(xs, txs)
self.assertAllClose(ys, jnp.cos(xs))
self.assertAllClose(tys, -jnp.sin(xs) * txs)
ys, tys = api.jvp(api.vmap(f), [xs], [txs])
self.assertAllClose(ys, jnp.cos(xs))
self.assertAllClose(tys, -jnp.sin(xs) * txs)
@jax.numpy_dtype_promotion('standard')
def test_jvp_closure(self):
z = jnp.array([2., 1., 3.])
def bcast(x): return z + x - z
@jax.custom_batching.custom_vmap
def f(x): return z + jnp.sin(x)
@f.def_vmap
def rule(axis_size, in_batched, xs):
self.assertEqual(axis_size, 3)
self.assertEqual(in_batched, [True])
return z + jnp.cos(xs), in_batched[0]
f_jvp = lambda x, tx: api.jvp(f, [x], [tx])
x, tx = jnp.array(1.), jnp.array(2.)
xs, txs = jnp.arange(3.), jnp.arange(3.) * 2.
y, ty = f_jvp(x, tx)
self.assertAllClose(y, z + jnp.sin(x))
self.assertAllClose(ty, bcast(jnp.cos(x)) * tx)
ys, tys = api.vmap(f_jvp)(xs, txs)
self.assertAllClose(ys, z + jnp.cos(xs))
self.assertAllClose(tys, bcast(-jnp.sin(xs)) * txs)
ys, tys = api.jvp(api.vmap(f), [xs], [txs])
self.assertAllClose(ys, z + jnp.cos(xs))
self.assertAllClose(tys, bcast(-jnp.sin(xs)) * txs)
def test_jvp_nary(self):
@jax.custom_batching.custom_vmap
def f(x, y): return jnp.sin(x) + y
@f.def_vmap
def rule(axis_size, in_batched, xs, ys):
self.assertEqual(axis_size, 3)
self.assertEqual(in_batched, [True, True])
return jnp.cos(xs) + ys, True
f_jvp = lambda x, y, tx, ty: api.jvp(f, [x, y], [tx, ty])
x, y, tx, ty = jnp.arange(4.)
xs, ys, txs, tys = 4. + jnp.arange(3. * 4).reshape((4, 3))
zs, tzs = api.vmap(f_jvp)(xs, ys, txs, tys)
self.assertAllClose(zs, jnp.cos(xs) + ys)
self.assertAllClose(tzs, -jnp.sin(xs) * txs + tys)
zs, tzs = api.jvp(api.vmap(f), [xs, ys], [txs, tys])
self.assertAllClose(zs, jnp.cos(xs) + ys)
self.assertAllClose(tzs, -jnp.sin(xs) * txs + tys)
def test_jvp_extra_batched_tangents(self):
@jax.custom_batching.custom_vmap
def f(x): return jnp.sin(x)
@f.def_vmap
def rule(axis_size, in_batched, xs):
self.assertEqual(axis_size, 3)
self.assertEqual(in_batched, [False])
return jnp.cos(xs), in_batched[0]
f_jvp = lambda x, tx: api.jvp(f, [x], [tx])
txs = 2. + jnp.arange(3.)
x = jnp.array(1, dtype=txs.dtype)
y, tys = api.vmap(f_jvp, in_axes=(None, 0), out_axes=(None, 0))(x, txs)
self.assertAllClose(y, jnp.cos(x))
self.assertAllClose(tys, -jnp.sin(x) * txs)
def test_jacfwd(self):
# jacfwd is another way to exercise extra-batched tangents
@jax.custom_batching.custom_vmap
def f(x): return jnp.sin(x)
@f.def_vmap
def rule(axis_size, in_batched, xs):
self.assertEqual(axis_size, 3)
self.assertEqual(in_batched, [False])
return jnp.cos(xs), in_batched[0]
x = jnp.arange(3.) + .72
j = api.jacfwd(f)(x)
self.assertAllClose(j, -jnp.diag(jnp.sin(x)))
def test_jvp_extra_batched_primals(self):
@jax.custom_batching.custom_vmap
def f(x): return jnp.sin(x)
@f.def_vmap
def rule(axis_size, in_batched, xs):
self.assertEqual(axis_size, 3)
self.assertEqual(in_batched, [False])
return jnp.cos(xs), in_batched[0]
f_jvp = lambda x, tx: api.jvp(f, [x], [tx])
xs = jnp.arange(3.)
tx = jnp.array(4, dtype=xs.dtype)
ys, tys = api.vmap(f_jvp, in_axes=(0, None))(xs, tx)
self.assertAllClose(ys, jnp.cos(xs))
self.assertAllClose(tys, -jnp.sin(xs) * tx)
def test_jvp_extra_batched_primals_with_linear_vmap_rule(self):
# When a function is linear, its Jacobian is constant. JAX's JVP
# of linear functions takes advantage of this: when mapping over a
# batch of primals relative to a fixed (i.e. symbolically
# replicated) tangent, output tangents remain replicated as well
# (i.e. JAX will not broadcast them). This is true in general, and
# this test checks that vmapped JVPs continue to behave this way
# when custom_vmap is involved and the custom vmap rule is linear.
@jax.custom_batching.custom_vmap
def f_linear(x): return 7. * x
@f_linear.def_vmap
def linear_rule(axis_size, in_batched, xs):
return 11. * xs, in_batched[0]
@jax.custom_batching.custom_vmap
def f_nonlinear(x): return jnp.sin(x)
@f_nonlinear.def_vmap
def nonlinear_rule(axis_size, in_batched, xs):
return jnp.cos(xs), in_batched[0]
f_lin_jvp = lambda x, tx: api.jvp(f_linear, [x], [tx])
f_non_jvp = lambda x, tx: api.jvp(f_nonlinear, [x], [tx])
xs = jnp.arange(3.)
tx = jnp.array(4., dtype=xs.dtype)
# doesn't err
_ = api.vmap(f_lin_jvp, in_axes=(0, None), out_axes=(0, None))(xs, tx)
# does err
self.assertRaisesRegex(
ValueError, "at vmap out_axes",
lambda: api.vmap(
f_non_jvp, in_axes=(0, None), out_axes=(0, None))(xs, tx))
def test_jvp_dataflow_violation(self):
# The jvp-of-custom-vmap machinery should not assume the standard
# dataflow constraint on the JVP of the custom vmap rule (primal
# outputs independent of tangent inputs). Both jvp and vmap are
# "forward" transformations under which, at present, we don't
# enforce the JVP dependence diagram. Because output primals can
# depend on input tangents, extra-batched input tangents can
# create batched output primals, as this test checks.
@jax.custom_jvp
def cos_with_invalid_dataflow_jvp(x): return jnp.cos(x)
@cos_with_invalid_dataflow_jvp.defjvp
def invalid_dataflow_jvp(x, tx):
[x], [tx] = x, tx
return jnp.cos(x * tx), tx
@jax.custom_batching.custom_vmap
def f(x): return jnp.sin(x)
@f.def_vmap
def rule(axis_size, in_batched, xs):
return cos_with_invalid_dataflow_jvp(xs), in_batched[0]
f_jvp = lambda x, tx: api.jvp(f, [x], [tx])
txs = 2. + jnp.arange(3.)
x = jnp.array(1, dtype=txs.dtype)
# doesn't err
ys, tys = api.vmap(f_jvp, in_axes=(None, 0))(x, txs)
self.assertAllClose(ys, jnp.cos(x * txs))
self.assertAllClose(tys, txs)
# does err
self.assertRaisesRegex(
ValueError, "at vmap out_axes",
lambda: api.vmap(
f_jvp, in_axes=(None, 0), out_axes=(None, 0))(x, txs))
def test_tree(self):
tree_sin = partial(jax.tree.map, jnp.sin)
tree_cos = partial(jax.tree.map, jnp.cos)
x, xs = jnp.array(1.), jnp.arange(3)
x = (x, [x + 1, x + 2], [x + 3], x + 4)
xs = (xs, [xs + 1, xs + 2], [xs + 3], xs + 4)
in_batched_ref = jax.tree.map(lambda _: True, x)
@jax.custom_batching.custom_vmap
def f(xs): return tree_sin(xs)
@f.def_vmap
def rule(axis_size, in_batched, xs):
self.assertEqual(in_batched, [in_batched_ref])
sz, = {z.shape[0] for z in jax.tree.leaves(xs)}
self.assertEqual(axis_size, sz)
return tree_cos(xs), in_batched[0]
y = f(x)
self.assertAllClose(y, tree_sin(x))
ys = api.vmap(f)(xs)
self.assertAllClose(ys, tree_cos(xs))
def test_tree_with_nones(self):
tree_sin = partial(jax.tree.map, jnp.sin)
tree_cos = partial(jax.tree.map, jnp.cos)
x, xs = jnp.array(1.), jnp.arange(3)
x = (x, [x + 1, None], [x + 3], None)
xs = (xs, [xs + 1, None], [xs + 3], None)
in_batched_ref = jax.tree.map(lambda _: True, x)
@jax.custom_batching.custom_vmap
def f(xs): return tree_sin(xs)
@f.def_vmap
def rule(axis_size, in_batched, xs):
self.assertEqual(in_batched, [in_batched_ref])
sz, = {z.shape[0] for z in jax.tree.leaves(xs)}
self.assertEqual(axis_size, sz)
return tree_cos(xs), in_batched[0]
y = f(x)
self.assertAllClose(y, tree_sin(x))
ys = api.vmap(f)(xs)
self.assertAllClose(ys, tree_cos(xs))
def test_jit(self):
@jax.custom_batching.custom_vmap
def f(x): return jnp.sin(x)
@f.def_vmap
def rule(axis_size, in_batched, xs):
self.assertEqual(in_batched, [True])
self.assertEqual(axis_size, xs.shape[0])
return jnp.cos(xs), in_batched[0]
x, xs = jnp.array(1.), jnp.arange(3)
self.assertAllClose(f(x), jit(f)(x))
self.assertAllClose(jit(api.vmap(f))(xs), api.vmap(f)(xs))
self.assertAllClose(api.vmap(jit(f))(xs), api.vmap(f)(xs))
def test_sequential_vmap_basic(self):
@jax.custom_batching.sequential_vmap
def f(x):
return x + 1.
def vmap_ref(xs):
return lax.map(f, xs)
xs = jnp.arange(3.)
jaxpr = api.make_jaxpr(api.vmap(f))(xs)
jaxpr_ref = api.make_jaxpr(vmap_ref)(xs)
self.assertEqual(str(jaxpr), str(jaxpr_ref))
def test_sequential_vmap_nary_same_batching(self):
@jax.custom_batching.sequential_vmap
def f(x, y):
return x + y
def vmap_ref(xs, ys):
return lax.map(lambda args: f(*args), (xs, ys))
xs, ys = jnp.arange(3.), 4. + jnp.arange(3.)
jaxpr = api.make_jaxpr(api.vmap(f))(xs, ys)
jaxpr_ref = api.make_jaxpr(vmap_ref)(xs, ys)
self.assertEqual(str(jaxpr), str(jaxpr_ref))
def test_sequential_vmap_nary_mixed_batching(self):
@jax.custom_batching.sequential_vmap
def f(x, y):
return x + y
def vmap_ref(xs, y):
return lax.map(lambda x: f(x, y), xs)
xs, y = jnp.arange(3.), 4.
jaxpr = api.make_jaxpr(api.vmap(f, in_axes=(0, None)))(xs, y)
jaxpr_ref = api.make_jaxpr(vmap_ref)(xs, y)
self.assertEqual(str(jaxpr), str(jaxpr_ref))
@parameterized.named_parameters(
("0", 0),
("1", 1),
("8", 4),
("12", 8),
("16", 16),
)
def test_batch_map_basic(self, batch_size: int):
def f(x):
self.assertEqual(x.shape, ())
return x**2
x = np.arange(16)
y = jax.lax.map(f, x, batch_size=batch_size)
np.testing.assert_array_equal(y, x**2)
@parameterized.named_parameters(
("0", 0),
("1", 1),
("8", 4),
("12", 8),
("16", 16),
)
def test_batch_map_pytrees(self, batch_size: int):
f = lambda x: {'b': x['a'] ** 2}
inputs = {'a': np.arange(16)}
expected = np.arange(16) ** 2
outputs = jax.lax.map(f, inputs, batch_size=batch_size)
self.assertAllClose(outputs['b'], expected)
outputs = jax.lax.map(
f, inputs, batch_size=batch_size
)
self.assertAllClose(outputs['b'], expected)
def test_batch_divides_axis(self):
def f(t):
x, a = t
self.assertEqual(x.shape, (4,))
return (x + a)**2
x = jax.random.randint(jax.random.key(0), (16, 4), -10, 10)
a = jax.random.randint(jax.random.key(1), (16, 4), -10, 10)
@jax.jit
def g(x, a):
return jax.lax.map(f, (x, a), batch_size=8)
y = g(x, a)
self.assertAllClose(y, (x + a)**2)
def test_undefined_rule(self):
@jax.custom_batching.custom_vmap
def f(x): return jnp.sin(x)
with self.assertRaisesRegex(
AttributeError, "No batching rule defined for custom_vmap function f"):
f(0.5)
def test_kwargs(self):
@jax.custom_batching.custom_vmap
def f(x): return jnp.sin(x)
@f.def_vmap
def rule(axis_size, in_batched, xs):
xs_batched, = in_batched
self.assertEqual(xs_batched, True)
self.assertEqual(axis_size, xs.shape[0])
return jnp.cos(xs), xs_batched
x, xs = jnp.array(1.), jnp.arange(3)
y = f(x=x)
self.assertAllClose(y, jnp.sin(x))
ys = api.vmap(f)(x=xs)
self.assertAllClose(ys, jnp.cos(xs))
def test_partial_eval_raises(self):
@jax.custom_batching.custom_vmap
def f(x):
return jnp.sin(x)
@f.def_vmap
def rule(axis_size, in_batched, xs):
del axis_size # unused
return jnp.cos(xs), in_batched[0]
with self.assertRaisesRegex(
ValueError,
"Linearization failed to produce known values for all output primals",
):
jax.grad(f)(0.5)
def test_compose_custom_vjp(self):
@jax.custom_vjp
@jax.custom_batching.custom_vmap
def f(x, y):
return jnp.sin(x) * y
@f.def_vmap
def f_vmap_rule(axis_size, in_batched, xs, ys):
return jnp.cos(xs) * ys, True
def f_fwd(x, y):
return f(x, y), (jnp.cos(x), jnp.sin(x), y)
def f_bwd(res, g):
cos_x, sin_x, y = res
return (cos_x * g * y, sin_x * g)
f.defvjp(f_fwd, f_bwd)
xs = jnp.linspace(0, 1, 5)
ys = jnp.linspace(-0.1, 0.1, 5)
self.assertAllClose(jax.vmap(f)(xs, ys), jnp.cos(xs) * ys)
jax.grad(f)(xs[0], ys[0]) # Doesn't crash.
def test_compose_custom_vjp_bwd_rule(self):
# This tests the case where both the forward and backward rules are wrapped
# in custom_vmap.
@jax.custom_batching.sequential_vmap
def fun_fwd(x, y):
return jnp.sin(x) * y, (x, y)
@jax.custom_batching.sequential_vmap
def fun_bwd(res, ct):
x, y = res
return x * ct, y * ct
fun = jax.custom_vjp(lambda *args: fun_fwd(*args)[0])
fun.defvjp(fun_fwd, fun_bwd)
xs = jnp.linspace(0, 1, 5)
y = jnp.array(0.5, dtype=xs.dtype)
f = jax.vmap(jax.jit(fun), in_axes=(0, None))
out, f_vjp = jax.vjp(f, xs, y)
f_vjp(out) # Doesn't crash.
def test_resolve_kwargs_error_message(self):
@jax.custom_batching.custom_vmap
def f(x, y, *, z=None):
return jnp.sin(x) * y
@f.def_vmap
def f_vmap_rule(axis_size, in_batched, xs, ys):
self.fail("should not be executed")
with self.assertRaisesRegex(
TypeError,
r"The input arguments to the custom_vmap-decorated function f(.*)\n"
r"missing a required argument: 'y'"
):
f(0.5)
with self.assertRaisesRegex(
TypeError,
r"The input arguments to the custom_vmap-decorated function f(.*)\n"
"The following keyword arguments could not be resolved to positions: z"
):
f(0.5, 0.1, z=1.0)
class CustomApiTest(jtu.JaxTestCase):
"""Test interactions among the custom_{vmap,jvp,vjp,transpose,*} APIs"""
def test_method_forwarding(self):
@jax.custom_batching.custom_vmap
@jax.custom_jvp
@jax.custom_transpose.custom_transpose
def f(x): return 2. * x
# none of these err:
@f.def_vmap
def f_batch(sz, b, xs): return 2. * xs
@f.defjvp
def f_jvp(x, tx): return 2. * x, 2. * tx
@f.def_transpose
def f_transpose(x): return 2. * x
def test_def_method_forwarding_all_permutations(self):
for wraps in it.permutations([
jax.custom_jvp, jax.custom_transpose.custom_transpose, jax.custom_batching.custom_vmap]):
f = lambda x: x + 1.
for wrap in wraps:
f = wrap(f)
for methods in it.permutations(['defjvp', 'def_vmap', 'def_transpose']):
for method in methods:
self.assertIsInstance(getattr(f, method), Callable)
for decorators in it.permutations([
jax.custom_vjp, jax.custom_transpose.custom_transpose, jax.custom_batching.custom_vmap]):
f = lambda x: x + 1.
for decorator in decorators:
f = decorator(f)
for methods in it.permutations(['defvjp', 'def_vmap', 'def_transpose']):
for method in methods:
self.assertIsInstance(getattr(f, method), Callable)
if __name__ == '__main__':
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/custom_api_test.py",
"license": "Apache License 2.0",
"lines": 3968,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/custom_partitioning_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import numpy as np
from functools import partial
from absl.testing import absltest
import jax
import jax.numpy as jnp
from jax import P
from jax._src import test_util as jtu
from jax._src import config
from jax._src.named_sharding import NamedSharding
from jax.experimental.custom_partitioning import (
custom_partitioning, SdyShardingRule, BATCHING)
config.parse_flags_with_absl()
jtu.request_cpu_devices(8)
@jtu.pytest_mark_if_available('multiaccelerator')
class CustomPartitionerTest(jtu.JaxTestCase):
def skip_if_custom_partitioning_not_supported(self):
if jtu.is_cloud_tpu():
raise unittest.SkipTest("Custom partitioning is not supported on libtpu.")
@jtu.skip_on_devices('cpu') # Collectives don't seem to work on CPU.
def test_custom_partitioner(self):
self.skip_if_custom_partitioning_not_supported()
def partition(precision, mesh, arg_shapes, result_shape):
arg_shardings = jax.tree.map(lambda s: s.sharding, arg_shapes)
result_sharding = result_shape[0].sharding
self.assertEqual(arg_shardings[0], result_sharding)
self.assertEqual(P('x', None), result_sharding.spec)
self.assertEqual(P('y', None), arg_shardings[1].spec)
def lower_fn(x, y):
axis_name = arg_shardings[1].spec[0][0]
i = jax.lax.axis_index(axis_name)
# Use offset i * 0 instead of 0 to ensure that the two offsets have the
# same dtype regardless the value of config.enable_x64.
z = jax.lax.psum(
jax.lax.dynamic_slice(x, (i * 0, i * 8), (8, 8)) @ y, (axis_name)
)
return z, z * z
return mesh, lower_fn, (result_sharding, result_sharding), arg_shardings
def infer_sharding_from_operands(precision, mesh, arg_shapes, result_shape):
arg_shardings = jax.tree.map(lambda s: s.sharding, arg_shapes)
x_shard, y_shard = arg_shardings
x_shape, y_shape = arg_shapes
x_names = tuple(x_shard.spec) + tuple(
None for _ in range(len(x_shape.shape) - len(x_shard.spec)))
y_names = tuple(y_shard.spec) + tuple(
None for _ in range(len(y_shape.shape) - len(y_shard.spec)))
z_shard = NamedSharding(y_shard.mesh, P(*(x_names[:-1] + y_names[1:])))
return z_shard, z_shard
@partial(custom_partitioning, static_argnums=(2,))
def f(x, y, precision=None):
z = jnp.matmul(x, y, precision=precision)
return z, z * z
f.def_partition(
infer_sharding_from_operands=infer_sharding_from_operands,
partition=partition,
sharding_rule=SdyShardingRule(operand_mappings=(('i', 'j'), ('j', 'k')), result_mappings=(('i', 'k'), ('i', 'k'))))
with jax.set_mesh(jtu.create_mesh((4, 2), ('x', 'y'))):
jit_f = jax.jit(f, in_shardings=(P('x'), P('y')), out_shardings=P('x'))
x = np.asarray(np.random.randint(0, 20, (32, 16)), dtype=np.float32)
y = np.asarray(np.random.randint(0, 20, (16, 32)), dtype=np.float32)
x_sharded = jax.device_put(x, P('x'))
y_sharded = jax.device_put(y, P('y'))
result1 = jax.jit(f)(x_sharded, y_sharded)
result2 = f(x, y)
result0 = jit_f(x_sharded, y_sharded)
self.assertArraysEqual(result0, result1)
self.assertArraysEqual(result1, result2)
def test_custom_partitioner_propagate_user_sharding(self):
self.skip_if_custom_partitioning_not_supported()
def partition(mesh, arg_shapes, result_shape):
def lower_fn(x):
return x
return (
mesh,
lower_fn,
arg_shapes[0].sharding,
(arg_shapes[0].sharding,),
)
def infer_sharding_from_operands(mesh, arg_shapes, result_shape):
return arg_shapes[0].sharding
def propagate_user_sharding(mesh, user_shape):
return user_shape.sharding
@custom_partitioning
def f(x):
return x
f.def_partition(
infer_sharding_from_operands=infer_sharding_from_operands,
partition=partition,
propagate_user_sharding=propagate_user_sharding,
sharding_rule='i j -> i j',
)
def f2(a):
return a + f(a)
with jax.set_mesh(jtu.create_mesh((4, 2), ('x', 'y'))):
jit_f = jax.jit(f2, in_shardings=(P(None, 'x')), out_shardings=P('x'))
x = np.asarray(np.random.randint(0, 20, (32, 16)), dtype=np.float32)
self.assertArraysEqual(x + x, jit_f(jax.device_put(x, P(None, 'x'))))
def test_custom_partitioner_sharding_override(self):
self.skip_if_custom_partitioning_not_supported()
def partition(mesh, arg_shapes, result_shape):
def lower_fn(x):
return x
y_shard = arg_shapes[0].sharding
return (
mesh,
lower_fn,
NamedSharding(y_shard.mesh, P(None)),
(NamedSharding(y_shard.mesh, P(None)),),
)
def infer_sharding_from_operands(mesh, arg_shapes, result_shape):
y_shard = arg_shapes[0].sharding
return NamedSharding(y_shard.mesh, P('x'))
@custom_partitioning
def f(x):
return x
f.def_partition(
infer_sharding_from_operands=infer_sharding_from_operands,
partition=partition,
sharding_rule=SdyShardingRule(operand_mappings=((BATCHING, 'i'),), result_mappings=((BATCHING, 'i'),)))
with jax.set_mesh(jtu.create_mesh((4, 2), ('x', 'y'))):
jit_f = jax.jit(f, in_shardings=(P(None, 'x')), out_shardings=P('x'))
x = np.asarray(np.random.randint(0, 20, (32, 16)), dtype=np.float32)
self.assertArraysEqual(x, jit_f(jax.device_put(x, P(None, 'x'))))
def test_custom_partitioner_invalid_sharding(self):
self.skip_if_custom_partitioning_not_supported()
def partition(mesh, arg_shapes, result_shape):
def lower_fn(x):
return x
y_shard = arg_shapes[0].sharding
return (
mesh,
lower_fn,
NamedSharding(y_shard.mesh, P(None)),
(NamedSharding(y_shard.mesh, P(None, 'x')),),
)
def infer_sharding_from_operands(mesh, arg_shapes, result_shape):
y_shard = arg_shapes[0].sharding
return NamedSharding(y_shard.mesh, P('x'))
@custom_partitioning
def f(x):
return x
f.def_partition(
infer_sharding_from_operands=infer_sharding_from_operands,
partition=partition,
sharding_rule='i j -> i j',
)
with jax.set_mesh(jtu.create_mesh((4, 2), ('x', 'y'))):
jit_f = jax.jit(f, in_shardings=(P(None, 'x')), out_shardings=P('x'))
x = np.asarray(np.random.randint(0, 20, (32, 16)), dtype=np.float32)
with self.assertRaisesRegex(Exception, 'Mismatch in result shapes.'):
jit_f(jax.device_put(x, P(None, 'x'))).block_until_ready()
def test_custom_partitioner_jit_annotated_function(self):
"""Test correct lowering of function with a @jax.jit annotated callee.
Annotating a callee with @jax.jit results in a module with a HLO CallOp.
This test is makes sure that the custom partitioner lowering supports
CallOps.
"""
self.skip_if_custom_partitioning_not_supported()
@custom_partitioning
def f(x):
return x
def partition(mesh, arg_shapes, result_shape):
def lower_fn(x):
@jax.jit
def g(y):
return y
return g(x)
x_shard = arg_shapes[0].sharding
return (
mesh,
lower_fn,
NamedSharding(x_shard.mesh, P('x')),
(NamedSharding(x_shard.mesh, P('x')),),
)
def infer_sharding_from_operands(mesh, arg_shapes, result_shape):
x_shard = arg_shapes[0].sharding
return NamedSharding(x_shard.mesh, P('x'))
f.def_partition(
infer_sharding_from_operands=infer_sharding_from_operands,
partition=partition,
sharding_rule='i -> i',
)
with jax.set_mesh(jtu.create_mesh((4,), ('x',))):
jit_f = jax.jit(f)
x = np.asarray(np.random.randint(0, 20, (32,)), dtype=np.float32)
jit_f = jax.jit(jit_f, in_shardings=(P('x')), out_shardings=P('x'))
self.assertArraysEqual(x, jit_f(jax.device_put(x, P('x'))))
def test_custom_partitioner_with_scan(self):
self.skip_if_custom_partitioning_not_supported()
# This is a reproducer from https://github.com/jax-ml/jax/issues/20864.
@custom_partitioning
def f(x):
return jnp.sum(x)
def partition(mesh, arg_shapes, result_shape):
def lower_fn(xs):
def f(carry, x):
return carry + jax.lax.psum(jnp.sum(x), axis_name='x'), None
carry, _ = jax.lax.scan(f, 0, xs)
return carry
result_shardings = jax.tree.map(lambda x: x.sharding, result_shape)
arg_shardings = jax.tree.map(lambda x: x.sharding, arg_shapes)
return mesh, lower_fn, result_shardings, arg_shardings
f.def_partition(
partition,
infer_sharding_from_operands=lambda mesh, *_: NamedSharding(mesh, P()),
propagate_user_sharding=lambda _, user_shape: user_shape.sharding,
sharding_rule='i j -> ') # Result is a scalar.
with jax.set_mesh(jtu.create_mesh((4,), ('x',))):
jit_f = jax.jit(f, in_shardings=P(None, 'x'))
xs = jax.device_put(jnp.ones([32, 16]), P(None, 'x'))
self.assertEqual(jit_f(xs), xs.sum())
def test_custom_partitioning_no_mesh_context(self):
self.skip_if_custom_partitioning_not_supported()
@custom_partitioning
def f(x):
return x
def partition(mesh, arg_shapes, result_shape):
def lower_fn(x):
@jax.jit
def g(y):
return y
return g(x)
x_shard = arg_shapes[0].sharding
return (
mesh,
lower_fn,
NamedSharding(x_shard.mesh, P('x')),
(NamedSharding(x_shard.mesh, P('x')),),
)
def infer_sharding_from_operands(mesh, arg_shapes, result_shape):
x_shard = arg_shapes[0].sharding
return NamedSharding(x_shard.mesh, P('x'))
f.def_partition(
infer_sharding_from_operands=infer_sharding_from_operands,
partition=partition,
sharding_rule='i -> i',
)
mesh = jtu.create_mesh((4,), ('x',))
x = np.asarray(np.random.randint(0, 20, (32,)), dtype=np.float32)
s = NamedSharding(mesh, P('x'))
jit_f = jax.jit(f, in_shardings=s, out_shardings=s)
self.assertArraysEqual(x, jit_f(x))
def test_custom_partitioner_pytree_inputs(self):
self.skip_if_custom_partitioning_not_supported()
def partition(mesh, arg_shapes, result_shape):
def lower_fn(xs):
x, y, z = xs
return x + y + z
return (
mesh,
lower_fn,
arg_shapes[0][0].sharding,
jax.tree.map(lambda x: x.sharding, arg_shapes),
)
def infer_sharding_from_operands(mesh, arg_shapes, result_shape):
return arg_shapes[0][0].sharding
def propagate_user_sharding(mesh, user_shape):
return user_shape.sharding
@custom_partitioning
def f(xs):
x, y, z = xs
return x + y + z
f.def_partition(
infer_sharding_from_operands=infer_sharding_from_operands,
partition=partition,
propagate_user_sharding=propagate_user_sharding,
sharding_rule='i j, i j, i j -> i j',
)
def f2(a):
return a + f((a, a, a))
with jax.set_mesh(jtu.create_mesh((4, 2), ('x', 'y'))):
jit_f = jax.jit(f2, in_shardings=(P(None, 'x')), out_shardings=P('x'))
x = np.asarray(np.random.randint(0, 20, (32, 16)), dtype=np.float32)
self.assertArraysEqual(x * 4, jit_f(jax.device_put(x, P(None, 'x'))))
@jtu.skip_on_devices('cpu')
def test_custom_partition_with_sharding_rule_callback(self):
self.skip_if_custom_partitioning_not_supported()
def partition(static_arg0, static_arg1, mesh, arg_shapes, result_shape):
arg_shardings = jax.tree.map(lambda s: s.sharding, arg_shapes)
result_sharding = result_shape.sharding
rank = len(arg_shapes[0].shape)
self.assertEqual(static_arg0, 1)
self.assertEqual(static_arg1, 2)
def lower_fn(x, y):
axis_name = arg_shardings[1].spec[rank-2][0]
i = jax.lax.axis_index(axis_name)
z = jax.lax.psum(jax.lax.dynamic_slice_in_dim(
jax.lax.dynamic_slice_in_dim(x, i * 0, 8, axis=rank-2),
i * 8, 8, axis=rank-1) @ y, (axis_name))
return z
return mesh, lower_fn, (result_sharding), arg_shardings
def produce_sharding_rule(static_arg0, static_arg1, mesh, arg_shapes, result_shape):
self.assertEqual(static_arg0, 1)
self.assertEqual(static_arg1, 2)
rank = len(arg_shapes[0].shape)
leading_axes = ""
for i in range(rank - 2):
leading_axes += f" b{i}"
return f"{leading_axes} i j, {leading_axes} j k -> {leading_axes} i k" , dict(reduction_factors=("j",))
@partial(custom_partitioning, static_argnums=(2,3))
def f(x, y, static_arg0=1, static_arg1=2):
return jnp.matmul(x, y)
f.def_partition(
infer_sharding_from_operands=None,
partition=partition,
sharding_rule=produce_sharding_rule)
mesh = jtu.create_mesh((4, 2), ('x', 'y'))
x = jax.device_put(np.arange(2 * 3 * 32 * 16).reshape(2, 3, 32, 16),
NamedSharding(mesh, P(None, None, 'x')))
y = jax.device_put(np.arange(2 * 3 * 16 * 32).reshape(2, 3, 16, 32),
NamedSharding(mesh, P(None, None,'y')))
result = jax.jit(f)(x, y)
expected_result = f(x, y)
self.assertArraysEqual(result, expected_result)
self.assertEqual(result.sharding, NamedSharding(mesh, P(None, None, 'x')))
def test_custom_partition_shardy_migration(self):
self.skip_if_custom_partitioning_not_supported()
def partition(mesh, arg_shapes, result_shape):
def lower_fn(x):
return x
return (
mesh,
lower_fn,
arg_shapes[0].sharding,
(arg_shapes[0].sharding,),
)
def infer_sharding_from_operands(mesh, arg_shapes, result_shape):
return arg_shapes[0].sharding
def propagate_user_sharding(mesh, user_shape):
return user_shape.sharding
@custom_partitioning
def f(x):
return x
f.def_partition(
infer_sharding_from_operands=infer_sharding_from_operands,
partition=partition,
propagate_user_sharding=propagate_user_sharding,
)
mesh = jtu.create_mesh((4, 2), ('x', 'y'))
x = jax.device_put(np.arange(32 * 16).reshape(32, 16),
NamedSharding(mesh, P(None, 'x')))
with self.assertRaisesRegex(
NotImplementedError, 'provide sharding_rule to migrate to Shardy'):
jax.jit(f)(x)
def test_custom_partitioner_reshape(self):
self.skip_if_custom_partitioning_not_supported()
def partition(mesh, arg_shapes, result_shape):
arg_shardings = jax.tree.map(lambda s: s.sharding, arg_shapes)
result_sharding = result_shape.sharding
def lower_fn(x, y):
return x.reshape((4,)) + y
return mesh, lower_fn, (result_sharding), arg_shardings
@partial(custom_partitioning)
def f(x, y):
x = x.reshape((8,))
return x + y
f.def_partition(
infer_sharding_from_operands=None,
propagate_user_sharding=None,
partition=partition,
sharding_rule='(i k) j, (i k j) -> (i k j)', i=2, k=2, need_replication_factors=('k',))
mesh = jtu.create_mesh((2, 4), ('x', 'y'))
x = jax.device_put(np.arange(8).reshape(4, 2),
NamedSharding(mesh, P('x', None)))
y = jax.device_put(np.arange(8),
NamedSharding(mesh, P('x')))
jitted_result = jax.jit(f)(x, y)
unjitted_result = f(x, y)
self.assertArraysEqual(jitted_result, unjitted_result)
self.assertEqual(jitted_result.sharding, NamedSharding(mesh, P('x')))
if __name__ == '__main__':
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/custom_partitioning_test.py",
"license": "Apache License 2.0",
"lines": 385,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/documentation_coverage_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test that public APIs are correctly documented."""
import collections
from collections.abc import Iterator, Mapping, Sequence
import importlib
import functools
import os
import pkgutil
import warnings
from absl.testing import absltest
from absl.testing import parameterized
import jax
import jax._src.test_util as jtu
from jax._src import config
config.parse_flags_with_absl()
CURRENTMODULE_TAG = '.. currentmodule::'
AUTOMODULE_TAG = '.. automodule::'
AUTOSUMMARY_TAG = '.. autosummary::'
AUTOCLASS_TAG = '.. autoclass::'
@functools.lru_cache()
def jax_docs_dir() -> str:
"""Return the string or path object pointing to the JAX docs."""
try:
# In bazel, access docs files via data dependencies of a jax.docs package.
return importlib.resources.files('jax.docs')
except ImportError:
# Outside of bazel, assume code is layed out as in the github repository, where
# the docs and tests subdirectories are both within the same top-level directory.
return os.path.abspath(os.path.join(__file__, os.pardir, os.pardir, "docs"))
UNDOCUMENTED_APIS = {
'jax': ['empty_ref', 'NamedSharding', 'P', 'Ref', 'Shard', 'reshard', 'ad_checkpoint', 'api_util', 'checkpoint_policies', 'core', 'custom_derivatives', 'custom_transpose', 'debug_key_reuse', 'device_put_replicated', 'device_put_sharded', 'effects_barrier', 'example_libraries', 'explain_cache_misses', 'experimental', 'extend', 'float0', 'free_ref', 'freeze', 'fwd_and_bwd', 'host_count', 'host_id', 'host_ids', 'interpreters', 'jax', 'jax2tf_associative_scan_reductions', 'legacy_prng_key', 'lib', 'make_user_context', 'new_ref', 'no_execution', 'numpy_dtype_promotion', 'remat', 'remove_size_one_mesh_axis_from_type', 'softmax_custom_jvp', 'threefry_partitionable', 'thread_guard', 'tools', 'transfer_guard_device_to_device', 'transfer_guard_device_to_host', 'transfer_guard_host_to_device', 'version', 'allow_f16_reductions'],
'jax.ref': ['empty_ref', 'free_ref'],
'jax.ad_checkpoint': ['checkpoint', 'checkpoint_policies', 'print_saved_residuals', 'remat', 'Offloadable', 'Recompute', 'Saveable'],
'jax.custom_batching': ['custom_vmap', 'sequential_vmap'],
'jax.custom_derivatives': ['CustomVJPPrimal', 'SymbolicZero', 'closure_convert', 'custom_gradient', 'custom_jvp', 'custom_jvp_call_p', 'custom_vjp', 'custom_vjp_call_p', 'custom_vjp_primal_tree_values', 'linear_call', 'remat_opt_p', 'zero_from_primal'],
'jax.custom_transpose': ['custom_transpose'],
'jax.debug': ['DebugEffect', 'log'],
'jax.distributed': ['is_initialized'],
'jax.dtypes': ['extended', 'finfo', 'iinfo'],
'jax.ffi': ['build_ffi_lowering_function', 'include_dir', 'register_ffi_target_as_batch_partitionable', 'register_ffi_type_id'],
'jax.lax': ['pcast', 'unreduced_psum', 'dce_sink', 'conv_transpose_shape_tuple', 'reduce_window_shape_tuple', 'conv_general_permutations', 'conv_general_shape_tuple', 'pbroadcast', 'padtype_to_pads', 'conv_shape_tuple', 'unreduced_psum_scatter', 'create_token', 'dtype', 'shape_as_value', 'all_gather_reduced', 'pvary', 'all_gather_start', 'all_gather_done', *(name for name in dir(jax.lax) if name.endswith('_p'))],
'jax.lax.linalg': [api for api in dir(jax.lax.linalg) if api.endswith('_p')],
'jax.memory': ['Space'],
'jax.monitoring': ['clear_event_listeners', 'record_event', 'record_event_duration_secs', 'record_event_time_span', 'record_scalar', 'register_event_duration_secs_listener', 'register_event_listener', 'register_event_time_span_listener', 'register_scalar_listener', 'unregister_event_duration_listener', 'unregister_event_listener', 'unregister_event_time_span_listener', 'unregister_scalar_listener'],
'jax.numpy': ['bfloat16', 'bool', 'e', 'euler_gamma', 'float4_e2m1fn', 'float8_e3m4', 'float8_e4m3', 'float8_e4m3b11fnuz', 'float8_e4m3fn', 'float8_e4m3fnuz', 'float8_e5m2', 'float8_e5m2fnuz', 'float8_e8m0fnu', 'inf', 'int1', 'int2', 'int4', 'nan', 'newaxis', 'pi', 'uint1', 'uint2', 'uint4'],
'jax.profiler': ['ProfileData', 'ProfileEvent', 'ProfileOptions', 'ProfilePlane', 'stop_server'],
'jax.random': ['key_impl', 'random_gamma_p'],
'jax.scipy.special': ['bessel_jn', 'sph_harm_y'],
'jax.sharding': ['AbstractDevice', 'AbstractMesh', 'AxisType', 'auto_axes', 'explicit_axes', 'get_abstract_mesh', 'reshard', 'set_mesh', 'use_abstract_mesh', 'get_mesh'],
'jax.stages': ['ArgInfo', 'CompilerOptions'],
'jax.tree_util': ['DictKey', 'FlattenedIndexKey', 'GetAttrKey', 'PyTreeDef', 'SequenceKey', 'default_registry'],
}
# A list of modules to skip entirely, either because they cannot be imported
# or because they are not expected to be documented.
MODULES_TO_SKIP = [
"jax.api_util", # internal tools, not documented.
"jax.cloud_tpu_init", # deprecated in JAX v0.8.1
"jax.collect_profile", # fails when xprof is not available.
"jax.core", # internal tools, not documented.
"jax.example_libraries", # TODO(jakevdp): un-skip these.
"jax.extend.backend",
"jax.extend.core.primitives",
"jax.extend.ifrt_programs",
"jax.extend.mlir",
"jax.extend.mlir.dialects",
"jax.extend.mlir.ir",
"jax.extend.mlir.passmanager",
"jax.extend.sharding",
"jax.extend.source_info_util",
"jax.experimental", # Many non-public submodules.
"jax.interpreters", # internal tools, not documented.
"jax.jaxlib", # internal tools, not documented.
"jax.lib", # deprecated in JAX v0.8.0
"jax.tools", # internal tools, not documented.
"jax.version", # no public APIs.
]
def extract_apis_from_rst_file(path: str) -> dict[str, list[str]]:
"""Extract documented APIs from an RST file."""
# We could do this more robustly by adding a docutils dependency, but that is
# pretty heavy. Instead we use simple string-based file parsing, recognizing the
# particular patterns used within the JAX documentation.
currentmodule: str = '<none>'
in_autosummary_block = False
apis = collections.defaultdict(list)
with open(path, 'r') as f:
for line in f:
stripped_line = line.strip()
if not stripped_line:
continue
if line.startswith(CURRENTMODULE_TAG):
currentmodule = line.removeprefix(CURRENTMODULE_TAG).strip()
continue
if line.startswith(AUTOMODULE_TAG):
currentmodule = line.removeprefix(AUTOMODULE_TAG).strip()
continue
if line.startswith(AUTOCLASS_TAG):
in_autosummary_block = False
apis[currentmodule].append(line.removeprefix(AUTOCLASS_TAG).strip())
continue
if line.startswith(AUTOSUMMARY_TAG):
in_autosummary_block = True
continue
if not in_autosummary_block:
continue
if not line.startswith(' '):
in_autosummary_block = False
continue
if stripped_line.startswith(':'):
continue
apis[currentmodule].append(stripped_line)
return dict(apis)
@functools.lru_cache()
def get_all_documented_jax_apis() -> Mapping[str, list[str]]:
"""Get the list of APIs documented in all files in a directory (recursive)."""
path = jax_docs_dir()
apis = collections.defaultdict(list)
for root, _, files in os.walk(path):
if (root.startswith(os.path.join(path, 'build'))
or root.startswith(os.path.join(path, '_autosummary'))):
continue
for filename in files:
if filename.endswith('.rst'):
new_apis = extract_apis_from_rst_file(os.path.join(root, filename))
for key, val in new_apis.items():
apis[key].extend(val)
return {key: sorted(vals) for key, vals in apis.items()}
@functools.lru_cache()
def list_public_jax_modules() -> Sequence[str]:
"""Return a list of the public modules defined in jax."""
# We could use pkgutil.walk_packages, but we want to avoid traversing modules
# like `jax._src`, `jax.example_libraries`, etc. so we implement it manually.
def walk_public_modules(paths: list[str], parent_package: str) -> Iterator[str]:
for info in pkgutil.iter_modules(paths):
pkg_name = f"{parent_package}.{info.name}"
if pkg_name in MODULES_TO_SKIP or info.name == 'tests' or info.name.startswith('_'):
continue
yield pkg_name
if not info.ispkg:
continue
try:
submodule = importlib.import_module(pkg_name)
except ImportError as e:
warnings.warn(f"failed to import {pkg_name}: {e!r}")
else:
if path := getattr(submodule, '__path__', None):
yield from walk_public_modules(path, pkg_name)
return [jax.__name__, *walk_public_modules(jax.__path__, jax.__name__)]
@functools.lru_cache()
def list_public_apis(module_name: str) -> Sequence[str]:
"""Return a list of public APIs within a specified module.
This will import the module as a side-effect.
"""
module = importlib.import_module(module_name)
return [api for api in dir(module)
if not api.startswith('_') # skip private members
and not api.startswith('@') # skip injected pytest-related symbols
]
@functools.lru_cache()
def get_all_public_jax_apis() -> Mapping[str, list[str]]:
"""Return a dictionary mapping jax submodules to their list of public APIs."""
apis = {}
for module in list_public_jax_modules():
try:
apis[module] = list_public_apis(module)
except ImportError as e:
warnings.warn(f"failed to import {module}: {e}")
return apis
class DocumentationCoverageTest(jtu.JaxTestCase):
def setUp(self):
if jtu.runtime_environment() == 'bazel':
self.skipTest("Skipping test in bazel, because rst docs aren't accessible.")
def test_list_public_jax_modules(self):
"""Simple smoke test for list_public_jax_modules()"""
apis = list_public_jax_modules()
# A few submodules which should be included
self.assertIn("jax", apis)
self.assertIn("jax.numpy", apis)
self.assertIn("jax.numpy.linalg", apis)
# A few submodules which should not be included
self.assertNotIn("jax._src", apis)
self.assertNotIn("jax._src.numpy", apis)
self.assertNotIn("jax.example_libraries", apis)
self.assertNotIn("jax.experimental.jax2tf", apis)
def test_list_public_apis(self):
"""Simple smoketest for list_public_apis()"""
jnp_apis = list_public_apis('jax.numpy')
self.assertIn("array", jnp_apis)
self.assertIn("zeros", jnp_apis)
self.assertNotIn("jax.numpy.array", jnp_apis)
self.assertNotIn("np", jnp_apis)
self.assertNotIn("jax", jnp_apis)
def test_get_all_public_jax_apis(self):
"""Simple smoketest for get_all_public_jax_apis()"""
apis = get_all_public_jax_apis()
self.assertIn("Array", apis["jax"])
self.assertIn("array", apis["jax.numpy"])
self.assertIn("eigh", apis["jax.numpy.linalg"])
def test_extract_apis_from_rst_file(self):
"""Simple smoketest for extract_apis_from_rst_file()"""
numpy_docs = os.path.join(jax_docs_dir(), "jax.numpy.rst")
apis = extract_apis_from_rst_file(numpy_docs)
self.assertIn("jax.numpy", apis.keys())
self.assertIn("jax.numpy.linalg", apis.keys())
self.assertIn("array", apis["jax.numpy"])
self.assertIn("asarray", apis["jax.numpy"])
self.assertIn("eigh", apis["jax.numpy.linalg"])
self.assertNotIn("jax", apis["jax.numpy"])
self.assertNotIn("jax.numpy", apis["jax.numpy"])
def test_get_all_documented_jax_apis(self):
"""Simple smoketest of get_all_documented_jax_apis()"""
apis = get_all_documented_jax_apis()
self.assertIn("Array", apis["jax"])
self.assertIn("arange", apis["jax.numpy"])
self.assertIn("eigh", apis["jax.lax.linalg"])
@parameterized.parameters(list_public_jax_modules())
def test_module_apis_documented(self, module):
"""Test that the APIs in each module are appropriately documented."""
public_apis = get_all_public_jax_apis()
documented_apis = get_all_documented_jax_apis()
pub_apis = {f"{module}.{api}" for api in public_apis.get(module, ())}
doc_apis = {f"{module}.{api}" for api in documented_apis.get(module, ())}
undoc_apis = {f"{module}.{api}" for api in UNDOCUMENTED_APIS.get(module, ())}
# Remove submodules from list.
pub_apis -= public_apis.keys()
pub_apis -= set(MODULES_TO_SKIP)
if (notempty := undoc_apis & doc_apis):
raise ValueError(
f"Found stale values in the UNDOCUMENTED_APIS list: {notempty}."
" If this fails, the fix is typically to remove the offending entries"
" from the UNDOCUMENTED_APIS mapping.")
if (notempty := pub_apis - doc_apis - undoc_apis):
raise ValueError(
f"Found public APIs that are not listed within docs: {notempty}."
" If this fails, it likely means a new public API has been added to the"
" jax package without an associated entry in docs/*.rst. To fix this,"
" either add the missing documentation entries, or add these names to the"
" UNDOCUMENTED_APIS mapping to indicate it is deliberately undocumented.")
if __name__ == "__main__":
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/documentation_coverage_test.py",
"license": "Apache License 2.0",
"lines": 251,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/filecheck/jax_mlir_ext.filecheck.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# RUN: %PYTHON %s | FileCheck %s -dump-input=always
from absl import app
import jax
from jax._src.interpreters import mlir
from jax._src.lib.mlir import ir
from jax._src.lib.mlir import passmanager
from jax._src.lib.mlir.dialects import func as func_dialect
from jax._src.lib.mlir.dialects import hlo
from jaxlib.mlir._mlir_libs import _jax_mlir_ext
import numpy as np
jax.config.parse_flags_with_absl()
def test_inlined_func_call():
# CHECK: #loc = loc(unknown)
# CHECK: module {
# CHECK-NEXT: func.func public @caller(%arg0: tensor<2x3xf32> loc(unknown), %arg1: tensor<2x3xf32> loc(unknown)) -> (tensor<2x3xf32>, tensor<2x3xf32>) {
# CHECK-NEXT: %0 = stablehlo.add %arg1, %arg0 : tensor<2x3xf32> loc(#loc8)
# CHECK-NEXT: %1 = stablehlo.multiply %0, %arg1 : tensor<2x3xf32> loc(#loc9)
# CHECK-NEXT: return %0, %1 : tensor<2x3xf32>, tensor<2x3xf32> loc(#loc)
# CHECK-NEXT: } loc(#loc)
# CHECK-NEXT: } loc(#loc)
# CHECK-NEXT: #loc1 = loc("callee_file":1:2)
# CHECK-NEXT: #loc2 = loc("caller_file":3:4)
# CHECK-NEXT: #loc3 = loc("callee_stack"(#loc1))
# CHECK-NEXT: #loc4 = loc("caller_stack"(#loc2))
# CHECK-NEXT: #loc5 = loc(callsite(#loc3 at #loc4))
# CHECK-NEXT: #loc6 = loc("caller_name/callee_name1"(#loc5))
# CHECK-NEXT: #loc7 = loc("caller_name/callee_name2"(#loc5))
# CHECK-NEXT: #loc8 = loc("caller_type:"(#loc6))
# CHECK-NEXT: #loc9 = loc("caller_type:"(#loc7))
ctx = mlir.make_ir_context()
loc = ir.Location.unknown(context=ctx)
aval = jax.core.ShapedArray((2, 3), np.dtype(np.float32))
arg_avals = [aval, aval]
result_avals = [aval, aval]
with ctx, loc:
callee_stack_loc = ir.Location.name(
"callee_stack", ir.Location.file("callee_file", 1, 2)
)
callee_loc1 = ir.Location.name(
"callee_name1", ir.Location.name("callee_type1:", callee_stack_loc)
)
callee_loc2 = ir.Location.name(
"callee_name2", ir.Location.name("callee_type2:", callee_stack_loc)
)
caller_stack_loc = ir.Location.name(
"caller_stack", ir.Location.file("caller_file", 3, 4)
)
caller_loc = ir.Location.name(
"caller_name", ir.Location.name("caller_type:", caller_stack_loc)
)
module = ir.Module.create(loc=ir.Location.unknown())
ip = ir.InsertionPoint(module.body)
arg_types = [mlir.aval_to_ir_type(aval) for aval in arg_avals]
result_types = [mlir.aval_to_ir_type(aval) for aval in result_avals]
ftype = ir.FunctionType.get(arg_types, result_types)
callee = func_dialect.FuncOp("callee", ftype, ip=ip)
callee.attributes["sym_visibility"] = ir.StringAttr.get("private")
entry_block = callee.add_entry_block()
with ir.InsertionPoint(entry_block):
with callee_loc1:
x = hlo.add(entry_block.arguments[0], entry_block.arguments[1])
with callee_loc2:
y = hlo.multiply(x, entry_block.arguments[0])
func_dialect.ReturnOp([x, y])
caller = func_dialect.FuncOp("caller", ftype, ip=ip)
caller.attributes["sym_visibility"] = ir.StringAttr.get("public")
entry_block = caller.add_entry_block()
with ir.InsertionPoint(entry_block):
x, y = entry_block.arguments
with caller_loc:
x, y = _jax_mlir_ext.inlined_func_call(callee, [y, x], entry_block)
func_dialect.ReturnOp([x, y])
module.operation.verify()
pipeline = passmanager.PassManager.parse("builtin.module(symbol-dce)")
pipeline.run(module.operation)
print(module.operation.print(enable_debug_info=True))
def test_traceback_to_location():
def f():
return g()
def g():
return h()
def h():
return jax._src.lib._jax.Traceback.get_traceback()
tb = f()
def _code_to_filename(code):
return (
"jax_mlir_ext_test.filecheck.py"
if "jax_mlir_ext.filecheck" in code.co_filename
else None
)
# CHECK: --- test_traceback_to_location
print("--- test_traceback_to_location")
ctx = mlir.make_ir_context()
with ctx:
# CHECK: loc(callsite("test_traceback_to_location.<locals>.h"("jax_mlir_ext_test.filecheck.py":{{[0-9]+}}:{{[0-9]+}} to :{{[0-9]+}}) at callsite("test_traceback_to_location.<locals>.g"("jax_mlir_ext_test.filecheck.py":{{[0-9]+}}:{{[0-9]+}} to :{{[0-9]+}}) at callsite("test_traceback_to_location.<locals>.f"("jax_mlir_ext_test.filecheck.py":{{[0-9]+}}:{{[0-9]+}} to :{{[0-9]+}}) at callsite("test_traceback_to_location"("jax_mlir_ext_test.filecheck.py":{{[0-9]+}}:{{[0-9]+}} to :{{[0-9]+}}) at callsite("main"("jax_mlir_ext_test.filecheck.py":{{[0-9]+}}:{{[0-9]+}} to :{{[0-9]+}}) at "<module>"("jax_mlir_ext_test.filecheck.py":{{[0-9]+}}:{{[0-9]+}} to :{{[0-9]+}})))))))
cache = _jax_mlir_ext.TracebackToLocationCache(
code_to_filename=_code_to_filename, frame_limit=1000)
loc = cache.get(tb)
print(loc)
# CHECK: loc(callsite("test_traceback_to_location.<locals>.h"("jax_mlir_ext_test.filecheck.py":{{[0-9]+}}:{{[0-9]+}} to :{{[0-9]+}}) at "test_traceback_to_location.<locals>.g"("jax_mlir_ext_test.filecheck.py":{{[0-9]+}}:{{[0-9]+}} to :{{[0-9]+}})))
cache = _jax_mlir_ext.TracebackToLocationCache(
code_to_filename=_code_to_filename, frame_limit=2)
loc = cache.get(tb)
print(loc)
def main(_):
test_inlined_func_call()
test_traceback_to_location()
if __name__ == "__main__":
app.run(main)
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/filecheck/jax_mlir_ext.filecheck.py",
"license": "Apache License 2.0",
"lines": 122,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/fused_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from absl.testing import absltest
import jax
import jax.numpy as jnp
from jax._src import test_util as jtu
from jax.experimental.fused import fused
jax.config.parse_flags_with_absl()
@fused(out_spaces=(jax.memory.Space.Host, jax.memory.Space.Device))
def f(x, y):
z = x + y
w = x * y
return z, w
class FusedTest(jtu.JaxTestCase):
def test_basic(self):
x = jnp.arange(3.)
x_host = jax.device_put(x, jax.memory.Space.Host)
y_device = jnp.arange(3.)
low = jax.jit(f).trace(x_host, y_device).lower(lowering_platforms=('cuda',))
txt = low._lowering.hlo().as_hlo_module().to_string()
self.assertIn('custom_call', txt)
self.assertIn('inlineable', txt)
self.assertIn('MUST_FUSE', txt)
self.assertIn('out_spaces', txt)
def test_vmap_basic(self):
x = jnp.arange(3.)
x_host = jax.device_put(x, jax.memory.Space.Host)
y_device = jnp.arange(3.)
f_ = jax.jit(jax.vmap(f))
f_.trace(x_host, y_device).lower(lowering_platforms=('cuda',)) # don't crash
def test_jvp_basic(self):
x = jnp.arange(3.)
x_host = jax.device_put(x, jax.memory.Space.Host)
y_device = jnp.arange(3.)
f_ = jax.jit(lambda x, y: jax.jvp(f, (x, y), (x, y)))
f_.trace(x_host, y_device).lower(lowering_platforms=('cuda',)) # don't crash
def test_grad_basic(self):
x = jnp.arange(3.)
x_host = jax.device_put(x, jax.memory.Space.Host)
y_device = jnp.arange(3.)
f_ = jax.jit(jax.grad(lambda x, y: f(x, y)[1].sum()))
f_.trace(x_host, y_device).lower(lowering_platforms=('cuda',)) # don't crash
if __name__ == '__main__':
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/fused_test.py",
"license": "Apache License 2.0",
"lines": 55,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/hijax_test.py | # Copyright 2024 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
from contextlib import contextmanager
from dataclasses import dataclass
from functools import partial
import itertools as it
from typing import Any
import unittest
from absl.testing import absltest, parameterized
import jax
import jax.numpy as jnp
from jax import typeof
from jax._src import config
from jax._src import core
from jax._src import dtypes
from jax._src import state
from jax._src.state import indexing
from jax._src.state import primitives as state_primitives
from jax._src.interpreters import ad
from jax._src.interpreters import batching
from jax._src import test_util as jtu
from jax._src.util import safe_zip, safe_map
from jax._src.state.discharge import run_state
from jax._src.hijax import (
HiPrimitive, HiType, Box, new_box, box_set, box_get, box_effect,
register_hitype, ShapedArray, Ty, custom_vjp3, MappingSpec, HipSpec)
from jax.experimental.hijax import VJPHiPrimitive
jtu.request_cpu_devices(8)
config.parse_flags_with_absl()
map, unsafe_map = safe_map, map
zip, unsafe_zip = safe_zip, zip
@dataclass(frozen=True)
class QArray:
arr: jax.Array # int8[m, k]
scale: jax.Array # f32[m]
# Define a type
@dataclass(frozen=True)
class QArrayTy(HiType):
shape: tuple[int, int]
# how to lower to (lo)jax types
def lo_ty(self) -> list[ShapedArray]:
m, k = self.shape
return [ShapedArray((m, k), jnp.dtype('int8')),
ShapedArray((m, ), jnp.dtype('float32'))]
# these next two are essentially the pytree interface
def lower_val(self, hi_val: QArray) -> list[jax.Array]:
return [hi_val.arr, hi_val.scale]
def raise_val(self, arr, scale) -> QArray:
return QArray(arr, scale) # alternative: LowerTrace
def ref_get_abstract_eval(self, ref_aval, *args, tree):
arr_aval = core.ShapedArray(self.shape, jnp.dtype('float32'))
updated_ref = ref_aval.update(inner_aval=arr_aval)
out, effects = state_primitives.get_p.abstract_eval(
updated_ref, *args, tree=tree
)
assert isinstance(out, core.ShapedArray)
return QArrayTy(out.shape), effects
def ref_swap_abstract_eval(self, ref_aval, val_aval, *args, tree):
arr_aval = core.ShapedArray(self.shape, jnp.dtype('float32'))
val_arr_aval = core.ShapedArray(val_aval.shape, jnp.dtype('float32'))
updated_ref = ref_aval.update(inner_aval=arr_aval)
out_aval, effects = state_primitives.swap_p.abstract_eval(
updated_ref, val_arr_aval,*args, tree=tree
)
assert isinstance(out_aval, core.ShapedArray)
return QArrayTy(out_aval.shape), effects
def ref_get_to_lojax(self, ref: state.TransformedRef | jax.Ref,
idx: indexing.NDIndexer):
if isinstance(ref, state.TransformedRef):
if ref.transforms: raise NotImplementedError(ref)
ref = ref.ref
# Unpack Ref type
ref = ref._refs
if not all(i.start == 0 and i.size == s
for i, s in zip(idx.indices, ref.arr.shape)):
raise NotImplementedError
outs = [out.get() for out in self.lower_val(ref)]
return self.raise_val(*outs)
def ref_swap_to_lojax(self, ref: state.TransformedRef | jax.Ref,
val: jax.Array, idx: indexing.NDIndexer):
if isinstance(ref, state.TransformedRef):
if ref.transforms: raise NotImplementedError(ref)
ref = ref.ref
# Unpack Ref type
ref = ref._refs
if not all(i.start == 0 and i.size == s
for i, s in zip(idx.indices, ref.arr.shape)):
raise NotImplementedError
outs = [out.swap(val) for out, val
in zip(self.lower_val(ref), self.lower_val(val))]
return self.raise_val(*outs)
# autodiff
def to_tangent_aval(self):
return self # different from what a pytree would do!
def vspace_zero(self):
m, k = self.shape
return QArray(jnp.zeros((m, k), jnp.dtype('int8')),
jnp.ones ((m, ), jnp.dtype('float32')))
register_hitype(QArray, lambda q: QArrayTy(q.arr.shape))
def to_qarray(x):
return to_qarray_p.bind(x)
def from_qarray(x):
return from_qarray_p.bind(x)
class ToQ(HiPrimitive):
def abstract_eval(_, lo_aval):
return QArrayTy(lo_aval.shape), set()
def to_lojax(_, lo_val):
m, _ = lo_val.shape
scale = lo_val.max(1) / 32.
return QArray((lo_val / scale[:, None]).astype('int8'), scale)
def jvp(_, primals, tangents):
(x,), (xdot,) = primals, tangents
return to_qarray(x), to_qarray(xdot)
def transpose(_, out_bar, __):
return [from_qarray(out_bar)]
to_qarray_p = ToQ('to_q')
class FromQ(HiPrimitive):
def abstract_eval(_, hi_aval):
return ShapedArray(hi_aval.shape, jnp.dtype('float32')), set()
def to_lojax(_, hi_val):
return hi_val.arr.astype('float32') * hi_val.scale[:, None]
def jvp(_, primals, tangents):
(x,), (xdot,) = primals, tangents
return from_qarray(x), from_qarray(xdot)
def transpose(_, out_bar, __):
return [to_qarray(out_bar)]
from_qarray_p = FromQ('from_q')
@dataclass
class HiTup:
elts: tuple
def __repr__(self):
return 'Tup{' + ','.join(map(repr, self.elts)) + '}'
@dataclass(frozen=True)
class TupTy(HiType):
tys: tuple[Ty, ...]
def __repr__(self):
return 'Tup{' + ','.join(a.str_short() for a in self.tys) + '}'
def __hash__(self):
return hash(self.tys)
def __eq__(self, other):
return self.tys == other.tys
def lo_ty(self):
return list(self.tys)
def lower_val(self, hi_val: HiTup):
return [lo for ty, elt in zip(self.tys, hi_val.elts)
for lo in ty.lower_val(elt)]
def raise_val(self, *elts_flat):
elts_iter = iter(elts_flat)
return HiTup(tuple(ty.raise_val(*it.islice(elts_iter, len(ty.lo_ty())))
for ty in self.tys))
def to_tangent_aval(self):
return TupTy(tuple(ty.to_tangent_aval() for ty in self.tys))
def normalize(self):
return TupTy(tuple(ty.normalize() for ty in self.tys))
def dec_rank(self, size, spec):
return TupTy(tuple(ty.dec_rank(size, s) for ty, s in zip(self.tys, spec.val)))
def inc_rank(self, size, spec):
return TupTy(tuple(ty.inc_rank(size, 0) for ty in self.tys))
def leading_axis_spec(self):
return TupSpec(tuple(ty.leading_axis_spec() for ty in self.tys))
def shard(self, mesh, manual_axes, check_vma, spec):
return TupTy(tuple(ty.shard(mesh, manual_axes, check_vma, s)
for ty, s in zip(self.tys, spec.val)))
def unshard(self, mesh, check_vma, spec):
return TupTy(tuple(ty.unshard(mesh, check_vma, s)
for ty, s in zip(self.tys, spec.val)))
register_hitype(HiTup, lambda t: TupTy(tuple(map(typeof, t.elts))))
@dataclass(frozen=True)
class TupSpec(MappingSpec):
val: tuple
@dataclass(frozen=True)
class TupP(HipSpec):
val: tuple
def to_lo(self) -> tuple[jax.PartitionSpec, ...]:
return self.val
class MakeTup(VJPHiPrimitive):
def __init__(self, in_avals):
in_avals = tuple(in_avals)
self.in_avals = in_avals
self.out_aval = TupTy(in_avals)
self.params = {}
super().__init__()
def expand(self, *elts):
return HiTup(elts)
def batch(self, _axis_data, args, in_dims):
return make_tup(*args), TupSpec(in_dims)
class GetTupElt(VJPHiPrimitive):
def __init__(self, in_aval, idx):
self.in_avals = in_aval,
self.out_aval = in_aval.tys[idx]
self.params = dict(idx=idx)
super().__init__()
def expand(self, tup):
return tup.elts[self.idx]
def vjp_fwd(self, tup):
return get_tuple_element(tup, self.idx), None
def vjp_bwd_retval(self, _res, g):
tup_ty, = self.in_avals
elts = map(ad.zeros_like_aval, tup_ty.tys)
elts[self.idx] = g
return make_tup(*elts),
def batch(self, _axis_data, args, in_dims):
(x,), (d,) = args, in_dims
return get_tuple_element(x, self.idx), d.val[self.idx]
def make_tup(*elts):
return MakeTup(map(typeof, elts))(*elts)
def get_tuple_element(tup, idx):
return GetTupElt(typeof(tup), idx)(tup)
@dataclass(frozen=True)
class ImmutBox:
_val: Any
@property
def shape(self):
if hasattr(self._val, 'shape'):
return self._val.shape
leaves = jax.tree.leaves(self._val)
if leaves and hasattr(leaves[0], 'shape'):
return leaves[0].shape
raise AttributeError(f"ImmutBox with value {self._val} has no shape")
@property
def ndim(self):
return len(self.shape)
def _is_zero(x):
return isinstance(x, ad.Zero)
def _get_aval(x):
return x.aval if _is_zero(x) else core.typeof(x)
def immutbox_to_aval(box: ImmutBox) -> 'ImmutBoxTy':
leaves, treedef = jax.tree.flatten(box._val, is_leaf=_is_zero)
leaf_avals = tuple(map(_get_aval, leaves))
return ImmutBoxTy(leaf_avals, treedef)
@dataclass(frozen=True)
class ImmutBoxTy(HiType):
leaf_avals: tuple[core.AbstractValue, ...]
treedef: Any
has_qdd = False
@property
def shape(self):
reconstructed = jax.tree.unflatten(self.treedef, self.leaf_avals)
if hasattr(reconstructed, 'shape'):
return reconstructed.shape
if self.leaf_avals and hasattr(self.leaf_avals[0], 'shape'):
return self.leaf_avals[0].shape
raise AttributeError(f"ImmutBoxTy with treedef {self.treedef} has no shape")
@property
def ndim(self):
return len(self.shape)
@property
def sharding(self):
reconstructed = jax.tree.unflatten(self.treedef, self.leaf_avals)
if hasattr(reconstructed, 'sharding'):
return reconstructed.sharding
if self.leaf_avals and hasattr(self.leaf_avals[0], 'sharding'):
return self.leaf_avals[0].sharding
return None
def lo_ty(self):
return list(self.leaf_avals)
def lower_val(self, hi_val: ImmutBox):
leaves, treedef = jax.tree.flatten(hi_val._val, is_leaf=_is_zero)
assert treedef == self.treedef
return leaves
def raise_val(self, *lo_vals):
return ImmutBox(jax.tree.unflatten(self.treedef, lo_vals))
def to_tangent_aval(self):
tangent_leaf_avals = tuple(aval.to_tangent_aval() for aval in self.leaf_avals)
return ImmutBoxTy(tangent_leaf_avals, self.treedef)
def _map_immutbox_ty(size: int, axis: int | None, aval: ImmutBoxTy) -> ImmutBoxTy:
if axis is None:
return aval
mapped_leaf_avals = tuple(core.mapped_aval(size, axis, leaf_aval)
for leaf_aval in aval.leaf_avals)
return ImmutBoxTy(mapped_leaf_avals, aval.treedef)
def _unmap_immutbox_ty(size: int, axis: int | None, explicit_mesh_axis,
aval: ImmutBoxTy) -> ImmutBoxTy:
if axis is None:
return aval
elif isinstance(axis, int):
unmapped_leaf_avals = tuple(core.unmapped_aval(size, axis, explicit_mesh_axis, leaf_aval)
for leaf_aval in aval.leaf_avals)
return ImmutBoxTy(unmapped_leaf_avals, aval.treedef)
else:
raise TypeError(axis)
core.aval_mapping_handlers[ImmutBoxTy] = (_map_immutbox_ty, _unmap_immutbox_ty)
class ImmutBoxNew(HiPrimitive):
def is_high(self, *leaves, leaf_avals, treedef) -> bool:
return True
def abstract_eval(self, *leaves, leaf_avals, treedef):
return ImmutBoxTy(leaf_avals, treedef), set()
def to_lojax(self, *leaves, leaf_avals, treedef):
val = jax.tree.unflatten(treedef, leaves)
return ImmutBox(val)
def jvp(self, primals, tangents, *, leaf_avals, treedef):
return (immutbox_new_p.bind(*primals, leaf_avals=leaf_avals, treedef=treedef),
immutbox_new_p.bind(*tangents, leaf_avals=leaf_avals, treedef=treedef))
def transpose(self, out_bar, *leaves, leaf_avals, treedef):
val = out_bar._val
leaves, _ = jax.tree.flatten(val, is_leaf=_is_zero)
return leaves
immutbox_new_p = ImmutBoxNew('immutbox_new')
def immutbox_new(val):
leaves, treedef = jax.tree.flatten(val, is_leaf=_is_zero)
leaf_avals = tuple(map(_get_aval, leaves))
leaves = [ad.instantiate_zeros(leaf) for leaf in leaves]
return immutbox_new_p.bind(*leaves, leaf_avals=leaf_avals, treedef=treedef)
class ImmutBoxGet(HiPrimitive):
multiple_results = True
def is_high(self, box_aval) -> bool:
return True
def abstract_eval(self, box_aval):
leaf_avals = box_aval.leaf_avals
return list(leaf_avals), set()
def to_lojax(self, box):
leaves, _ = jax.tree.flatten(box._val, is_leaf=_is_zero)
return tuple(leaves)
def jvp(self, primals, tangents):
(box,), (box_dot,) = primals, tangents
return immutbox_get(box), immutbox_get(box_dot)
def transpose(self, out_bars, box):
box_aval = core.typeof(box) if not ad.is_undefined_primal(box) else box.aval
treedef = box_aval.treedef
reconstructed_cotangent = jax.tree.unflatten(treedef, out_bars)
return (immutbox_new(reconstructed_cotangent),)
immutbox_get_p = ImmutBoxGet('immutbox_get')
def immutbox_get(box):
leaves = immutbox_get_p.bind(box)
box_ty = core.typeof(box)
return jax.tree.unflatten(box_ty.treedef, leaves)
register_hitype(ImmutBox, immutbox_to_aval)
class Square(VJPHiPrimitive):
"""Simple parameterless hijax primitive for use in tests."""
_jvp_execution_count = 0
def __init__(self, in_aval):
self.in_avals = (in_aval,)
self.out_aval = in_aval
self.params = {}
super().__init__()
@classmethod
@contextmanager
def assert_jvp_rule_called_once(cls):
initial_count = cls._jvp_execution_count
yield
assert cls._jvp_execution_count == initial_count + 1
def expand(self, x):
return x ** 2
def jvp(self, primals, tangents):
self.__class__._jvp_execution_count += 1
(x,), (t,) = primals, tangents
return self(x), t * 2.0 * x
def vjp_fwd(self, nzs_in, x):
return (self(x), x)
def vjp_bwd_retval(self, res, t):
return (t * 2.0 * res,)
def square(x):
"""Bind a hijax primtive that returns the square of x."""
return Square(jax.typeof(x))(x)
class HijaxTest(jtu.JaxTestCase):
def test_basic_register(self):
# older test that defines a slightly different QArray internally
@dataclass(frozen=True)
class QArray:
arr: jax.Array
scale: jax.Array
axis: int
@dataclass(frozen=True)
class QArrayTy(HiType):
shape: tuple[int, int]
axis: int
ndim = property(lambda self: len(self.shape))
# how to lower to (lo)jax types
def lo_ty(self) -> list[ShapedArray]:
m, k = self.shape
return [ShapedArray((m, k), jnp.dtype('int8')),
ShapedArray((m, ), jnp.dtype('float32'))]
# these next two are essentially the pytree interface
def lower_val(self, hi_val: QArray) -> list[jax.Array]:
return [hi_val.arr, hi_val.scale]
def raise_val(self, arr, scale) -> QArray:
return QArray(arr, scale, self.axis)
register_hitype(QArray, lambda q: QArrayTy(q.arr.shape, q.axis))
q = QArray(jnp.zeros((4, 4), 'int8'), jnp.ones(4, 'float32'), axis=1)
jax.jit(lambda x: x)(q) # don't crash
def test_custom_types_and_primitive(self):
if config.enable_x64.value: raise unittest.SkipTest("no x64")
@dataclass(frozen=True)
class MyArray:
arr: jax.Array # always f32
@dataclass(frozen=True)
class MyTy(HiType):
def to_tangent_aval(self):
return MyTy()
def str_short(self, short_dtypes=False):
return 'MyTy'
def lo_ty(self):
return [core.ShapedArray((), jnp.dtype('float32'))]
def lower_val(self, hi_val: MyArray) -> list[jax.Array]:
return [hi_val.arr]
def raise_val(self, val) -> MyArray:
return MyArray(val)
def __eq__(self, other): return isinstance(other, MyTy)
def vspace_zero(self):
return MyArray(jnp.zeros((), 'float32'))
def vspace_add(self, x, y):
return add(x, y)
core.pytype_aval_mappings[MyArray] = lambda _: MyTy()
dtypes.canonicalize_value_handlers[MyArray] = lambda x: x
class ToMy(HiPrimitive):
def is_high(self, _): return True
def abstract_eval(_, lo_aval):
return MyTy(), set()
def to_lojax(_, lo):
return MyArray(lo)
def jvp(_, primals, tangents):
x, x_dot = *primals, *tangents
return to(x), to(x_dot)
def transpose(self, out_bar, _):
return from_(out_bar),
class FromMy(HiPrimitive):
def is_high(self, _): return True
def abstract_eval(_, hi_aval):
return hi_aval.lo_ty()[0], set()
def to_lojax(_, hi):
return hi.arr
def jvp(_, primals, tangents):
x, x_dot = *primals, *tangents
return from_(x), from_(x_dot)
def transpose(self, out_bar, _):
return to(out_bar),
def to(x): return to_p.bind(x)
to_p = ToMy('to_my')
def from_(x): return from_p.bind(x)
from_p = FromMy('from_my')
def mul(x, y): return mul_p.bind(x, y)
def add(x, y): return add_p.bind(x, y)
class MyMul(HiPrimitive):
def is_high(self, *_): return True
def abstract_eval(_, hi_x, hi_y):
if hi_x != hi_y: raise Exception
return hi_x, set()
def to_lojax(_, hi_x, hi_y):
return MyArray(hi_x.arr * hi_y.arr)
def jvp(_, primals, tangents):
(x, y), (x_dot, y_dot) = primals, tangents
return mul(x, y), add(mul(x, y_dot), mul(x_dot, y))
def transpose(self, out_bar, x, y):
assert ad.is_undefined_primal(x) ^ ad.is_undefined_primal(y)
if ad.is_undefined_primal(x):
return mul(out_bar, y), None
else:
return None, mul(x, out_bar)
class MyAdd(HiPrimitive):
def is_high(self, *_): return True
def abstract_eval(_, hi_x, hi_y):
if hi_x != hi_y: raise Exception
return hi_x, set()
def to_lojax(_, hi_x, hi_y):
return MyArray(hi_x.arr + hi_y.arr)
def jvp(_, primals, tangents):
assert False # TODO
def transpose(self, out_bar, x, y):
return out_bar, out_bar
mul_p = MyMul('my_mul')
add_p = MyAdd('my_add')
@jax.jit
def f(x):
return to(from_(x))
# test basic to/from jit
a = MyArray(jnp.ones(()))
b = f(a) # don't crash
self.assertIsInstance(b, MyArray)
self.assertAllClose(b.arr, jnp.ones(()))
# test basic to/from autodiff
b, b_dot = jax.jvp(f, (a,), (a,))
self.assertIsInstance(b, MyArray)
self.assertIsInstance(b_dot, MyArray)
# test mul jit and backward pass
@jax.jit
def f(x):
return mul(x, x)
b, f_vjp = jax.vjp(f, a)
self.assertIn('MyTy', str(f_vjp))
a_grad, = f_vjp(b)
self.assertIsInstance(a_grad, MyArray)
self.assertAllClose(a_grad.arr, 2.0, check_dtypes=False)
def test_stages(self):
@dataclass(frozen=True)
class ArrayTuple:
x0: jax.Array
x1: jax.Array
@dataclass(frozen=True)
class ShapedArrayTuple(HiType):
x0: ShapedArray
x1: ShapedArray
# sharding=None
# how to lower to (lo)jax types
def lo_ty(self) -> list[ShapedArray]:
return [self.x0, self.x1]
# these next two are essentially the pytree interface
def lower_val(self, hi_val: ArrayTuple) -> list[jax.Array]:
return [hi_val.x0, hi_val.x1]
def raise_val(self, x0, x1) -> ArrayTuple:
return ArrayTuple(x0, x1)
register_hitype(ArrayTuple, lambda q: ShapedArrayTuple(
jax.typeof(q.x0), jax.typeof(q.x1)))
q = ArrayTuple(jnp.zeros((4, 4), 'int8'), jnp.ones(4, 'float32'))
jax.jit(lambda x: x).lower(q).as_text() # don't crash
compiled = jax.jit(lambda x: x).lower(q).compile()
compiled(q) # don't crash
@parameterized.parameters([False, True])
def test_while_loop(self, jit):
q = to_qarray(jnp.ones((2, 2), 'float32'))
def f(q1, q2):
def cond_fun(i_carry):
i, _, __ = i_carry
return i < 1
def body_fun(i_carry):
i, q_carry, _ = i_carry
q_carry = to_qarray(from_qarray(q_carry))
return i + 1, q_carry, q
n, q_out, _ = jax.lax.while_loop(cond_fun, body_fun, (0, q1, q2))
return n, q_out
if jit:
f = jax.jit(f)
jax.make_jaxpr(f)(q, q) # doesn't crash
n, q_out = f(q, q)
self.assertEqual(n, 1)
expected = from_qarray(to_qarray(from_qarray(q)))
self.assertAllClose(from_qarray(q_out), expected, check_dtypes=False)
@parameterized.parameters([False, True])
def test_tuple_basic(self, jit):
def f():
tup = make_tup(1, 2)
return get_tuple_element(tup, 1)
if jit:
f = jax.jit(f)
self.assertEqual(f(), 2)
def test_tuple_vmap(self):
tup = make_tup(jnp.arange(3.), jnp.arange(3.))
jax.vmap(lambda x: x, in_axes=TupSpec((0, 0)), out_axes=TupSpec((0, 0)), axis_size=3)(tup)
def test_tuple_vmap_infer(self):
tup = make_tup(jnp.arange(3.), jnp.arange(3.))
jax.vmap(lambda _: make_tup(jnp.ones(3), jnp.ones(3)),
in_axes=TupSpec((0, 0)), out_axes=batching.infer, axis_size=3)(tup)
# def test_tuple_vmap_match(self):
# tup = make_tup(jnp.arange(3.), jnp.arange(3.))
# jax.vmap(lambda _: make_tup(jnp.ones(3), jnp.ones(3)),
# in_axes=TupSpec((0, 0)), out_axes=TupSpec((0, 0)), axis_size=3)(tup)
def test_tuple_vmap_primitive(self):
tup = make_tup(jnp.arange(3.), 5.)
def f(tup):
a, b = get_tuple_element(tup, 0), get_tuple_element(tup, 1)
return make_tup(b, a)
jax.vmap(f, in_axes=TupSpec((0, None)), out_axes=TupSpec((None, 0)), axis_size=3)(tup)
@parameterized.parameters([False, True])
def test_tuple_scan(self, jit):
tup = make_tup(jnp.arange(3.), jnp.arange(3. * 4).reshape(3, 4))
def body(_, x):
self.assertEqual(typeof(x), TupTy((typeof(jnp.zeros(())), typeof(jnp.arange(4.)))))
a = get_tuple_element(x, 0)
b = get_tuple_element(x, 1)
return (), make_tup(a + 1, b * 2)
def f(): return jax.lax.scan(body, (), tup, length=3)
if jit:
f = jax.jit(f)
(), tup2 = f()
a = get_tuple_element(tup2, 0)
b = get_tuple_element(tup2, 1)
self.assertAllClose(a, jnp.arange(3.) + 1)
self.assertAllClose(b, jnp.arange(3. * 4).reshape(3, 4) * 2)
@jtu.with_explicit_mesh((2, 2), ('i', 'j'))
def test_tuple_shit(self, mesh):
x = jax.device_put(jnp.arange(4.), jax.P('i'))
y = jax.device_put(jnp.arange(3.), jax.P(None))
tup = make_tup(x, y)
x_ = get_tuple_element(tup, 0)
y_ = get_tuple_element(tup, 1)
self.assertEqual(jax.typeof(x_).sharding.spec, jax.P('i'))
self.assertEqual(jax.typeof(y_).sharding.spec, jax.P(None))
@jtu.with_explicit_mesh((2, 2), ('i', 'j'))
def test_tuple_shmap(self, mesh):
x = jax.device_put(jnp.arange(4.), jax.P('i'))
y = jax.device_put(jnp.arange(3.), jax.P(None))
tup = make_tup(x, y)
@jax.jit
@jax.shard_map(in_specs=TupP((jax.P('i'), jax.P(None))),
out_specs=TupP((jax.P(None), jax.P('i'))))
def fun(tup):
a, b = get_tuple_element(tup, 0), get_tuple_element(tup, 1)
return make_tup(b, a)
out = fun(tup)
x_ = get_tuple_element(out, 1)
y_ = get_tuple_element(out, 0)
self.assertAllClose(x, x_)
self.assertAllClose(y, y_)
self.assertEqual(x.sharding, x_.sharding)
self.assertEqual(y.sharding, y_.sharding)
# @jtu.with_explicit_mesh((2, 2), ('i', 'j'))
# def test_tuple_shmap_out_specs_error(self, mesh):
# x = jax.device_put(jnp.arange(4.), jax.P('i'))
# y = jax.device_put(jnp.arange(3.), jax.P(None))
# tup = make_tup(x, y)
# # TODO(mattjj,yashkatariya): this errors too late, make shmap checks work
# @jax.jit
# @jax.shard_map(in_specs=TupP((jax.P('i'), jax.P(None))),
# out_specs=TupP((jax.P('i'), jax.P('i')))) # NOTE!!!!
# def fun(tup):
# a, b = get_tuple_element(tup, 0), get_tuple_element(tup, 1)
# return make_tup(b, a)
# out = fun(tup)
# x_ = get_tuple_element(out, 1)
# y_ = get_tuple_element(out, 0)
# self.assertAllClose(x, x_)
# self.assertAllClose(y, y_)
# self.assertEqual(x.sharding, x_.sharding)
# self.assertEqual(y.sharding, y_.sharding)
@parameterized.parameters([False, True])
def test_ref_to_tuple(self, jit):
def f():
tup = make_tup(1, 2)
ref = jax.new_ref(tup)
tup_ = ref[...]
return get_tuple_element(tup_, 1)
if jit:
f = jax.jit(f)
self.assertEqual(f(), 2)
@parameterized.parameters([False, True])
def test_run_state(self, jit):
def f():
@run_state
def g(ref_args):
tup_ref, x_ref = ref_args
tup = tup_ref[...]
x_ref[...] = get_tuple_element(tup, 1)
tup = make_tup(1, 2)
_, ans = g((tup, 3))
return ans
if jit:
f = jax.jit(f)
ans = f()
self.assertEqual(ans, 2)
@parameterized.parameters([False, True])
def test_newstyle_hiprimitive(self, jit):
class RaiseToStaticPower(VJPHiPrimitive):
def __init__(self, in_aval, *, power):
self.in_avals = (in_aval,)
self.out_aval = in_aval
self.params = dict(power=power)
super().__init__()
def expand(self, x):
return x ** self.power
def vjp_fwd(self, nzs_in, x):
ans = self(x)
return (ans, x)
def vjp_bwd(self, res, t, xbar_accum):
xbar = t * self.power * raise_to_static_power(res, self.power-1)
xbar_accum.accum(xbar)
def batch(self, _axis_data, args, in_dims):
in_dim, = in_dims
x, = args
return raise_to_static_power(x, self.power), in_dim
def jvp(self, primals, tangents):
(x,), (t,) = primals, tangents
return self(x), t * self.power * raise_to_static_power(x, self.power-1)
def raise_to_static_power(x, power):
x_aval = jax.typeof(x)
return RaiseToStaticPower(x_aval, power=power)(x)
def f(x):
return raise_to_static_power(x, power=3)
if jit:
f = jax.jit(f)
self.assertEqual(f.lower(2.0).compile()(2.0), 8.0)
self.assertEqual(f(2.0), 8.0)
xs = jnp.arange(3.0)
self.assertAllClose(jax.vmap(f)(xs), xs**3)
self.assertEqual(jax.grad(f)(2.0), 12.0)
self.assertEqual(jax.jvp(f, (2.0,), (1.0,)),
(8.0, 12.0))
@parameterized.parameters([False, True])
def test_newstyle_hiprimitive_retval(self, jit):
class RaiseToStaticPower(VJPHiPrimitive):
def __init__(self, in_aval, *, power):
self.in_avals = (in_aval,)
self.out_aval = in_aval
self.params = dict(power=power)
super().__init__()
def expand(self, x):
return x ** self.power
def vjp_fwd(self, nzs_in, x):
ans = self(x)
return (ans, x)
def vjp_bwd_retval(self, res, t):
return (t * self.power * raise_to_static_power(res, self.power-1),)
def batch(self, _axis_data, args, in_dims):
in_dim, = in_dims
x, = args
return raise_to_static_power(x, self.power), in_dim
def raise_to_static_power(x, power):
x_aval = jax.typeof(x)
return RaiseToStaticPower(x_aval, power=power)(x)
def f(x):
return raise_to_static_power(x, power=3)
if jit:
f = jax.jit(f)
self.assertEqual(f(2.0), 8.0)
xs = jnp.arange(3.0)
self.assertAllClose(jax.vmap(f)(xs), xs**3)
self.assertEqual(jax.grad(f)(2.0), 12.0)
def test_newstyle_hiprimitive_defines_both_types_of_vjp_error(self):
class RaiseToStaticPower(VJPHiPrimitive):
def __init__(self, in_aval, *, power):
self.in_avals = (in_aval,)
self.out_aval = in_aval
self.params = dict(power=power)
super().__init__()
def expand(self, x):
return x ** self.power
def vjp_fwd(self, x):
ans = self(x)
return (ans, x)
def vjp_bwd(self, res, t, xbar_accum):
xbar = t * self.power * raise_to_static_power(res, self.power-1)
xbar_accum.accum(xbar)
def vjp_bwd_retval(self, res, t):
return (t * self.power * raise_to_static_power(res, self.power-1),)
def batch(self, _axis_data, args, in_dims):
in_dim, = in_dims
x, = args
return raise_to_static_power(x, self.power), in_dim
def raise_to_static_power(x, power):
x_aval = jax.typeof(x)
return RaiseToStaticPower(x_aval, power=power)(x)
def f(x):
return raise_to_static_power(x, power=3)
with self.assertRaises(AttributeError):
f(2.0)
def test_newstyle_hiprimitive_vmap(self):
class Mul(VJPHiPrimitive):
def __init__(self, aval):
self.in_avals = (aval, aval)
self.out_aval = aval
self.params = {}
super().__init__()
def expand(self, x, y):
return x * y
def batch_dim_rule(self, axis_data, in_dims):
return in_dims[1] if in_dims[0] is None else in_dims[0]
def mul(x, y):
return Mul(typeof(x))(x, y)
self.assertAllClose(mul(2.0, 3.0), 6.0)
x = jnp.arange(3.0)
y = jnp.arange(3.0) + 1.0
self.assertAllClose(jax.vmap(mul)(x, y), x * y)
x = jnp.arange(6.0).reshape(2, 3)
self.assertAllClose(jax.vmap(mul, in_axes=(0, None))(x, y), x * y[None, :])
self.assertAllClose(jax.vmap(mul, in_axes=(None, 0))(y, x), x * y[None, :])
x = jnp.arange(24.0).reshape(2, 3, 4)
f = jax.vmap(mul, in_axes=(0, None))
f = jax.vmap(f, in_axes=(2, None), out_axes=2)
self.assertAllClose(f(x, y), x * y[None, :, None])
x = jnp.arange(12.0).reshape(3, 4)
y = jnp.arange(6.0).reshape(2, 3)
f = jax.vmap(mul, in_axes=(None, 0))
f = jax.vmap(f, in_axes=(1, None), out_axes=2)
self.assertAllClose(f(x, y), x[None, :, :] * y[:, :, None])
@config.numpy_dtype_promotion('standard')
def test_newstyle_hiprimitive_qarray(self):
@dataclass(frozen=True) # not NamedTuple, which is a pytree
class QArray:
qvalue: jax.Array
scale: jax.Array
@dataclass(frozen=True)
class QArrayTy(HiType):
shape: tuple[int, int]
def to_tangent_aval(self):
return ShapedArray(self.shape, jnp.dtype('float32'))
register_hitype(QArray, lambda q: QArrayTy(q.qvalue.shape))
def q(x):
return Q(jax.typeof(x))(x)
def dq(qx):
return DQ(jax.typeof(qx))(qx)
class Q(VJPHiPrimitive):
def __init__(self, unquantized_aval):
if unquantized_aval.dtype != jnp.dtype('float32'): raise TypeError
quantized_aval = QArrayTy(unquantized_aval.shape)
self.in_avals = (unquantized_aval,)
self.out_aval = quantized_aval
self.params = {}
super().__init__()
def expand(self, x):
scale = jnp.max(jnp.abs(x)) / 127
qvalue = jnp.round(x / scale).astype(jnp.int8)
return QArray(qvalue, scale)
def vjp_fwd(self, nzs_in, x):
return self(x), None
def vjp_bwd_retval(self, _, g):
return g,
class DQ(VJPHiPrimitive):
def __init__(self, quantized_aval):
unquantized_aval = ShapedArray(quantized_aval.shape, jnp.dtype('float32'))
self.in_avals = (quantized_aval,)
self.out_aval = unquantized_aval
self.params = {}
super().__init__()
def expand(self, qx):
return qx.qvalue * qx.scale
def vjp_fwd(self, nzs_in, qx):
return self(qx), None
def vjp_bwd_retval(self, _, g):
return g,
def f(x):
return jnp.sum(dq(q(x)))
x = jax.random.normal(jax.random.key(0), (3, 3), dtype='float32')
jax.grad(f)(x)
def test_symbolic_zeros(self):
class Mul(VJPHiPrimitive):
def __init__(self, aval):
self.in_avals = (aval, aval)
self.out_aval = aval
self.params = {}
super().__init__()
def expand(self, x, y):
return x * y
def vjp_fwd(self, nzs_in, x, y):
assert list(nzs_in) == list(nzs_in_) # defined below
ans = self(x, y)
return ans, (x, y)
def vjp_bwd(self, res, g, x_acc, y_acc):
assert list(nzs_in_) == [not isinstance(x_acc, ad.NullAccum),
not isinstance(y_acc, ad.NullAccum)]
x, y = res
x_acc.accum(g * y)
y_acc.accum(x * g)
def mul(x, y):
return Mul(typeof(x))(x, y)
nzs_in_ = (True, False)
self.assertAllClose(jax.grad(mul)(2., 3.), 3., check_dtypes=False)
nzs_in_ = (False, True)
self.assertAllClose(jax.grad(mul, 1)(2., 3.), 2., check_dtypes=False)
def test_symbolic_zeros_retval(self):
class Mul(VJPHiPrimitive):
def __init__(self, aval):
self.in_avals = (aval, aval)
self.out_aval = aval
self.params = {}
super().__init__()
def expand(self, x, y):
return x * y
def vjp_fwd(self, nzs_in, x, y):
assert list(nzs_in) == list(nzs_in_) # defined below
ans = self(x, y)
return ans, (x, y)
def vjp_bwd_retval(self, res, g):
x, y = res
return (g * y, x * g)
def mul(x, y):
return Mul(typeof(x))(x, y)
nzs_in_ = (True, False)
self.assertAllClose(jax.grad(mul)(2., 3.), 3., check_dtypes=False)
nzs_in_ = (False, True)
self.assertAllClose(jax.grad(mul, 1)(2., 3.), 2., check_dtypes=False)
@jtu.with_explicit_mesh((2,), ('data',))
def test_hijax_primitive_under_shard_map(self, mesh):
x = jax.device_put(jnp.arange(10), jax.P('data'))
g = jax.shard_map(square, in_specs=(jax.P('data'),), out_specs=jax.P('data'))
g(x)
jax.jit(g)(x)
def test_hijax_cond_platform_dependent(self):
x = jnp.arange(10)
result = jax.jit(partial(jax.lax.platform_dependent, cpu=square, default=square))(x)
self.assertArraysAllClose(result, x ** 2)
def test_hijax_primitive_under_remat(self):
x = jnp.arange(10)
expected = x ** 2
with self.subTest("no jit"):
self.assertArraysAllClose(jax.remat(square)(x), expected)
with self.subTest("jit"):
self.assertArraysAllClose(jax.jit(jax.remat(square))(x), expected)
x = jnp.float32(2.0)
expected_grad = jnp.float32(4.0)
with self.subTest("jit-of-grad"):
with Square.assert_jvp_rule_called_once():
actual_grad = jax.jit(jax.grad(jax.remat(square)))(x)
self.assertArraysAllClose(actual_grad, expected_grad)
@parameterized.parameters([False, True])
def test_linearize_rule(self, jit):
class RaiseToStaticPower(VJPHiPrimitive):
def __init__(self, in_aval, *, power):
self.in_avals = (in_aval,)
self.out_aval = in_aval
self.params = dict(power=power)
super().__init__()
def expand(self, x):
return x ** self.power
def lin(self, nzs_in, x):
nz, = nzs_in
assert nz
return self(x), x
def linearized(self, x, t):
return t * self.power * raise_to_static_power(x, self.power-1)
def raise_to_static_power(x, power):
x_aval = jax.typeof(x)
return RaiseToStaticPower(x_aval, power=power)(x)
def f(x):
return raise_to_static_power(x, 3)
if jit:
f = jax.jit(f)
self.assertEqual(f(2.0), 8.0)
self.assertEqual(jax.linearize(f, 2.0)[1](1.0), 12.0)
class BoxTest(jtu.JaxTestCase):
@parameterized.parameters([False, True])
def test_qdd(self, jit):
val1 = 1.0
val2 = jnp.arange(3)
box1 = Box(val1)
def f(box2):
assert core.cur_qdd(box2).leaf_avals == (core.typeof(val1),)
box2.set(val2)
assert core.cur_qdd(box2).leaf_avals == (core.typeof(val2),)
box3 = new_box()
box3.set(val2)
assert core.cur_qdd(box3).leaf_avals == (core.typeof(val2),)
box3.set(val1)
assert core.cur_qdd(box3).leaf_avals == (core.typeof(val1),)
assert core.cur_qdd(box1).leaf_avals == (core.typeof(val1),)
box1.set(val2)
assert core.cur_qdd(box1).leaf_avals == (core.typeof(val2),)
return
if jit:
f = jax.jit(f)
f(Box(val1))
def test_qdd_vmap(self):
# https://github.com/jax-ml/jax/issues/34758
def f():
return Box(jnp.array(0)).get()
jax.vmap(f, axis_size=2)() # don't crash
def test_jit_internal(self):
@jax.jit
def f(x):
box = new_box() # TODO not Box
box.set(x)
box.set(box.get() + box.get())
return box.get()
f(1)
def test_jit_internal_box_constructor(self):
@jax.jit
def f(x):
box = Box(x)
box.set(box.get() + box.get())
return box.get()
f(1)
@parameterized.parameters([False, True])
def test_isinstance(self, jit):
def f():
box = Box()
self.assertIsInstance(box, Box)
if jit:
f = jax.jit(f)
f()
def test_jit_arg(self):
@jax.jit
def f(box, x):
assert tracing_ok
box.set(box.get() + x)
tracing_ok = True
box1 = Box(1.0)
f(box1, 1.)
self.assertAllClose(box1.get(), 2.0)
tracing_ok = False
box2 = Box(2.0)
f(box2, 2.)
self.assertAllClose(box2.get(), 4.0)
def test_jit_arg2(self):
# set without get
@jax.jit
def f(box, x):
box_set(box, x)
box = Box(0.0)
f(box, 1.)
self.assertAllClose(box_get(box), 1.0, check_dtypes=False)
def test_jit_arg_in_pytree(self):
@jax.jit
def f(dct, x):
assert tracing_ok
box = dct['box']
box.set(box.get() + x)
tracing_ok = True
box1 = Box(1.0)
f({'box': box1, 'a': 1.0}, 1.)
self.assertAllClose(box1.get(), 2.0)
tracing_ok = False
box2 = Box(2.0)
f({'box': box2, 'a': 2.0}, 2.)
self.assertAllClose(box2.get(), 4.0)
tracing_ok = True
box3 = Box(3) # int, dtype changed
f({'box': box3, 'a': 2.0}, 2.)
self.assertAllClose(box3.get(), 5.0)
def test_jit_closure(self):
box = Box(1.0)
@jax.jit
def f(x):
assert tracing_ok
box.set(box.get() + x)
tracing_ok = True
f(2.0)
self.assertAllClose(box.get(), 3.0)
tracing_ok = False
f(5.0)
self.assertAllClose(box.get(), 8.0)
def test_jit_closure_nested(self):
box = Box(5.0)
@jax.jit
def f(x):
box.set(box.get() + x)
@jax.jit
def g(x):
f(x)
g(3.0)
self.assertAllClose(box.get(), 8.0)
def test_jit_closure_nested2(self):
@jax.jit
def h(x):
box = new_box()
box.set(x)
@jax.jit
def k(x):
box.set(box.get() + x)
k(1.0)
k(1.0)
return box.get()
ans = h(2.0)
self.assertAllClose(ans, 4.0)
def test_jit_closure_nested3(self):
box = new_box()
@jax.jit
def h(x):
box.set(x)
@jax.jit
def k(x):
box.set(box.get() + x)
k(1.0)
k(1.0)
return box.get()
ans = h(2.0)
self.assertAllClose(ans, 4.0)
@parameterized.parameters([False, True])
def test_jvp_closure_stop_gradient(self, jit):
box = Box(1.0)
def f(x):
y = 2 * x
box.set(box.get() + jax.lax.stop_gradient(y))
return y
if jit:
f = jax.jit(f)
y, y_dot = jax.jvp(f, (1.0,), (1.0,))
self.assertAllClose(y, 2.0)
self.assertAllClose(y_dot, 2.0)
self.assertAllClose(box.get(), 3.0)
@parameterized.parameters([False, True])
def test_jvp_arg(self, jit):
def f(box, x):
box.set(box.get() + x)
return x
if jit:
f = jax.jit(f)
box = Box(5.0)
box_dot = Box(1.0)
y, y_dot = jax.jvp(f, (box, 2.), (box_dot, 1.))
self.assertAllClose(y, 2.0)
self.assertAllClose(y_dot, 1.0)
self.assertAllClose(box.get(), 7.0)
self.assertAllClose(box_dot.get(), 2.0)
@parameterized.parameters([False, True])
def test_custom_vjp_plumbing(self, jit):
box = Box(0.0)
@jax.custom_vjp
def foo(x):
return x
def foo_fwd(x):
return foo(x), None
def foo_bwd(_, g):
box.set(g)
return g,
foo.defvjp(foo_fwd, foo_bwd)
def f(x):
x = 2 * x
x = foo(x)
x = 2 * x
return x
if jit:
f = jax.jit(f)
jax.grad(f)(1.0)
self.assertAllClose(box.get(), 2.0)
@parameterized.parameters([False, True])
def test_custom_vjp_plumbing_abstracted(self, jit):
box = Box(0.0)
@jax.custom_vjp
def foo(box, x):
return x
def foo_fwd(box, x):
return x, box
def foo_bwd(box, g):
box.set(g)
return None, g
foo.defvjp(foo_fwd, foo_bwd)
def f(box, x):
x = 2 * x
x = foo(box, x)
x = 2 * x
return x
if jit:
f = jax.jit(f)
jax.grad(partial(f, box))(1.0)
self.assertAllClose(box.get(), 2.0)
@parameterized.parameters([False, True])
def test_custom_vjp_primal(self, jit):
box = Box(0.0)
@custom_vjp3
def foo(box, x):
box.set(x)
return x
def foo_fwd(box, x):
assert False # doesn't run
def foo_bwd(box, g):
assert False # doesn't run
foo.defvjp(foo_fwd, foo_bwd)
def f(box, x):
x = 2 * x
x = foo(box, x)
x = 2 * x
return x
if jit:
f = jax.jit(f)
f(box, 1.0)
self.assertAllClose(box.get(), 2.0)
@parameterized.parameters([False, True])
def test_grad_closure_stop_gradient(self, jit):
box = Box(0.0)
def f(x):
y = x * 2
box.set(box.get() + jax.lax.stop_gradient(y))
return y
if jit:
f = jax.jit(f)
g = jax.grad(f)(1.0)
self.assertAllClose(g, 2.0)
self.assertAllClose(box.get(), 2.0)
@parameterized.parameters([False, True])
def test_scan_basic(self, jit):
box = Box(1.0)
def double_it_10():
def body(_, __):
box.set(box.get() * 2)
return None, None
_, _ = jax.lax.scan(body, None, None, length=10)
if jit:
double_it_10 = jax.jit(double_it_10)
double_it_10()
self.assertAllClose(box.get(), 1024., check_dtypes=False)
def test_cond_box_internally_pure(self):
@jax.jit
def doubleit(x):
b = new_box()
b.set(x)
b.set(b.get() + b.get())
return b.get()
def identity(x): return x
@jax.jit
def f(x):
return jax.lax.cond(x > 0, doubleit, identity, x)
self.assertAllClose(f(1.0), 2.0)
def test_cond_box_arg(self):
@jax.jit
def f(x):
b = new_box()
b.set(x)
jax.lax.cond(x > 0, lambda box: box.set(box.get() + 1), lambda _: None, b)
return b.get()
self.assertAllClose(f(1.0), 2.0)
def test_cond_closed_over_box(self):
# TODO: good error messages in the case that qdd changes differently in each branch
def f(x):
b = new_box()
b.set(1.0)
jax.lax.cond(x > 0., lambda _: b.set(b.get() + 1.0), lambda _: None, 1.0)
return b.get()
self.assertAllClose(f(1.0), 2.0)
# TODO error-checking tests from attrs_test.py
###
def test_box_autodiff(self):
if config.enable_x64.value: raise unittest.SkipTest("no x64")
class StashTangents(HiPrimitive):
def is_high(self, *_):
return True
def abstract_eval(_, box_aval, x_aval):
del box_aval
return x_aval, {box_effect}
def to_lojax(_, box, x):
return x
def jvp(_, primals, tangents):
box, x = primals
_, x_dot = tangents
box_set(box, x_dot)
return x, x_dot
def transpose(self, *args):
assert False # TODO
stash_tangents_p = StashTangents('stash_tangents')
def stash_tangents(box, x):
return stash_tangents_p.bind(box, x)
@jax.jit
def f(box, x):
x = stash_tangents(box, x)
return x
box = Box(0.0)
jax.jvp(partial(f, box), (3.,), (5.,))
self.assertAllClose(box_get(box), 5.0, check_dtypes=False)
def test_type_changing_box(self):
box = Box(jnp.arange(1))
box_set(box, jnp.arange(2))
self.assertLen(box._val, 2)
@jax.jit
def f(box, x):
box_set(box, x)
f(box, jnp.arange(3))
self.assertLen(box._val, 3)
f(box, jnp.arange(4))
self.assertLen(box._val, 4)
def test_pytree_box(self):
box = Box(None)
@jax.jit
def f(box, x):
assert tracing_ok
val = box_get(box)
if val is None:
box_set(box, x)
else:
box_set(box, [x, x])
tracing_ok = True
f(box, 1.0)
self.assertAllClose(box_get(box), 1.0, check_dtypes=False)
f(box, 2.0)
self.assertAllClose(box_get(box), [2.0, 2.0], check_dtypes=False)
f(box, 3.0)
self.assertAllClose(box_get(box), [3.0, 3.0], check_dtypes=False)
tracing_ok = False
f(box, 4.0)
self.assertAllClose(box_get(box), [4.0, 4.0], check_dtypes=False)
def test_pytree_of_hijaxtypes_box(self):
@dataclass(frozen=True)
class MyArray:
arr: jax.Array # always f32
@dataclass(frozen=True)
class MyTy(HiType):
has_qdd = False
def to_tangent_aval(self):
return MyTy()
def str_short(self, short_dtypes=False):
return 'MyTy'
def lo_ty(self):
return [core.ShapedArray((), jnp.dtype('float32'))]
def lower_val(self, hi_val: MyArray) -> list[jax.Array]:
return [hi_val.arr]
def raise_val(self, val) -> MyArray:
return MyArray(val)
def __eq__(self, other): return isinstance(other, MyTy)
core.pytype_aval_mappings[MyArray] = lambda _: MyTy()
box = Box([MyArray(jnp.float32(1)),
MyArray(jnp.float32(2))])
@jax.jit
def f(box):
a, b = box_get(box)
box_set(box, [b, a])
f(box)
val = box_get(box)
self.assertIsInstance(val, list)
self.assertLen(val, 2)
b_, a_ = val
self.assertIsInstance(a_, MyArray)
self.assertIsInstance(b_, MyArray)
self.assertAllClose(a_.arr, 1, check_dtypes=False)
self.assertAllClose(b_.arr, 2, check_dtypes=False)
def test_closed_over_type_changing_box(self):
box = Box(None)
box2 = Box(None)
@jax.jit
def f():
assert tracing_ok
x = box.get()
if x is None:
box.set(0)
elif type(x) is dict:
box.set(dict(x, a=5))
box2.set(3)
else:
box.set(x + 1)
tracing_ok = True
f() # tracing okay because first time
f() # tracing okay because first time with box as not None
tracing_ok = False
f()
self.assertEqual(box.get(), 2)
self.assertEqual(box2.get(), None)
box.set(None)
f()
f()
f()
f()
self.assertEqual(box.get(), 3)
self.assertEqual(box2.get(), None)
box.set({'b': 3})
tracing_ok = True
f()
self.assertEqual(box.get(), dict(a=5, b=3))
self.assertEqual(box2.get(), 3)
@parameterized.parameters([False, True])
def test_while_loop(self, jit):
box = Box(1.)
def f():
zero = jnp.zeros((), 'int32')
def cond_fun(i):
return i + zero < 5
def body_fun(i):
box.set(box.get() * 2.)
return i + 1
_ = jax.lax.while_loop(cond_fun, body_fun, 0)
if jit:
f = jax.jit(f)
f()
self.assertAllClose(box.get(), 32, check_dtypes=False)
def test_while_loop_typechange_error(self):
box = Box([1.])
def cond_fun(i):
return i < 5
def body_fun(i):
box.set(box.get() * 2)
return i + 1
with self.assertRaisesRegex(TypeError, "type-changing mutations not allowed"):
_ = jax.lax.while_loop(cond_fun, body_fun, 0)
def test_eval_shape(self):
qarray = QArray(jnp.ones((2, 2)), jnp.ones(2))
@jax.jit
def f():
return qarray
out_type = jax.eval_shape(f)
self.assertEqual(out_type, QArrayTy((2, 2)))
def test_stages_mutable(self):
box = Box(1.0)
@jax.jit
def f(box):
box.set(box.get() + 1.)
f.lower(box).as_text() # don't crash
compiled = f.lower(box).compile()
compiled(box)
compiled(box)
compiled(box)
self.assertAllClose(box.get(), 4.)
class RefTest(jtu.JaxTestCase):
def test_get_ref_hitype(self):
@jax.jit
def f(q):
ref = jax.new_ref(q)
return ref[:, 0:2]
qarray = QArray(jnp.ones((2, 2), dtype='int8'), jnp.ones(2, 'float32'))
o = f(qarray)
self.assertArraysEqual(o.arr, qarray.arr)
self.assertArraysEqual(o.scale, qarray.scale)
def test_swap_ref_hitype(self):
@jax.jit
def f(q1, q2):
ref = jax.new_ref(q1)
ref[:, :] = q2
return ref.get()
q1 = QArray(jnp.zeros((2, 2), dtype='int8'), jnp.zeros(2, 'float32'))
q2 = QArray(jnp.ones((2, 2), dtype='int8'), jnp.ones(2, 'float32'))
o = f(q1, q2)
self.assertArraysEqual(o.arr, q2.arr)
self.assertArraysEqual(o.scale, q2.scale)
class HijaxTransformCoverageTest(jtu.JaxTestCase):
# ------------
# grad
# ------------
# with differentiable hijax arguments
def test_hitypes_as_grad_args(self):
box = immutbox_new((jnp.array(2.0), jnp.array(3.0)))
def loss_fn(tup):
x = immutbox_get(tup)[0]
return x ** 2
grads = jax.grad(loss_fn)(box)
self.assertAllClose(immutbox_get(grads)[0], 4.0)
# with non-differentiable hijax arguments
def test_hitypes_as_nondiff_grad_args(self):
box = immutbox_new((jnp.array(2.0), jnp.array(3.0)))
x = jnp.array(3.0)
def loss_fn(x, box):
y = immutbox_get(box)[1]
return x ** 2 + y
grad = jax.grad(loss_fn)(x, box)
self.assertAllClose(grad, 6.0, check_dtypes=False)
# with hijax captured arguments
def test_hitypes_as_captured_args(self):
box = immutbox_new((jnp.array(2.0), jnp.array(3.0)))
def loss_fn(x):
y = immutbox_get(box)[1]
return x ** 2 + y
grad = jax.grad(loss_fn)(jnp.array(4.0))
self.assertAllClose(grad, 8.0, check_dtypes=False)
# with differentiable mutable hijax arguments
@absltest.skip("Not yet implemented")
def test_mutable_hitypes_as_grad_args(self):
box = Box(jnp.array(2.0))
def loss_fn(box):
return box.get() ** 2
jax.grad(loss_fn)(box)
# NOTE: unclear what the tangent type will be here
# with non-differentiable mutable hijax arguments
def test_mutable_hitypes_as_nondiff_grad_args(self):
box = Box(jnp.array(2.0))
x = jnp.array(3.0)
def loss_fn(x, box):
box.set(jax.lax.stop_gradient(x * 2))
return x ** 2 + box.get()
grad = jax.grad(loss_fn)(x, box)
self.assertAllClose(box.get(), 6.0, check_dtypes=False)
self.assertAllClose(grad, 6.0, check_dtypes=False)
# with mutable hijax captured arguments
def test_mutable_hitypes_as_captured_args(self):
box = Box(jnp.array(2.0))
def loss_fn(x):
box.set(jax.lax.stop_gradient(x * 3))
return x ** 2 + box.get()
grad = jax.grad(loss_fn)(jnp.array(4.0))
self.assertAllClose(box.get(), 12.0, check_dtypes=False)
self.assertAllClose(grad, 8.0, check_dtypes=False)
#------------
# scan
#------------
# with hijax carry arguments
def test_hitypes_as_scan_carry(self):
box = immutbox_new((jnp.array(1.0), jnp.array(2.0)))
def body(box, _):
x, y = immutbox_get(box)
return immutbox_new((x + 1.0, y + 2.0)), None
box, _ = jax.lax.scan(body, box, None, length=5)
x, y = immutbox_get(box)
self.assertAllClose(x, 6.0, check_dtypes=False)
self.assertAllClose(y, 12.0, check_dtypes=False)
# with hijax captured arguments
def test_hitypes_as_scan_captured(self):
box = immutbox_new((jnp.array(3.0), jnp.array(4.0)))
carry0 = jnp.array(1.0)
xs = jnp.arange(5, dtype=jnp.float32)
def body(carry, x):
a, b = immutbox_get(box)
carry = a * carry + b
y = a * x + b
return carry, immutbox_new(y)
carry, ys_box = jax.lax.scan(body, carry0, xs)
ys = immutbox_get(ys_box)
self.assertAllClose(carry, 727.0, check_dtypes=False)
self.assertAllClose(ys, 3.0 * xs + 4.0, check_dtypes=False)
# with mutable hijax carry arguments
@absltest.skip("has_qdd not yet supported for Box in scan carry")
def test_mutable_hitypes_as_scan_carry(self):
box = Box(jnp.array(1.0))
def body(box, _):
box.set(box.get() * 2)
return box, None
box, _ = jax.lax.scan(body, box, None, length=5)
self.assertAllClose(box.get(), 32.0, check_dtypes=False)
# with mutable hijax extensive arguments
@absltest.skip("Box doesn't have shape attribute needed for scan extensive")
def test_mutable_hitypes_as_scan_extensive(self):
boxes = [Box(jnp.float32(i)) for i in range(5)]
def body(_, box_i):
val = box_i.get()
box_i.set(val * 2)
return None, box_i
_, boxes_out = jax.lax.scan(body, None, boxes)
for i, box in enumerate(boxes_out):
self.assertAllClose(box.get(), i * 2, check_dtypes=False)
# with mutable hijax captured arguments
def test_mutable_hitypes_as_scan_captured(self):
box = Box(jnp.array(3.0))
def body(_, __):
box.set(box.get() + 1.0)
return None, None
jax.lax.scan(body, None, None, length=5)
self.assertAllClose(box.get(), 8.0, check_dtypes=False)
if __name__ == '__main__':
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/hijax_test.py",
"license": "Apache License 2.0",
"lines": 1500,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/lax_numpy_setops_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from functools import partial, wraps
import itertools
import math
from absl.testing import absltest
import numpy as np
import jax
from jax import lax
import jax.numpy as jnp
from jax._src import config
from jax._src import test_util as jtu
config.parse_flags_with_absl()
nonempty_array_shapes = [(), (4,), (3, 4), (3, 1), (1, 4), (2, 1, 4), (2, 3, 4)]
empty_array_shapes = [(0,), (0, 4), (3, 0),]
scalar_shapes = [jtu.NUMPY_SCALAR_SHAPE, jtu.PYTHON_SCALAR_SHAPE]
array_shapes = nonempty_array_shapes + empty_array_shapes
nonempty_shapes = scalar_shapes + nonempty_array_shapes
all_shapes = scalar_shapes + array_shapes
default_dtypes = jtu.dtypes.all_floating + jtu.dtypes.all_integer
inexact_dtypes = jtu.dtypes.all_floating + jtu.dtypes.complex
number_dtypes = default_dtypes + jtu.dtypes.complex + jtu.dtypes.all_unsigned
def np_unique_backport(ar, return_index=False, return_inverse=False, return_counts=False,
axis=None, **kwds):
# Wrapper for np.unique, handling the change to inverse_indices in numpy 2.0
result = np.unique(ar, return_index=return_index, return_inverse=return_inverse,
return_counts=return_counts, axis=axis, **kwds)
if jtu.numpy_version() >= (2, 0, 1) or np.ndim(ar) == 1 or not return_inverse:
return result
idx = 2 if return_index else 1
inverse_indices = result[idx]
if axis is None:
inverse_indices = inverse_indices.reshape(np.shape(ar))
elif jtu.numpy_version() == (2, 0, 0):
inverse_indices = inverse_indices.reshape(-1)
return (*result[:idx], inverse_indices, *result[idx + 1:])
def arrays_with_overlapping_values(rng, shapes, dtypes, unique=False, overlap=0.5) -> list[jax.Array]:
"""Generate multiple arrays with some overlapping values.
This is useful for tests of set-like operations.
"""
assert 0 <= overlap <= 1
sizes = [math.prod(jtu._dims_of_shape(shape)) for shape in shapes]
total_size = int(sum(sizes) * (1 - overlap)) + max(sizes) # non-strict upper-bound.
if unique:
vals = jtu.rand_unique_int(rng)((total_size,), 'int32')
else:
vals = jtu.rand_default(rng)((total_size,), 'int32')
offsets = [int(sum(sizes[:i]) * (1 - overlap)) for i in range(len(sizes))]
return [rng.permutation(vals[offset: offset + size]).reshape(shape).astype(dtype)
for (offset, size, shape, dtype) in zip(offsets, sizes, shapes, dtypes)]
def with_size_argument(fun):
@wraps(fun)
def wrapped(*args, size=None, fill_value=None, **kwargs):
result = fun(*args, **kwargs)
if size is None or size == len(result):
return result
elif size < len(result):
return result[:size]
else:
if fill_value is None:
fill_value = result.min() if result.size else 0
return np.pad(result, (0, size - len(result)), constant_values=fill_value)
return wrapped
class LaxNumpySetopsTest(jtu.JaxTestCase):
"""Tests of set-like operations from jax.numpy."""
@jtu.sample_product(
element_shape=all_shapes,
test_shape=all_shapes,
dtype=default_dtypes,
invert=[False, True],
method=['auto', 'compare_all', 'binary_search', 'sort']
)
def testIsin(self, element_shape, test_shape, dtype, invert, method):
rng = jtu.rand_default(self.rng())
args_maker = lambda: [rng(element_shape, dtype), rng(test_shape, dtype)]
jnp_fun = lambda e, t: jnp.isin(e, t, invert=invert, method=method)
np_fun = lambda e, t: np.isin(e, t, invert=invert)
self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)
self._CompileAndCheck(jnp_fun, args_maker)
@jtu.sample_product(
dtype1=[s for s in default_dtypes if s != jnp.bfloat16],
dtype2=[s for s in default_dtypes if s != jnp.bfloat16],
shape1=all_shapes,
shape2=all_shapes,
overlap=[0.1, 0.5, 0.9],
)
def testSetdiff1d(self, shape1, shape2, dtype1, dtype2, overlap):
args_maker = partial(arrays_with_overlapping_values, self.rng(),
shapes=[shape1, shape2], dtypes=[dtype1, dtype2],
overlap=overlap)
with jtu.strict_promotion_if_dtypes_match([dtype1, dtype2]):
self._CheckAgainstNumpy(np.setdiff1d, jnp.setdiff1d, args_maker)
@jtu.sample_product(
dtype1=[s for s in default_dtypes if s != jnp.bfloat16],
dtype2=[s for s in default_dtypes if s != jnp.bfloat16],
shape1=all_shapes,
shape2=all_shapes,
size=[1, 5, 10],
fill_value=[None, -1],
overlap=[0.1, 0.5, 0.9],
)
def testSetdiff1dSize(self, shape1, shape2, dtype1, dtype2, size, fill_value, overlap):
args_maker = partial(arrays_with_overlapping_values, self.rng(),
shapes=[shape1, shape2], dtypes=[dtype1, dtype2],
overlap=overlap)
def np_fun(arg1, arg2):
result = np.setdiff1d(arg1, arg2)
if size <= len(result):
return result[:size]
else:
return np.pad(result, (0, size-len(result)), constant_values=fill_value or 0)
def jnp_fun(arg1, arg2):
return jnp.setdiff1d(arg1, arg2, size=size, fill_value=fill_value)
with jtu.strict_promotion_if_dtypes_match([dtype1, dtype2]):
self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)
self._CompileAndCheck(jnp_fun, args_maker)
@jtu.sample_product(
shape1=all_shapes,
shape2=all_shapes,
)
def testSetdiff1dAssumeUnique(self, shape1, shape2):
# regression test for https://github.com/jax-ml/jax/issues/32335
args_maker = lambda: (jnp.arange(math.prod(shape1), dtype='int32').reshape(shape1),
jnp.arange(math.prod(shape2), dtype='int32').reshape(shape2))
np_op = partial(np.setdiff1d, assume_unique=True)
jnp_op = partial(jnp.setdiff1d, assume_unique=True)
self._CheckAgainstNumpy(np_op, jnp_op, args_maker)
@jtu.sample_product(
dtype1=[s for s in default_dtypes if s != jnp.bfloat16],
dtype2=[s for s in default_dtypes if s != jnp.bfloat16],
shape1=all_shapes,
shape2=all_shapes,
overlap=[0.1, 0.5, 0.9],
)
def testUnion1d(self, shape1, shape2, dtype1, dtype2, overlap):
args_maker = partial(arrays_with_overlapping_values, self.rng(),
shapes=[shape1, shape2], dtypes=[dtype1, dtype2],
overlap=overlap)
def np_fun(arg1, arg2):
dtype = jnp.promote_types(arg1.dtype, arg2.dtype)
return np.union1d(arg1, arg2).astype(dtype)
with jtu.strict_promotion_if_dtypes_match([dtype1, dtype2]):
self._CheckAgainstNumpy(np_fun, jnp.union1d, args_maker)
@jtu.sample_product(
dtype1=[s for s in default_dtypes if s != jnp.bfloat16],
dtype2=[s for s in default_dtypes if s != jnp.bfloat16],
shape1=nonempty_shapes,
shape2=nonempty_shapes,
size=[1, 5, 10],
fill_value=[None, -1],
overlap=[0.1, 0.5, 0.9],
)
def testUnion1dSize(self, shape1, shape2, dtype1, dtype2, size, fill_value, overlap):
args_maker = partial(arrays_with_overlapping_values, self.rng(),
shapes=[shape1, shape2], dtypes=[dtype1, dtype2],
overlap=overlap)
def np_fun(arg1, arg2):
dtype = jnp.promote_types(arg1.dtype, arg2.dtype)
result = np.union1d(arg1, arg2).astype(dtype)
fv = result.min() if fill_value is None else fill_value
if size <= len(result):
return result[:size]
else:
return np.concatenate([result, np.full(size - len(result), fv, result.dtype)])
def jnp_fun(arg1, arg2):
return jnp.union1d(arg1, arg2, size=size, fill_value=fill_value)
with jtu.strict_promotion_if_dtypes_match([dtype1, dtype2]):
self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)
self._CompileAndCheck(jnp_fun, args_maker)
@jtu.sample_product(
dtype1=[s for s in default_dtypes if s != jnp.bfloat16],
dtype2=[s for s in default_dtypes if s != jnp.bfloat16],
shape1=all_shapes,
shape2=all_shapes,
assume_unique=[False, True],
size=[None, 2, 5],
fill_value=[None, 99],
overlap=[0.1, 0.5, 0.9],
)
def testSetxor1d(self, shape1, dtype1, shape2, dtype2, assume_unique, size, fill_value, overlap):
args_maker = partial(arrays_with_overlapping_values, self.rng(),
shapes=[shape1, shape2], dtypes=[dtype1, dtype2],
overlap=overlap)
jnp_fun = lambda ar1, ar2: jnp.setxor1d(ar1, ar2, assume_unique=assume_unique,
size=size, fill_value=fill_value)
def np_fun(ar1, ar2):
if assume_unique:
# numpy requires 1D inputs when assume_unique is True.
ar1 = np.ravel(ar1)
ar2 = np.ravel(ar2)
return with_size_argument(np.setxor1d)(ar1, ar2, assume_unique, size=size, fill_value=fill_value)
with jtu.strict_promotion_if_dtypes_match([dtype1, dtype2]):
self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, check_dtypes=False)
@jtu.sample_product(
dtype1=[s for s in default_dtypes if s != jnp.bfloat16],
dtype2=[s for s in default_dtypes if s != jnp.bfloat16],
shape1=nonempty_shapes,
shape2=nonempty_shapes,
assume_unique=[False, True],
return_indices=[False, True],
size=[None, 3, 5],
fill_value=[None, -1],
overlap=[0.1, 0.5, 0.9],
)
def testIntersect1d(self, shape1, dtype1, shape2, dtype2, assume_unique,
return_indices, size, fill_value, overlap):
args_maker = partial(arrays_with_overlapping_values, self.rng(),
shapes=[shape1, shape2], dtypes=[dtype1, dtype2],
unique=assume_unique, overlap=overlap)
def jnp_fun(ar1, ar2):
return jnp.intersect1d(ar1, ar2, assume_unique=assume_unique, return_indices=return_indices,
size=size, fill_value=fill_value)
def np_fun(ar1, ar2):
result = np.intersect1d(ar1, ar2, assume_unique=assume_unique, return_indices=return_indices)
def correct_size(x, fill_value):
if size is None or size == len(x):
return x
elif size < len(x):
return x[:size]
else:
if fill_value is None:
fill_value = x.min()
return np.pad(x, (0, size - len(x)), constant_values=fill_value)
if return_indices:
return tuple(correct_size(r, f) for r, f in zip(result, [fill_value, ar1.size, ar2.size]))
else:
return correct_size(result, fill_value)
with jtu.strict_promotion_if_dtypes_match([dtype1, dtype2]):
self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, check_dtypes=False)
@jtu.sample_product(
[dict(shape=shape, axis=axis)
for shape in all_shapes
for axis in [None] + list(range(len(shape)))],
dtype=number_dtypes,
return_index=[False, True],
return_inverse=[False, True],
return_counts=[False, True],
)
def testUnique(self, shape, dtype, axis, return_index, return_inverse, return_counts):
rng = jtu.rand_some_equal(self.rng())
args_maker = lambda: [rng(shape, dtype)]
extra_args = (return_index, return_inverse, return_counts)
use_defaults = (False, *(True for arg in extra_args if arg)) if any(extra_args) else False
np_fun = jtu.with_jax_dtype_defaults(lambda x: np_unique_backport(x, *extra_args, axis=axis), use_defaults)
jnp_fun = lambda x: jnp.unique(x, *extra_args, axis=axis)
self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)
@jtu.sample_product(shape=all_shapes, dtype=number_dtypes)
def testUniqueAll(self, shape, dtype):
rng = jtu.rand_some_equal(self.rng())
args_maker = lambda: [rng(shape, dtype)]
self._CheckAgainstNumpy(jnp.unique_all, np.unique_all, args_maker)
@jtu.sample_product(shape=all_shapes, dtype=number_dtypes)
def testUniqueCounts(self, shape, dtype):
rng = jtu.rand_some_equal(self.rng())
args_maker = lambda: [rng(shape, dtype)]
self._CheckAgainstNumpy(jnp.unique_counts, np.unique_counts, args_maker)
@jtu.sample_product(shape=all_shapes, dtype=number_dtypes)
def testUniqueInverse(self, shape, dtype):
rng = jtu.rand_some_equal(self.rng())
args_maker = lambda: [rng(shape, dtype)]
self._CheckAgainstNumpy(jnp.unique_inverse, np.unique_inverse, args_maker)
@jtu.sample_product(shape=all_shapes, dtype=number_dtypes)
def testUniqueValues(self, shape, dtype):
rng = jtu.rand_some_equal(self.rng())
args_maker = lambda: [rng(shape, dtype)]
np_fun = lambda *args: np.sort(np.unique_values(*args))
self._CheckAgainstNumpy(jnp.unique_values, np_fun, args_maker)
@jtu.sample_product(
[dict(shape=shape, axis=axis)
for shape in nonempty_array_shapes
for axis in [None] + list(range(len(shape)))],
dtype=number_dtypes,
size=[1, 5, 10],
fill_value=[None, 0, "slice"],
)
def testUniqueSize(self, shape, dtype, axis, size, fill_value):
rng = jtu.rand_some_equal(self.rng())
args_maker = lambda: [rng(shape, dtype)]
kwds = dict(axis=axis, return_index=True, return_inverse=True, return_counts=True)
if fill_value == "slice":
if axis is None:
fill_value = rng((), dtype)
else:
fill_value = rng(shape[:axis] + shape[axis + 1:], dtype)
elif fill_value is not None:
fill_value = np.array(fill_value).astype(dtype)
@partial(jtu.with_jax_dtype_defaults, use_defaults=(False, True, True, True))
def np_fun(x, fill_value=fill_value):
u, ind, inv, counts = np_unique_backport(x, **kwds)
axis = kwds['axis']
if axis is None:
x = x.ravel()
axis = 0
n_unique = u.shape[axis]
if size <= u.shape[axis]:
slc = (slice(None),) * axis + (slice(size),)
u, ind, counts = u[slc], ind[:size], counts[:size]
else:
extra = (0, size - n_unique)
pads = [(0, 0)] * u.ndim
pads[axis] = extra
u = np.pad(u, pads, constant_values=0)
slices = [slice(None)] * u.ndim
slices[axis] = slice(1)
if fill_value is None:
fill_value = u[tuple(slices)]
elif np.ndim(fill_value):
fill_value = lax.expand_dims(fill_value, (axis,))
slices[axis] = slice(n_unique, None)
u[tuple(slices)] = fill_value
ind = np.pad(ind, extra, constant_values=ind[0])
counts = np.pad(counts, extra, constant_values=0)
return u, ind, inv, counts
jnp_fun = lambda x: jnp.unique(x, size=size, fill_value=fill_value, **kwds)
self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)
self._CompileAndCheck(jnp_fun, args_maker)
@jtu.sample_product(dtype=inexact_dtypes)
def testUniqueNans(self, dtype):
def args_maker():
x = [-0.0, 0.0, 1.0, 1.0, np.nan, -np.nan]
if np.issubdtype(dtype, np.complexfloating):
x = [complex(i, j) for i, j in itertools.product(x, repeat=2)]
return [np.array(x, dtype=dtype)]
kwds = dict(return_index=True, return_inverse=True, return_counts=True)
jnp_fun = partial(jnp.unique, **kwds)
def np_fun(x):
dtype = x.dtype
# numpy unique fails for bfloat16 NaNs, so we cast to float64
if x.dtype == jnp.bfloat16:
x = x.astype('float64')
u, *rest = np.unique(x, **kwds)
return (u.astype(dtype), *rest)
self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)
@jtu.sample_product(dtype=inexact_dtypes, equal_nan=[True, False])
@jtu.ignore_warning(
category=RuntimeWarning, message='invalid value encountered in cast'
)
def testUniqueEqualNan(self, dtype, equal_nan):
shape = (20,)
rng = jtu.rand_some_nan(self.rng())
args_maker = lambda: [rng(shape, dtype)]
def np_fun(x):
dtype = x.dtype
# numpy unique fails for bfloat16 NaNs, so we cast to float64
if x.dtype == jnp.bfloat16:
x = x.astype('float64')
return np.unique(x, equal_nan=equal_nan).astype(dtype)
jnp_fun = partial(jnp.unique, equal_nan=equal_nan)
self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)
if __name__ == "__main__":
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/lax_numpy_setops_test.py",
"license": "Apache License 2.0",
"lines": 362,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/mosaic/gpu_test_distributed.py | # Copyright 2025 The JAX Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import os
from absl.testing import parameterized
import jax
from jax._src import config
from jax._src import test_util as jtu
from jax._src import test_multiprocess as jt_multiprocess
from jax._src.interpreters import mlir
from jax._src.lib.mlir import ir
from jax._src.lib.mlir.dialects import arith
from jax._src.lib.mlir.dialects import memref
from jax._src.lib.mlir.dialects import vector
from jax.experimental.mosaic.gpu import dialect as mgpu_dialect # pylint: disable=g-importing-member
from jax.experimental import multihost_utils
import jax.numpy as jnp
import numpy as np
import jax.experimental.mosaic.gpu as mgpu
import jax.experimental.mosaic.gpu.fragmented_array as fa
# ruff: noqa: F405
# pylint: disable=g-complex-comprehension
P = jax.sharding.PartitionSpec
class TestCase(parameterized.TestCase):
def setUp(self):
if (not jtu.test_device_matches(["cuda"]) or
not jtu.is_cuda_compute_capability_at_least("9.0")):
self.skipTest("Only works on GPU with capability >= sm90")
if not mgpu.supports_cross_device_collectives():
self.skipTest("NVSHMEM library unavailable.")
if os.environ.get("XLA_PYTHON_CLIENT_ALLOCATOR", "") == "platform":
self.skipTest("NVSHMEM doesn't work with the platform allocator.")
if jax.process_count() == 1:
self.skipTest("Test requires multiple processes.")
if jax.device_count() != jax.process_count():
self.skipTest("Need 1 device per process")
super().setUp()
self.prng = np.random.default_rng(1234)
self.context = mlir.make_ir_context()
if mgpu_dialect is not None:
mgpu_dialect.register_dialect(self.context)
self.enter_context(config.traceback_filtering("off"))
self.enter_context(self.context)
self.enter_context(ir.Location.unknown())
class ProfilerTest(TestCase):
def test_get_device_id(self):
index = ir.IndexType.get()
def kernel(ctx, dst, _):
device_id = ctx.device_id()
memref.store(device_id, dst, [arith.constant(index, 0)])
mesh = jax.make_mesh(
(jax.device_count(),), ("x",), axis_types=(jax.sharding.AxisType.Explicit,)
)
with jax.set_mesh(mesh):
out_shape = jax.ShapeDtypeStruct((1,), jnp.int32)
y = jax.jit(
jax.shard_map(
mgpu.as_gpu_kernel(
kernel, (1, 1, 1), (128, 1, 1), (), out_shape, ()
),
out_specs=P("x"),
check_vma=False,
)
)()
y_np = multihost_utils.process_allgather(y, tiled=True)
np.testing.assert_array_equal(y_np, np.arange(jax.device_count()))
def test_remote_async_copy_basic(self):
i32 = ir.IntegerType.get_signless(32)
def kernel(ctx, src, sem, dst, scratch):
tmp, barrier = scratch
other_device = arith.subi(arith.constant(i32, 1), ctx.device_id())
ctx.async_copy(src_ref=src, dst_ref=tmp, barrier=barrier)
barrier.wait()
ctx.async_copy(src_ref=tmp, dst_ref=dst, gmem_peer_id=other_device)
ctx.await_async_copy(0)
other_sem = mgpu.SemaphoreRef(
mgpu.utils.memref_ptr(ctx.to_remote(sem, other_device))
)
other_sem.signal(1)
my_sem = mgpu.SemaphoreRef(mgpu.utils.memref_ptr(sem))
my_sem.wait(1)
mesh = jax.make_mesh(
(2,), ("x",), axis_types=(jax.sharding.AxisType.Explicit,)
)
with jax.set_mesh(mesh):
x_np = np.arange(64 * 64, dtype=jnp.float32).reshape(64, 64)
x = jax.sharding.reshard(x_np, P("x"))
sem = jax.sharding.reshard(jnp.zeros((1,), dtype=jnp.int32), P())
y, _ = jax.jit(
jax.shard_map(
lambda x, sem: mgpu.as_gpu_kernel(
kernel, (1, 1, 1), (128, 1, 1), x, x, (x, mgpu.TMABarrier()), inout_shape=sem
)(x, sem),
in_specs=(P("x"), P(None)),
out_specs=[P("x"), P(None)],
check_vma=False,
)
)(x, sem)
y_np = multihost_utils.process_allgather(y, tiled=True)
np.testing.assert_array_equal(
y_np, np.concatenate(np.split(x_np, 2)[::-1], axis=0)
)
def test_remote_async_copy_add(self):
i32 = ir.IntegerType.get_signless(32)
def kernel(ctx, src, sem, dst, scratch):
tmp, barrier = scratch
other_device = arith.subi(arith.constant(i32, 1), ctx.device_id())
other_sem = mgpu.SemaphoreRef(
mgpu.utils.memref_ptr(ctx.to_remote(sem, other_device))
)
my_sem = mgpu.SemaphoreRef(mgpu.utils.memref_ptr(sem))
ctx.async_copy(src_ref=src, dst_ref=tmp, barrier=barrier)
barrier.wait()
fa.FragmentedArray.splat(arith.constant(ir.F32Type.get(), 1.0), (32, 64)).store_untiled(dst)
mgpu.warpgroup_barrier()
other_sem.signal(1)
my_sem.wait(1)
ctx.async_copy(src_ref=tmp, dst_ref=dst, gmem_peer_id=other_device, reduction_op="add")
ctx.await_async_copy(0)
other_sem.signal(1)
my_sem.wait(1)
mesh = jax.make_mesh(
(2,), ("x",), axis_types=(jax.sharding.AxisType.Explicit,)
)
with jax.set_mesh(mesh):
x_np = np.arange(64 * 64, dtype=jnp.float32).reshape(64, 64)
x = jax.sharding.reshard(x_np, P("x"))
sem = jax.sharding.reshard(jnp.zeros((1,), dtype=jnp.int32), P())
y, _ = jax.jit(
jax.shard_map(
lambda x, sem: mgpu.as_gpu_kernel(
kernel, (1, 1, 1), (128, 1, 1), x, x, (x, mgpu.TMABarrier()), inout_shape=sem
)(x, sem),
in_specs=(P("x"), P(None)),
out_specs=[P("x"), P(None)],
check_vma=False,
)
)(x, sem)
y_np = multihost_utils.process_allgather(y, tiled=True)
np.testing.assert_array_equal(
y_np, 1 + np.concatenate(np.split(x_np, 2)[::-1], axis=0)
)
def test_remote_semaphore(self):
i32 = ir.IntegerType.get_signless(32)
def kernel(ctx, sem, _):
my_device = ctx.device_id()
other_device = arith.subi(arith.constant(i32, 1), my_device)
my_sem = mgpu.SemaphoreRef(mgpu.utils.memref_ptr(sem))
other_dst = ctx.to_remote(sem, other_device)
other_sem = mgpu.SemaphoreRef(mgpu.utils.memref_ptr(other_dst))
# We signal and wait a different amount on each device to make sure we're
# really communicating here.
other_sem.signal(arith.addi(arith.constant(i32, 1), other_device))
@mgpu.fori(arith.addi(arith.constant(i32, 1), my_device), None)
def wait_loop(i, _):
my_sem.wait(1)
mesh = jax.make_mesh(
(2,), ("x",), axis_types=(jax.sharding.AxisType.Explicit,)
)
with jax.set_mesh(mesh):
sem = jax.sharding.reshard(jnp.zeros((1,), dtype=jnp.int32), P())
out_sem = jax.jit(
jax.shard_map(
mgpu.as_gpu_kernel(
kernel, (1, 1, 1), (128, 1, 1), (), (), (), inout_shape=sem
),
out_specs=P("x"),
check_vma=False,
)
)(sem)
out_sems = multihost_utils.process_allgather(out_sem, tiled=True)
np.testing.assert_array_equal(out_sems, np.zeros_like(out_sems))
@parameterized.parameters(1, 2, 4)
def test_multimem_basic(self, vector_length):
i32 = ir.IntegerType.get_signless(32)
index = ir.IndexType.get()
def kernel(ctx, sem, out, _):
my_device = ctx.device_id()
other_device = arith.subi(arith.constant(i32, 1), my_device)
my_sem = mgpu.SemaphoreRef(mgpu.utils.memref_ptr(sem))
other_dst = ctx.to_remote(sem, other_device)
other_sem = mgpu.SemaphoreRef(mgpu.utils.memref_ptr(other_dst))
with mgpu.when(arith.cmpi(arith.CmpIPredicate.eq, my_device, arith.constant(i32, 0))):
c = arith.constant(i32, 1)
vc = vector.broadcast(ir.VectorType.get((vector_length,), i32), c)
multicast_ref = ctx.to_remote_multicast(out)
multicast_ref.store(vc, [arith.constant(index, 0)])
other_sem.signal(arith.constant(i32, 1))
my_sem.wait(1)
mesh = jax.make_mesh(
(2,), ("x",), axis_types=(jax.sharding.AxisType.Explicit,)
)
with jax.set_mesh(mesh):
sem = jax.sharding.reshard(jnp.zeros((1,), dtype=jnp.int32), P())
out_shape = jax.ShapeDtypeStruct((vector_length,), jnp.int32)
out, out_sem = jax.jit(
jax.shard_map(
mgpu.as_gpu_kernel(
kernel, (1, 1, 1), (128, 1, 1), (), out_shape, (), inout_shape=sem
),
out_specs=P("x"),
check_vma=False,
)
)(sem)
out_sems = multihost_utils.process_allgather(out_sem, tiled=True)
np.testing.assert_array_equal(out_sems, np.zeros_like(out_sems))
out = multihost_utils.process_allgather(out, tiled=True)
np.testing.assert_array_equal(out, np.ones_like(out))
def test_multimem_store_registers(self):
i32 = ir.IntegerType.get_signless(32)
def kernel(ctx, inp, sem, out, _):
my_device = ctx.device_id()
other_device = arith.subi(arith.constant(i32, 1), my_device)
my_sem = mgpu.SemaphoreRef(mgpu.utils.memref_ptr(sem))
other_dst = ctx.to_remote(sem, other_device)
other_sem = mgpu.SemaphoreRef(mgpu.utils.memref_ptr(other_dst))
with mgpu.when(arith.cmpi(arith.CmpIPredicate.eq, my_device, arith.constant(i32, 0))):
arr = mgpu.FragmentedArray.load_strided(inp, is_signed=True)
arr.store_untiled(ctx.to_remote_multicast(out), optimized=False)
other_sem.signal(arith.constant(i32, 1))
my_sem.wait(1)
mesh = jax.make_mesh(
(2,), ("x",), axis_types=(jax.sharding.AxisType.Explicit,)
)
with jax.set_mesh(mesh):
sem = jax.sharding.reshard(jnp.zeros((1,), dtype=jnp.int32), P())
x = jax.sharding.reshard(jnp.arange(2048, dtype=jnp.int32).reshape(64, 32), P())
y, out_sem = jax.jit(
jax.shard_map(
mgpu.as_gpu_kernel(
kernel, (1, 1, 1), (128, 1, 1), x, x, (), inout_shape=sem
),
out_specs=P("x"),
check_vma=False,
)
)(x, sem)
out_sems = multihost_utils.process_allgather(out_sem, tiled=True)
np.testing.assert_array_equal(out_sems, np.zeros_like(out_sems))
y = multihost_utils.process_allgather(y, tiled=True).reshape(2, *x.shape)
np.testing.assert_array_equal(y, jnp.stack([x, x]))
def test_multimem_store_tma(self):
i32 = ir.IntegerType.get_signless(32)
def kernel(ctx, inp, sem, out, scratch):
my_device = ctx.device_id()
other_device = arith.subi(arith.constant(i32, 1), my_device)
my_sem = mgpu.SemaphoreRef(mgpu.utils.memref_ptr(sem))
other_dst = ctx.to_remote(sem, other_device)
other_sem = mgpu.SemaphoreRef(mgpu.utils.memref_ptr(other_dst))
with mgpu.when(arith.cmpi(arith.CmpIPredicate.eq, my_device, arith.constant(i32, 0))):
arr = mgpu.FragmentedArray.load_strided(inp, is_signed=True)
arr.store_untiled(scratch)
mgpu.commit_shared()
ctx.async_copy(
src_ref=scratch, dst_ref=out, gmem_peer_id=mgpu.GLOBAL_BROADCAST
)
ctx.await_async_copy(0)
other_sem.signal(arith.constant(i32, 1))
my_sem.wait(1)
mesh = jax.make_mesh(
(2,), ("x",), axis_types=(jax.sharding.AxisType.Explicit,)
)
with jax.set_mesh(mesh):
sem = jax.sharding.reshard(jnp.zeros((1,), dtype=jnp.int32), P())
x = jax.sharding.reshard(jnp.arange(2048, dtype=jnp.int32).reshape(64, 32), P())
y, out_sem = jax.jit(
jax.shard_map(
mgpu.as_gpu_kernel(
kernel, (1, 1, 1), (128, 1, 1), x, x, x, inout_shape=sem
),
out_specs=P("x"),
check_vma=False,
)
)(x, sem)
out_sems = multihost_utils.process_allgather(out_sem, tiled=True)
np.testing.assert_array_equal(out_sems, np.zeros_like(out_sems))
y = multihost_utils.process_allgather(y, tiled=True).reshape(2, *x.shape)
np.testing.assert_array_equal(y, jnp.stack([x, x]))
@parameterized.parameters(
(jnp.int32, 1, "add"),
(jnp.int32, 1, "min"),
(jnp.int32, 1, "max"),
(jnp.int32, 1, "and"),
(jnp.int32, 1, "or"),
(jnp.int32, 1, "xor"),
(jnp.float32, 1, "add"),
(jnp.float32, 2, "add"),
(jnp.float32, 4, "add"),
(jnp.float16, 2, "add"),
(jnp.float16, 2, "min"),
(jnp.float16, 4, "max"),
(jnp.float16, 8, "add"),
(jnp.bfloat16, 2, "max"),
(jnp.bfloat16, 8, "add"),
(jnp.float8_e5m2, 4, "add"),
(jnp.float8_e5m2, 8, "min"),
(jnp.float8_e5m2, 16, "max"),
(jnp.float8_e4m3fn, 4, "min"),
(jnp.float8_e4m3fn, 8, "max"),
(jnp.float8_e4m3fn, 16, "add"),
)
def test_multimem_load_reduce(self, dtype, vector_length, reduction):
if dtype in (
jnp.float8_e5m2,
jnp.float8_e4m3fn,
) and not jtu.is_cuda_compute_capability_at_least("10.0"):
self.skipTest("Only works on GPU with capability >= sm100")
i32 = ir.IntegerType.get_signless(32)
def kernel(ctx, inp, sem, out, _):
my_device = ctx.device_id()
other_device = arith.subi(arith.constant(i32, 1), my_device)
my_sem = mgpu.SemaphoreRef(mgpu.utils.memref_ptr(sem))
other_dst = ctx.to_remote(sem, other_device)
other_sem = mgpu.SemaphoreRef(mgpu.utils.memref_ptr(other_dst))
layout = fa.WGStridedFragLayout((64, 32), vec_size=vector_length)
arr = mgpu.FragmentedArray.load_reduce_untiled(
ctx.to_remote_multicast(inp),
layout=layout,
is_signed=mgpu.utils.is_signed(dtype),
reduction=reduction,
)
arr.store_untiled(out, optimized=False)
other_sem.signal(arith.constant(i32, 1))
my_sem.wait(1)
mesh = jax.make_mesh(
(2,), ("x",), axis_types=(jax.sharding.AxisType.Explicit,)
)
with jax.set_mesh(mesh):
sem = jax.sharding.reshard(jnp.zeros((1,), dtype=jnp.int32), P())
# The rounding we see in low precision types seems to be different from
# what JAX/XLA use.
match jnp.dtype(dtype).itemsize:
case 4:
bound = 800000
case 2:
bound = 128
case 1:
bound = 4
case _:
raise ValueError(f"Unsupported dtype: {dtype}")
x_local = jax.random.randint(
jax.random.key(1234), (128, 32), dtype=jnp.int32, minval=-bound, maxval=bound
).astype(dtype)
x = jax.sharding.reshard(x_local, P("x"))
x_shard = jax.ShapeDtypeStruct((64, 32), dtype)
# TODO(b/448323639): We don't need x to be inout here, but without aliasing
# XLA doesn't actually insert the copy that puts the operand in symmetric
# memory, which causes the kernel to crash.
y, _, out_sem = jax.jit(
jax.shard_map(
mgpu.as_gpu_kernel(
kernel, (1, 1, 1), (128, 1, 1), (), x_shard, (), inout_shape=(x_shard, sem)
),
out_specs=P("x"),
check_vma=False,
)
)(x, sem)
out_sems = multihost_utils.process_allgather(out_sem, tiled=True)
np.testing.assert_array_equal(out_sems, np.zeros_like(out_sems))
y = multihost_utils.process_allgather(y, tiled=True)
match reduction:
case "add":
np_reduction = jnp.add
case "min":
np_reduction = jnp.minimum
case "max":
np_reduction = jnp.maximum
case "and":
np_reduction = jnp.bitwise_and
case "or":
np_reduction = jnp.bitwise_or
case "xor":
np_reduction = jnp.bitwise_xor
case _:
raise ValueError(reduction)
np.testing.assert_array_equal(
y.astype(jnp.float32), np.tile(np_reduction(x_local[:64], x_local[64:]), (2, 1))
)
if __name__ == "__main__":
# This test doesn't work with the platform allocator, so we override it
# if it's ran alone. If it's part of a larger test suite and the platform
# allocator is used, setUp will skip the test.
os.environ['XLA_PYTHON_CLIENT_MEM_FRACTION'] = '0.01'
os.environ['XLA_PYTHON_CLIENT_ALLOCATOR'] = 'default'
jt_multiprocess.main()
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/mosaic/gpu_test_distributed.py",
"license": "Apache License 2.0",
"lines": 395,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/mosaic/gpu_torch_test.py | # Copyright 2025 The JAX Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import unittest
from absl.testing import absltest
from absl.testing import parameterized
import jax
from jax._src import config
from jax._src import test_util as jtu
from jax._src.interpreters import mlir
from jax._src.lib.mlir import ir
from jax._src.lib.mlir.dialects import arith
from jax._src.lib.mlir.dialects import gpu
import jax.experimental.mosaic.gpu as mgpu
from jax.experimental.mosaic.gpu import dialect as mgpu_dialect # pylint: disable=g-importing-member
from jax.experimental.mosaic.gpu.utils import * # noqa: F403
import jax.numpy as jnp
import numpy as np
try:
import torch
except ImportError:
torch = None
# ruff: noqa: F405
# pylint: disable=g-complex-comprehension
config.parse_flags_with_absl()
class TorchTest(parameterized.TestCase):
def setUp(self):
if (not jtu.test_device_matches(["cuda"]) or
not jtu.is_cuda_compute_capability_at_least("9.0")):
self.skipTest("Only works on GPU with capability >= sm90")
super().setUp()
self.prng = np.random.default_rng(1234)
self.context = mlir.make_ir_context()
mgpu_dialect.register_dialect(self.context)
self.enter_context(config.traceback_filtering("off"))
self.enter_context(self.context)
self.enter_context(ir.Location.unknown())
if torch is None:
raise unittest.SkipTest("Test requires PyTorch")
def test_basic(self):
def kernel(ctx, i_gmem, o_gmem, _):
x = mgpu.FragmentedArray.load_strided(i_gmem)
(x + x).store_untiled(o_gmem)
ty = jax.ShapeDtypeStruct((128, 128), jnp.float32)
x = torch.randn((128, 128), dtype=torch.float, device='cuda')
f = mgpu.as_torch_gpu_kernel(kernel, (1, 1, 1), (128, 1, 1), ty, ty, ())
y = f(x)
np.testing.assert_allclose(y.cpu(), x.cpu() * 2)
del y # Make sure the destructor runs successfully.
def test_inout(self):
def kernel(ctx, src, inout, dst, smem):
val = memref.load(inout, [])
gpu.barrier()
new_val = arith.constant(ir.IntegerType.get_signless(32), 42)
memref.store(new_val, inout, [])
x = mgpu.FragmentedArray.load_strided(src, is_signed=True)
(x + val).store_untiled(dst)
x = torch.arange(128, dtype=torch.int32, device='cuda')
y = torch.tensor(2.0, dtype=torch.int32, device='cuda')
x_ty = jax.ShapeDtypeStruct((128,), jnp.int32)
y_ty = jax.ShapeDtypeStruct((), jnp.int32)
kernel = mgpu.as_torch_gpu_kernel(
kernel, (1, 1, 1), (128, 1, 1), x_ty, x_ty, (), inout_shape=y_ty,
)
xo, yo = kernel(x, y)
np.testing.assert_array_equal(xo.cpu(), x.cpu() + 2.0)
np.testing.assert_array_equal(yo.cpu(), torch.tensor(42, dtype=torch.int32))
if __name__ == "__main__":
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/mosaic/gpu_torch_test.py",
"license": "Apache License 2.0",
"lines": 80,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/mosaic/gpu_torch_test_distributed.py | # Copyright 2025 The JAX Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import os
import unittest
from absl.testing import parameterized
import jax
from jax._src import config
from jax._src import test_util as jtu
from jax._src import test_multiprocess as jt_multiprocess
from jax._src.interpreters import mlir
from jax._src.lib.mlir import ir
from jax._src.lib.mlir.dialects import arith
from jax._src.lib.mlir.dialects import memref
from jax.experimental.mosaic.gpu import dialect as mgpu_dialect # pylint: disable=g-importing-member
import jax.numpy as jnp
import numpy as np
import jax.experimental.mosaic.gpu as mgpu
try:
import torch
import torch.distributed as dist
import torch.distributed._symmetric_memory as symm_mem
except ImportError:
torch = None
# ruff: noqa: F405
# pylint: disable=g-complex-comprehension
class TorchTest(parameterized.TestCase):
def setUpClass():
torch.cuda.set_device("cuda:0")
torch.set_default_device("cuda")
if torch is None:
raise unittest.SkipTest("Test requires torch")
if not torch.cuda.is_available():
raise unittest.SkipTest("Test requires torch with CUDA support")
if (not jtu.test_device_matches(["cuda"]) or
not jtu.is_cuda_compute_capability_at_least("9.0")):
raise unittest.SkipTest("Only works on GPU with capability >= sm90")
device_count = torch.cuda.device_count()
for d1 in range(device_count - 1):
for d2 in range(d1 + 1, device_count):
if not torch.cuda.can_device_access_peer(d1, d2):
raise unittest.SkipTest("Test requires p2p access")
if jax.process_count() == 1:
raise unittest.SkipTest("Test requires multiple processes.")
if jax.device_count() != jax.process_count():
raise unittest.SkipTest("Need 1 device per process")
os.environ["RANK"] = str(jax.process_index())
os.environ["WORLD_SIZE"] = str(jax.process_count())
os.environ["MASTER_ADDR"] = "localhost"
os.environ["MASTER_PORT"] = "5728"
dist.init_process_group("nccl")
symm_mem.enable_symm_mem_for_group(dist.group.WORLD.group_name)
assert dist.is_initialized()
assert symm_mem.is_nvshmem_available()
symm_mem.set_backend("NVSHMEM")
symm_mem.empty(1) # Just to initialize NVSHMEM
def setUp(self):
self.prng = np.random.default_rng(1234)
self.context = mlir.make_ir_context()
if mgpu_dialect is not None:
mgpu_dialect.register_dialect(self.context)
self.enter_context(config.traceback_filtering("off"))
self.enter_context(self.context)
self.enter_context(ir.Location.unknown())
def test_get_device_id(self):
index = ir.IndexType.get()
def kernel_body(ctx, dst, _):
device_id = ctx.device_id()
memref.store(device_id, dst, [arith.constant(index, 0)])
out_shape = jax.ShapeDtypeStruct((1,), jnp.int32)
kernel = mgpu.as_torch_gpu_kernel(
kernel_body, (1, 1, 1), (128, 1, 1), (), out_shape, ()
)
gathered = torch.empty((2,), dtype=torch.int32)
dist.all_gather_into_tensor(gathered, kernel())
self.assertEqual(gathered.tolist(), list(range(jax.process_count())))
def test_remote_semaphore(self):
if dist.get_world_size() != 2:
self.skipTest("Test assumes 2 devices")
i32 = ir.IntegerType.get_signless(32)
def kernel(ctx, sem, _):
my_device = ctx.device_id()
other_device = arith.subi(arith.constant(i32, 1), my_device)
my_sem = mgpu.SemaphoreRef(mgpu.utils.memref_ptr(sem))
other_dst = ctx.to_remote(sem, other_device)
other_sem = mgpu.SemaphoreRef(mgpu.utils.memref_ptr(other_dst))
# We signal and wait a different amount on each device to make sure we're
# really communicating here.
other_sem.signal(arith.addi(arith.constant(i32, 1), other_device))
@mgpu.fori(arith.addi(arith.constant(i32, 1), my_device), None)
def wait_loop(i, _):
my_sem.wait(1)
sem_shape = jax.ShapeDtypeStruct((1,), jnp.int32)
kernel = mgpu.as_torch_gpu_kernel(
kernel, (1, 1, 1), (128, 1, 1), (), (), (), inout_shape=sem_shape
)
gathered = torch.empty((2,), dtype=torch.int32)
sem = symm_mem.empty((1,), dtype=torch.int32)
symm_mem.rendezvous(sem, dist.group.WORLD)
(sem_again,) = kernel(sem)
self.assertEqual(sem_again.data_ptr(), sem.data_ptr())
dist.all_gather_into_tensor(gathered, sem)
self.assertEqual(gathered.tolist(), [0, 0])
if __name__ == "__main__":
jt_multiprocess.main()
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/mosaic/gpu_torch_test_distributed.py",
"license": "Apache License 2.0",
"lines": 116,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/multiprocess/all_gather_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from absl.testing import parameterized
import jax
from jax import lax
from jax._src import test_multiprocess as jt_multiprocess
from jax._src import test_util as jtu
import jax.numpy as jnp
import numpy as np
class AllGatherTest(jt_multiprocess.MultiProcessTest):
@parameterized.parameters(
(np.int32,), (jnp.float32,), (jnp.float16,), (jnp.bfloat16,)
)
def test_all_gather_shard_map(self, dtype):
mesh_shape = (jax.process_count(), jax.local_device_count())
mesh = jtu.create_mesh(mesh_shape, ("x", "y"))
spec = jax.P("x", "y")
@jax.shard_map(
mesh=mesh, in_specs=spec, out_specs=jax.P(None, None), check_vma=False
)
def f(x):
out = lax.all_gather(x, "x", axis=0, tiled=True)
return lax.all_gather(out, "y", axis=1, tiled=True)
global_len = np.prod(mesh_shape)
global_arr = jnp.arange(global_len, dtype=dtype).reshape(mesh_shape)
sharding = jax.NamedSharding(mesh, spec)
global_xs = jax.make_array_from_callback(
mesh_shape, sharding, lambda index: global_arr[index]
)
out = f(global_xs)
for actual in out.addressable_shards:
jtu.check_close(actual.data, global_arr[actual.index])
if __name__ == "__main__":
jt_multiprocess.main()
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/multiprocess/all_gather_test.py",
"license": "Apache License 2.0",
"lines": 45,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/multiprocess/all_reduce_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from absl.testing import parameterized
import jax
from jax import lax
from jax import numpy as jnp
from jax._src import test_multiprocess as jt_multiprocess
from jax._src import test_util as jtu
import numpy as np
def randint_sample(shape):
return jax.random.randint(jax.random.PRNGKey(42), shape, -100, 100)
class AllReduceTest(jt_multiprocess.MultiProcessTest):
def test_psum_simple(self):
mesh = jtu.create_mesh((jax.device_count(),), "x")
spec = jax.P("x")
@jax.shard_map(mesh=mesh, in_specs=spec, out_specs=spec)
def f(x):
return lax.psum(x, "x")
out = f(jnp.array([1] * jax.device_count()))
for o in out.addressable_shards:
self.assertEqual(o.data, np.array([jax.device_count()]))
@parameterized.parameters(
(np.int32,), (jnp.float32,), (jnp.float16,), (jnp.bfloat16,)
)
def test_psum(self, dtype):
mesh_shape = (jax.process_count(), jax.local_device_count())
mesh = jtu.create_mesh(mesh_shape, ("x", "y"))
spec = jax.P("x", "y")
@jax.shard_map(mesh=mesh, in_specs=spec, out_specs=spec)
def f(x):
return lax.psum(x, ("x", "y"))
xs = (
jnp.arange(jax.local_device_count())
+ jax.process_index() * jax.local_device_count()
)
xs = jnp.expand_dims(xs, axis=0).astype(dtype)
sharding = jax.NamedSharding(mesh, spec)
global_xs = jax.make_array_from_process_local_data(sharding, xs, mesh_shape)
local_xs = jnp.sum(jnp.arange(jax.device_count())).reshape(1, 1)
out = f(global_xs)
for actual in out.addressable_shards:
jtu.check_close(actual.data, local_xs)
def test_psum_subset_devices(self):
mesh_shape = (jax.process_count(), jax.local_device_count())
mesh = jtu.create_mesh(mesh_shape, ("x", "y"))
spec = jax.P("x")
@jax.shard_map(mesh=mesh, in_specs=spec, out_specs=spec)
def f(x):
return lax.psum(x, "x")
xs = (
jnp.arange(jax.local_device_count())
+ jax.process_index() * jax.local_device_count()
)
xs = jnp.expand_dims(xs, axis=0)
sharding = jax.NamedSharding(mesh, spec)
global_xs = jax.make_array_from_process_local_data(sharding, xs, mesh_shape)
local_xs = (
jnp.arange(jax.device_count())
.reshape(mesh_shape)
.sum(axis=0, keepdims=True)
)
out = f(global_xs)
for actual in out.addressable_shards:
jtu.check_close(actual.data, local_xs)
def test_psum_multiple_operands(self):
mesh_shape = (jax.process_count(), jax.local_device_count())
mesh = jtu.create_mesh(mesh_shape, ("x", "y"))
spec = jax.P("x", "y")
sharding = jax.NamedSharding(mesh, spec)
x = (
jnp.arange(jax.local_device_count())
+ jax.process_index() * jax.local_device_count()
)
x = jnp.expand_dims(x, axis=(0, -1))
@jax.shard_map(mesh=mesh, in_specs=spec, out_specs=spec)
def f(x):
return lax.psum(x, ("x", "y"))
length = 100
xs = jnp.tile(x, (1, 1, length))
global_shape = mesh_shape + (length,)
global_xs = jax.make_array_from_process_local_data(sharding, xs, global_shape)
local_xs = jnp.sum(jnp.arange(jax.device_count())) * jnp.ones((1, 1, length))
out = f(global_xs)
for actual in out.addressable_shards:
jtu.check_close(actual.data, local_xs)
length = 200
xs = jnp.tile(x, (1, 1, length))
global_shape = mesh_shape + (length,)
global_xs = jax.make_array_from_process_local_data(sharding, xs, global_shape)
local_xs = jnp.sum(jnp.arange(jax.device_count())) * jnp.ones((1, 1, length))
out = f(global_xs)
for actual in out.addressable_shards:
jtu.check_close(actual.data, local_xs)
# TODO(dsuo): Remove this warning once PmapSharding is removed. We don't
# convert this to shard_map since axis_index_groups raises a
# NotImplementedError.
@jtu.ignore_warning(category=DeprecationWarning)
def test_psum_axis_index_groups(self):
devices = list(range(jax.device_count()))
axis_index_groups = [devices[0::2], devices[1::2]]
print(axis_index_groups, jax.devices())
f = jax.pmap(
lambda x: lax.psum(x, "i", axis_index_groups=axis_index_groups),
axis_name="i",
)
xs = randint_sample([jax.process_count(), jax.local_device_count(), 100])
out = f(xs[jax.process_index()])
xs = xs.reshape([jax.device_count(), 100])
group0_expected = sum(xs[0::2, :])
group1_expected = sum(xs[1::2, :])
if jax.config.jax_pmap_shmap_merge:
for i, shard in enumerate(out.addressable_shards):
device_id = i + jax.process_index() * jax.local_device_count()
expected = group0_expected if device_id % 2 == 0 else group1_expected
np.testing.assert_array_equal(np.squeeze(shard.data), expected)
else:
for i, actual in enumerate(out):
device_id = i + jax.process_index() * jax.local_device_count()
expected = group0_expected if device_id % 2 == 0 else group1_expected
np.testing.assert_array_equal(actual, expected)
if __name__ == "__main__":
jt_multiprocess.main()
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/multiprocess/all_reduce_test.py",
"license": "Apache License 2.0",
"lines": 133,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/multiprocess/all_to_all_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from absl.testing import parameterized
import jax
from jax import lax
from jax._src import test_multiprocess as jt_multiprocess
from jax._src import test_util as jtu
import jax.numpy as jnp
import numpy as np
class AllToAllTest(jt_multiprocess.MultiProcessTest):
@parameterized.parameters(
(np.int32,), (jnp.float32,), (jnp.float16,), (jnp.bfloat16,)
)
def test_all_to_all_shard_map(self, dtype):
rng = np.random.RandomState(42)
devices = jax.devices()
mesh = jax.sharding.Mesh(devices, ("i",))
device_to_index = {d: i for i, d in enumerate(devices)}
@jax.shard_map(
mesh=mesh,
in_specs=jax.P("i", None, None),
out_specs=jax.P("i", None, None),
)
def f(x):
x = jnp.squeeze(x, 0)
out = lax.all_to_all(x, "i", split_axis=0, concat_axis=0)
return jnp.expand_dims(out, 0)
shape = [
jax.process_count(),
jax.local_device_count(),
jax.device_count(),
100,
]
if jnp.issubdtype(dtype, jnp.floating):
xs = rng.randn(*shape).astype(dtype)
else:
xs = rng.randint(0, 100, size=shape).astype(dtype)
global_shape = (jax.device_count(), jax.device_count(), 100)
sharding = jax.NamedSharding(mesh, jax.P("i", None, None))
local_data = xs[jax.process_index()]
global_xs = jax.make_array_from_process_local_data(
sharding, local_data, global_shape
)
global_out = f(global_xs)
local_shards = global_out.addressable_shards
local_shards = sorted(local_shards, key=lambda s: device_to_index[s.device])
for shard in local_shards:
rank = device_to_index[shard.device]
actual = np.array(shard.data).squeeze(0) # (D, 100)
expected = np.reshape(xs[:, :, rank, :], [jax.device_count(), 100])
jtu.check_close(actual, expected)
if __name__ == "__main__":
jt_multiprocess.main()
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/multiprocess/all_to_all_test.py",
"license": "Apache License 2.0",
"lines": 64,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/multiprocess/array_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Multihost tests for jax.Array."""
import math
import unittest
from absl.testing import parameterized
import jax
from jax._src import array
from jax._src import sharding_impls
from jax._src import test_multiprocess as jt_multiprocess
from jax._src import test_util as jtu
from jax._src.lib import jaxlib_extension_version
import jax.numpy as jnp
from jax.sharding import PartitionSpec as P
import numpy as np
def create_array(shape, arr_sharding, global_data=None):
if global_data is None:
global_data = np.arange(math.prod(shape), dtype=np.float32).reshape(shape)
return array.make_array_from_callback(
shape, arr_sharding, lambda idx: global_data[idx],
dtype=global_data.dtype), global_data
def create_nonaddressable_array(shape, spec=None):
"""Creates an array that is non-addressable in half of the processes.
Args:
shape: Shape of the array.
spec: Sharding spec of the array. If None, the array is sharded over all
participating devices.
Returns:
A tuple of the created array and the global data.
"""
n_dev = len(jax.devices()) // 2
mesh = jax.make_mesh((n_dev,), ("x",), devices=jax.devices()[:n_dev],
axis_types=(jax.sharding.AxisType.Explicit,))
if spec is None:
spec = P("x")
s = jax.sharding.NamedSharding(mesh, spec)
return create_array(shape, s)
class ArrayTestMultiHost(jt_multiprocess.MultiProcessTest):
@parameterized.named_parameters(
(
"mesh_x_y",
P("x", "y"),
# device_id -> (index, replica_id)
{
0: ((slice(0, 2), slice(0, 1)), 0),
1: ((slice(0, 2), slice(1, 2)), 0),
2: ((slice(2, 4), slice(0, 1)), 0),
3: ((slice(2, 4), slice(1, 2)), 0),
4: ((slice(4, 6), slice(0, 1)), 0),
5: ((slice(4, 6), slice(1, 2)), 0),
6: ((slice(6, 8), slice(0, 1)), 0),
7: ((slice(6, 8), slice(1, 2)), 0),
},
(2, 1),
False,
False,
),
(
"mesh_x",
P("x"),
# device_id -> (index, replica_id)
{
0: ((slice(0, 2), slice(None)), 0),
1: ((slice(0, 2), slice(None)), 1),
2: ((slice(2, 4), slice(None)), 0),
3: ((slice(2, 4), slice(None)), 1),
4: ((slice(4, 6), slice(None)), 0),
5: ((slice(4, 6), slice(None)), 1),
6: ((slice(6, 8), slice(None)), 0),
7: ((slice(6, 8), slice(None)), 1),
},
(2, 2),
False,
False,
),
(
"mesh_y",
P("y"),
# device_id -> (index, replica_id)
{
0: ((slice(0, 4), slice(None)), 0),
1: ((slice(4, 8), slice(None)), 0),
2: ((slice(0, 4), slice(None)), 1),
3: ((slice(4, 8), slice(None)), 1),
4: ((slice(0, 4), slice(None)), 2),
5: ((slice(4, 8), slice(None)), 2),
6: ((slice(0, 4), slice(None)), 3),
7: ((slice(4, 8), slice(None)), 3),
},
(4, 2),
False,
True,
),
(
"mesh_xy",
P(("x", "y")),
# device_id -> (index, replica_id)
{
0: ((slice(0, 1), slice(None)), 0),
1: ((slice(1, 2), slice(None)), 0),
2: ((slice(2, 3), slice(None)), 0),
3: ((slice(3, 4), slice(None)), 0),
4: ((slice(4, 5), slice(None)), 0),
5: ((slice(5, 6), slice(None)), 0),
6: ((slice(6, 7), slice(None)), 0),
7: ((slice(7, 8), slice(None)), 0),
},
(1, 2),
False,
False,
),
(
"mesh_fully_replicated",
P(),
# device_id -> (index, replica_id)
{
0: ((slice(None), slice(None)), 0),
1: ((slice(None), slice(None)), 1),
2: ((slice(None), slice(None)), 2),
3: ((slice(None), slice(None)), 3),
4: ((slice(None), slice(None)), 4),
5: ((slice(None), slice(None)), 5),
6: ((slice(None), slice(None)), 6),
7: ((slice(None), slice(None)), 7),
},
(8, 2),
True,
True,
),
)
# Test does not work with non-contiguous device IDs.
@jtu.skip_on_devices("cpu")
def test_array_2d_shard(self, pspec, expected_idx_rid,
expected_shard_shape, expected_is_fully_replicated,
fetch_to_host):
if jtu.is_device_tpu("5", "e"):
raise unittest.SkipTest("Test fails on v5e")
global_mesh = jtu.create_mesh((4, 2), ("x", "y"), iota_order=True)
global_input_shape = (8, 2)
arr, global_input_data = create_array(
global_input_shape, jax.sharding.NamedSharding(global_mesh, pspec))
self.assertEqual(arr.is_fully_replicated, expected_is_fully_replicated)
for s in arr.addressable_shards:
sd = s.device.id
expected_index = expected_idx_rid[sd][0]
expected_replica_id = expected_idx_rid[sd][1]
self.assertEqual(s.index, expected_index)
self.assertEqual(s.replica_id, expected_replica_id)
self.assertEqual(s.data.shape, expected_shard_shape)
np.testing.assert_array_equal(np.asarray(s.data),
global_input_data[expected_index])
for s in arr.global_shards:
sd = s.device.id
expected_index = expected_idx_rid[sd][0]
expected_replica_id = expected_idx_rid[sd][1]
self.assertEqual(s.index, expected_index)
self.assertEqual(s.replica_id, expected_replica_id)
if s.data is not None:
self.assertEqual(s.data.shape, expected_shard_shape)
np.testing.assert_array_equal(np.asarray(s.data),
global_input_data[expected_index])
if fetch_to_host:
np.testing.assert_array_equal(arr._value, global_input_data)
else:
with self.assertRaisesRegex(
RuntimeError,
r"Fetching value for `jax.Array` that spans non-addressable \(non"
r" process local\) devices is not possible",
):
_ = arr._value
@parameterized.named_parameters(
("mesh_x_y_z", P("x", "y", "z"), (4, 2, 1), False),
("mesh_xy_z", P(("x", "y"), "z"), (2, 2, 2), False),
("mesh_z", P("z"), (4, 4, 2), True),
("mesh_None_z", P(None, None, "z"), (8, 4, 1), True),
)
def test_array_3d_shard(self, pspec, expected_shard_shape, fetch_to_host):
if jtu.is_device_tpu("5", "e"):
raise unittest.SkipTest("Test fails on v5e")
global_mesh = jtu.create_mesh((2, 2, 2), ("x", "y", "z"))
global_input_shape = (8, 4, 2)
arr, global_input_data = create_array(
global_input_shape, jax.sharding.NamedSharding(global_mesh, pspec))
self.assertEqual(arr.ndim, 3)
self.assertEqual(arr.size, 64)
self.assertEqual(arr.addressable_data(0).shape, expected_shard_shape)
if fetch_to_host:
np.testing.assert_array_equal(arr._value, global_input_data)
else:
with self.assertRaisesRegex(
RuntimeError,
r"Fetching value for `jax.Array` that spans non-addressable \(non"
r" process local\) devices is not possible",
):
_ = arr._value
def test_sharded_zeros_like(self):
if jtu.is_device_tpu("5", "e"):
raise unittest.SkipTest("Test fails on v5e")
global_mesh = jtu.create_mesh((4, 2), ("x", "y"))
input_shape = (8, 2)
a, input_data = create_array(
input_shape, jax.sharding.NamedSharding(global_mesh, P("x", "y")))
out = jnp.zeros_like(a)
expected = np.zeros_like(input_data)
self.assertLen(out.addressable_shards, 2)
for i in out.addressable_shards:
np.testing.assert_array_equal(i.data, expected[i.index])
self.assertEqual(i.replica_id, 0)
self.assertEqual(i.data.shape, (2, 1))
@parameterized.product(
spec=[
(("a", "b", "c"),),
(("a", "b"), "c"),
(("a", "b"),),
(("a",),),
(("b",),),
(("c",),),
((),),
],
infer_shape=[True, False],
)
def test_make_array_from_process_data(self, spec, infer_shape):
mesh = jtu.create_mesh((2, 2, 2), ("a", "b", "c"), iota_order=True)
# Key: number of processes. Value: axes corresponding to hosts.
host_axes_dict = {1: (), 2: ("a",), 4: ("a", "b"), 8: ("a", "b", "c")}
host_axes = set(host_axes_dict[jax.process_count()])
axis0_spec = (spec[0],) if isinstance(spec[0], str) else spec[0]
expected_process_shards = 2 ** len(host_axes.intersection(axis0_spec))
sharding = jax.sharding.NamedSharding(mesh, P(*spec))
replicated = jax.sharding.NamedSharding(mesh, P(None))
num_indices0 = sharding_impls.num_addressable_indices(sharding, 0, (8, 4))
num_indices1 = sharding_impls.num_addressable_indices(sharding, 1, (8, 4))
global_shape = None if infer_shape else (8, 4)
if infer_shape and num_indices1 < 4:
# If 2nd dimension is sharded across hosts (as it is on v5e 4x2)
# it would affect the computed global_shape, for test's simplicity we
# set explicit global_shape global shape to be 2.
global_shape = (8, 4)
process_index, num_shards = sharding_impls.get_process_index_and_count(
sharding,
0,
ndims=2,
)
self.assertEqual(num_shards, expected_process_shards)
process_data = np.arange(4)[None, :] + 4 * process_index
b = np.broadcast_to(process_data, (num_indices0, 4))
r = jax.make_array_from_process_local_data(sharding, b, global_shape)
self.assertEqual(r.shape, (8, 4))
self.assertEqual(r.sharding, sharding)
r = np.array(jax.jit(lambda x: x, out_shardings=replicated)(r))
global_target = [np.arange(4) + 4 * (i * num_shards // 8) for i in range(8)]
np.testing.assert_array_equal(sorted(r, key=lambda x: x[0]), global_target)
def test_make_array_from_process_data_shape_inference(self):
mesh = jtu.create_mesh((2, 2, 2), ("a", "b", "c"), iota_order=True)
sharding = jax.sharding.NamedSharding(mesh, P(("a", "b"), "c"))
r = jax.make_array_from_process_local_data(sharding, np.ones([4, 4]))
self.assertEqual(r.sharding, sharding)
process_to_target_shape = {1: (4, 4), 2: (8, 4), 4: (16, 4), 8: (16, 8)}
target_shape = process_to_target_shape[jax.process_count()]
self.assertEqual(target_shape, r.shape)
# Check if we can specify that local input actually contains full-span
# across different axes.
r2 = jax.make_array_from_process_local_data(
sharding, np.ones([4, 4]), global_shape=(target_shape[0], 4)
)
self.assertEqual(r2.sharding, sharding)
self.assertEqual((target_shape[0], 4), r2.shape)
r2 = jax.make_array_from_process_local_data(
sharding, np.ones([4, 4]), global_shape=(4, target_shape[1])
)
self.assertEqual(r2.sharding, sharding)
self.assertEqual((4, target_shape[1]), r2.shape)
r2 = jax.make_array_from_process_local_data(
sharding, np.ones([4, 4]), global_shape=(4, 4)
)
self.assertEqual(r2.sharding, sharding)
self.assertEqual((4, 4), r2.shape)
# Verify that we get not-supported message rather than non-uniform
with self.assertRaisesRegex(ValueError, ".*supported"):
jax.make_array_from_process_local_data(
sharding, np.ones([4, 4]), global_shape=(4, None)
)
@parameterized.named_parameters(
("shape_none", None),
("shape_tuple", (16, 4)),
("shape_pytree", {"a": (16, 4), "b": (16, 4)}),
)
@jtu.run_on_devices("cpu")
def test_make_array_from_process_local_data_pytree(self, global_shape):
mesh = jtu.create_mesh((2, 2, 2), ("a", "b", "c"), iota_order=True)
with jax.set_mesh(mesh):
r = jax.make_array_from_process_local_data(
P(("a", "b"), "c"),
{"a": np.ones([4, 4]), "b": np.ones([4, 4])},
global_shape=global_shape,
)
self.assertTupleEqual(r["a"].shape, (16, 4))
self.assertTupleEqual(r["b"].shape, (16, 4))
def test_multi_process_to_py(self):
global_mesh = jtu.create_mesh((4, 2), ("x", "y"))
input_shape = (8, 2)
a, input_data = create_array(
input_shape, jax.sharding.NamedSharding(global_mesh, P(None))
)
self.assertIsInstance(np.asarray(a), np.ndarray)
np.testing.assert_array_equal(np.asarray(a), input_data)
a, input_data = create_array(
input_shape, jax.sharding.NamedSharding(global_mesh, P("x"))
)
with self.assertRaisesRegex(
RuntimeError,
r"Fetching value for `jax.Array` that spans non-addressable \(non"
r" process local\) devices is not possible.",
):
np.asarray(a)
def test_multi_process_repr(self):
global_mesh = jtu.create_mesh((4, 2), ("x", "y"))
input_shape = (8, 2)
a, _ = create_array(input_shape,
jax.sharding.NamedSharding(global_mesh, P(None)))
val = repr(a)
self.assertIn("Array([[ 0., 1.]", val)
a, _ = create_array(input_shape,
jax.sharding.NamedSharding(global_mesh, P("x")))
val = repr(a)
self.assertEqual(val, "Array(shape=(8, 2), dtype=float32)")
def test_getitem(self):
if jtu.is_device_tpu("5", "e"):
raise unittest.SkipTest("Test fails on v5e")
global_mesh = jtu.create_mesh((4, 2), ("x", "y"))
input_shape = (16, 8)
arr, input_data = create_array(
input_shape, jax.sharding.NamedSharding(global_mesh, P("x", "y")))
s = arr[2:4, 0:1]
np.testing.assert_array_equal(s, input_data[2:4, 0:1])
p = arr[:2]
np.testing.assert_array_equal(p, input_data[:2])
def test_array_fully_replicated_shard(self):
global_mesh = jtu.create_mesh((4, 2), ("x", "y"))
inp_shape = (8, 2)
arr, inp_data = create_array(
inp_shape, jax.sharding.NamedSharding(global_mesh, P()))
fs = arr._fully_replicated_shard()
self.assertEqual(fs.shape, inp_shape)
self.assertLen(fs.sharding.device_set, 1)
self.assertEqual(fs.devices(), {jax.local_devices()[0]})
np.testing.assert_array_equal(fs, inp_data)
np.testing.assert_array_equal(arr.addressable_data(0), inp_data)
def test_device_put_uncommitted_array(self):
mesh = jtu.create_mesh((4, 2), ("x", "y"))
s = jax.sharding.NamedSharding(mesh, P("x", "y"))
inp = jnp.arange(16).reshape(8, 2)
out = jax.device_put(inp, s)
for shard in out.addressable_shards:
np.testing.assert_array_equal(shard.data, inp[shard.index])
self.assertEqual(out.sharding, s)
def test_device_put_np_array(self):
mesh = jtu.create_mesh((4, 2), ("x", "y"))
s = jax.sharding.NamedSharding(mesh, P("x", "y"))
inp = np.arange(16).reshape(8, 2)
out = jax.device_put(inp, s)
for shard in out.addressable_shards:
np.testing.assert_array_equal(shard.data, inp[shard.index])
self.assertEqual(out.sharding, s)
def test_device_put_python_scalar(self):
mesh = jtu.create_mesh((2, 2), ("x", "y"))
s = jax.sharding.NamedSharding(mesh, P())
out = jax.device_put(1, s)
for shard in out.addressable_shards:
np.testing.assert_array_equal(shard.data, 1)
self.assertEqual(out.sharding, s)
def test_device_put_python_scalar_different_error(self):
mesh = jtu.create_mesh((4, 2), ("x", "y"))
s = jax.sharding.NamedSharding(mesh, P())
with self.assertRaisesRegex(
AssertionError,
".*passed to device_put is not the same on each process.*"):
if jax.process_index() == 0:
jax.device_put(1., s)
else:
jax.device_put(2., s)
def test_device_put_uncommitted_array_different_inputs_error(self):
mesh = jtu.create_mesh((4, 2), ("x", "y"))
s = jax.sharding.NamedSharding(mesh, P("x", "y"))
with self.assertRaisesRegex(
AssertionError,
".*passed to device_put is not the same on each process.*"):
if jax.process_index() == 0:
jax.device_put(jnp.arange(16).reshape(8, 2), s)
else:
jax.device_put(jnp.arange(16, stop=32).reshape(8, 2), s)
def test_device_put_committed_array_error(self):
mesh = jtu.create_mesh((4, 2), ("x", "y"))
s = jax.sharding.NamedSharding(mesh, P("x", "y"))
inp = jax.device_put(jnp.arange(16).reshape(8, 2), jax.local_devices()[0])
with self.assertRaisesRegex(ValueError, "device_put's second argument.*"):
jax.device_put(inp, s)
def test_closed_over_global_array_error(self):
mesh = jtu.create_mesh((4, 2), ("x", "y"))
s = jax.sharding.NamedSharding(mesh, P("x", "y"))
arr, np_inp = create_array((8, 2), s)
@jax.jit
def f(x):
return x + arr
with self.assertRaisesRegex(
RuntimeError,
r"Closing over jax.Array that spans non-addressable \(non process"
r" local\) devices is not allowed"):
f(np_inp)
def test_zeros_like_use_mesh(self):
mesh = jtu.create_mesh((4, 2), ("x", "y"))
s = jax.sharding.NamedSharding(mesh, P())
np_inp = np.array(0, dtype=np.float32)
arr = jax.device_put(np_inp, s)
with jax.set_mesh(mesh):
out = jnp.zeros_like(arr)
np.testing.assert_array_equal(out, np_inp)
def test_sharding_process_indices_all_devices(self):
mesh = jax.make_mesh((jax.device_count(),), ("x",), devices=jax.devices(),
axis_types=(jax.sharding.AxisType.Explicit,))
s = jax.sharding.NamedSharding(mesh, P("x",))
expected_pids = {d.process_index for d in s.device_set}
self.assertEqual(s._internal_device_list.process_indices, expected_pids)
self.assertLen(s._internal_device_list.process_indices, jax.process_count())
class NonaddressableArrayTestMultiHost(jt_multiprocess.MultiProcessTest):
def test_create_nonaddressable_array(self):
y, x = create_nonaddressable_array((8, 8))
# The array is non-addressable in at least one process.
self.assertLess(len(y.sharding._internal_device_list.process_indices),
jax.process_count())
for a in y.addressable_shards:
np.testing.assert_array_equal(a.data, x[a.index])
fr, x = create_nonaddressable_array((8, 8), spec=P())
self.assertTrue(fr.sharding.is_fully_replicated)
self.assertLess(len(fr.sharding._internal_device_list.process_indices),
jax.process_count())
if fr.sharding.has_addressable_devices:
np.testing.assert_array_equal(x, fr)
def test_named_sharding_is_fully_addressable(self):
pid = 0
ds = jax.local_devices(process_index=pid)
mesh = jtu.create_mesh((len(ds),), ("x",))
s = jax.sharding.NamedSharding(mesh, P("x"))
self.assertEqual(s.is_fully_addressable, jax.process_index() == pid)
def test_single_device_sharding_is_fully_addressable(self):
d = jax.devices()[0]
s = jax.sharding.SingleDeviceSharding(d)
self.assertEqual(s.is_fully_addressable,
jax.process_index() == d.process_index)
def test_array_with_no_local_shards_has_valid_layout(self):
d = jax.devices()[0]
s = jax.sharding.SingleDeviceSharding(d)
shape = (8, 8)
np_inp = np.arange(math.prod(shape), dtype=np.int32).reshape(shape)
xs = []
if jax.process_index() == d.process_index:
x = jax.device_put(np_inp, s)
xs.append(x)
arr = jax.make_array_from_single_device_arrays(
shape, s, xs, dtype=jnp.int32)
self.assertIsNotNone(arr.format.layout)
def test_device_put_uncommitted_array_namedsharding(self):
n_local = len(jax.local_devices())
pid = 0
mesh = jax.make_mesh(
(n_local,), ("x",), devices=jax.local_devices(process_index=pid),
axis_types=(jax.sharding.AxisType.Explicit,))
s = jax.sharding.NamedSharding(mesh, P("x",))
inp = jnp.arange(16).reshape(8, 2)
out = jax.device_put(inp, s)
# device_put of an uncommitted array to a sharding that is addressable only
# in process `pid` should return an array with addressable shards only in
# process `pid`. In other processes, the returned array has no addressable
# shards.
expected_num_shards = n_local if jax.process_index() == pid else 0
self.assertLen(out.addressable_shards, expected_num_shards)
for shard in out.addressable_shards:
np.testing.assert_array_equal(shard.data, inp[shard.index])
self.assertEqual(out.sharding, s)
def test_device_put_numpy_array_namedsharding(self):
n_local = len(jax.local_devices())
pid = 1
mesh = jax.make_mesh(
(n_local,), ("x",), devices=jax.local_devices(process_index=pid),
axis_types=(jax.sharding.AxisType.Explicit,))
s = jax.sharding.NamedSharding(mesh, P("x",))
inp = np.arange(16).reshape(8, 2)
out = jax.device_put(inp, s)
# device_put of a numpy array to a sharding that is addressable only in
# process `pid` should return an array with addressable shards only in
# process `pid`. In other processes, the returned array has no addressable
# shards.
expected_num_shards = n_local if jax.process_index() == pid else 0
self.assertLen(out.addressable_shards, expected_num_shards)
for shard in out.addressable_shards:
np.testing.assert_array_equal(shard.data, inp[shard.index])
self.assertEqual(out.sharding, s)
def test_device_put_numpy_array_singledevice(self):
inp = np.arange(16).reshape(8, 2)
d = jax.devices()[0]
out = jax.device_put(inp, d)
# device_put of a numpy array to a sharding that is addressable only in
# process `pid` should return an array with addressable shards only in
# process `pid`. In other processes, the returned array has no addressable
# shards.
expected_num_shards = 1 if jax.process_index() == d.process_index else 0
self.assertLen(out.addressable_shards, expected_num_shards)
for shard in out.addressable_shards:
np.testing.assert_array_equal(shard.data, inp[shard.index])
self.assertEqual(out.sharding, jax.sharding.SingleDeviceSharding(d))
def test_device_put_to_device_error(self):
mesh = jax.make_mesh((jax.device_count(),), ("x",), devices=jax.devices(),
axis_types=(jax.sharding.AxisType.Explicit,))
s = jax.sharding.NamedSharding(mesh, P("x",))
inp = jax.device_put(jnp.arange(16).reshape(8, 2), s)
with self.assertRaisesRegex(ValueError,
"must be a fully addressable array or"):
nonlocal_pid = (jax.process_index() + 1) % jax.process_count()
jax.device_put(inp, jax.local_devices(process_index=nonlocal_pid)[0])
def test_make_array_from_callback(self):
n_local = jax.local_device_count()
pid = 1
mesh = jax.make_mesh(
(n_local,), ("x",), devices=jax.local_devices(process_index=pid),
axis_types=(jax.sharding.AxisType.Explicit,))
s = jax.sharding.NamedSharding(mesh, P("x",))
# Create an array that is non-addressable in processes besides `pid`.
global_data = np.arange(16, dtype=np.int32).reshape(8, 2)
arr = jax.make_array_from_callback(
global_data.shape, s, lambda idx: global_data[idx],
dtype=global_data.dtype)
# The returned array should only contain addressable shards in process
# `pid`.
expected_num_shards = n_local if jax.process_index() == pid else 0
self.assertLen(arr.addressable_shards, expected_num_shards)
np.testing.assert_array_equal(arr.shape, global_data.shape)
for shard in arr.addressable_shards:
np.testing.assert_array_equal(shard.data, global_data[shard.index])
def test_make_array_from_callback_prngkey(self):
n_local = jax.local_device_count()
pid = 1
mesh = jax.make_mesh(
(n_local,), ("x",), devices=jax.local_devices(process_index=pid),
axis_types=(jax.sharding.AxisType.Explicit,))
s = jax.sharding.NamedSharding(mesh, P("x",))
# Create a PRNG key array that is non-addressable in processes besides
# `pid`.
seeds = jnp.arange(8)
global_data = jax.vmap(lambda x: jax.random.key(seed=x))(seeds)
k = jax.random.key(0)
arr = jax.make_array_from_callback(
global_data.shape, s, lambda idx: global_data[idx],
dtype=k.dtype)
# The returned array should only contain addressable shards in process
# `pid`.
expected_num_shards = n_local if jax.process_index() == pid else 0
self.assertLen(arr.addressable_shards, expected_num_shards)
np.testing.assert_array_equal(arr.shape, global_data.shape)
for shard in arr.addressable_shards:
np.testing.assert_array_equal(shard.data.shape, (8 // n_local,))
def test_sharding_process_indices_device_subset(self):
n_devices = jax.device_count()
mesh = jax.make_mesh(
(n_devices // 2,), ("x",), devices=jax.devices()[:n_devices // 2],
axis_types=(jax.sharding.AxisType.Explicit,))
s = jax.sharding.NamedSharding(mesh, P("x",))
expected_pids = {d.process_index for d in s.device_set}
self.assertEqual(s._internal_device_list.process_indices, expected_pids)
self.assertLen(s._internal_device_list.process_indices,
jax.process_count() // 2)
def test_jit_no_local_devices_named_sharding(self):
x = np.arange(64).reshape(8, 8)
n_local = jax.local_device_count()
pid = 1
# Create a sharding that is non-addressable in processes besides `pid`.
mesh = jax.make_mesh(
(n_local,), ("x",), devices=jax.local_devices(process_index=pid),
axis_types=(jax.sharding.AxisType.Explicit,))
s = jax.sharding.NamedSharding(mesh, P("x",))
y = jax.device_put(x, s)
expected_num_shards = n_local if jax.process_index() == pid else 0
self.assertLen(y.addressable_shards, expected_num_shards)
@jax.jit
def f(x):
return x + 1
# The returned array should only contain addressable shards in process
# `pid`. No work is done in other processes.
z = f(y)
z.block_until_ready()
self.assertLen(z.addressable_shards, expected_num_shards)
if jax.process_index() == pid:
for shard in z.addressable_shards:
np.testing.assert_array_equal(shard.data, x[shard.index] + 1)
def test_jit_no_local_devices_named_sharding_collective(self):
x = np.arange(64).reshape(8, 8)
n_local = jax.local_device_count()
pid = 1
# Create a sharding that is non-addressable in processes besides `pid`.
mesh = jax.make_mesh(
(n_local,), ("x",), devices=jax.local_devices(process_index=pid),
axis_types=(jax.sharding.AxisType.Explicit,))
s = jax.sharding.NamedSharding(mesh, P("x",))
y = jax.device_put(x, s)
expected_num_shards = n_local if jax.process_index() == pid else 0
self.assertLen(y.addressable_shards, expected_num_shards)
@jax.jit
def f(x):
return jnp.sum(x)
# The returned array should only contain addressable shards in process
# `pid`. No work is done in other processes.
z = f(y)
z.block_until_ready()
self.assertLen(z.addressable_shards, expected_num_shards)
if jax.process_index() == pid:
expected = x.sum()
for shard in z.addressable_shards:
np.testing.assert_array_equal(shard.data, expected)
def test_jit_no_local_devices_single_device_sharding(self):
x = np.arange(64).reshape(8, 8)
pid = 1
# Create a single device sharding for a device local to process `pid`.
s = jax.sharding.SingleDeviceSharding(
jax.local_devices(process_index=pid)[0])
y = jax.device_put(x, s)
expected_num_shards = 1 if jax.process_index() == pid else 0
self.assertLen(y.addressable_shards, expected_num_shards)
@jax.jit
def f(x):
return x + 1
# The returned array should only contain an addressable shard in process
# `pid`. No work is done in other processes.
z = f(y)
z.block_until_ready()
self.assertLen(z.addressable_shards, expected_num_shards)
if jax.process_index() == pid:
np.testing.assert_array_equal(z.addressable_shards[0].data, x + 1)
def test_jit_fastpath_matmul(self):
mesh = jax.sharding.Mesh(
jax.devices()[: len(jax.devices()) // 2], axis_names=("devices"))
sharding = jax.sharding.NamedSharding(mesh, P())
x = jax.device_put(
jnp.arange(8 * 16, dtype=jnp.float32).reshape((8, 16)), sharding)
w = jax.device_put(
jnp.arange(16 * 4, dtype=jnp.float32).reshape((16, 4)), sharding)
jax.experimental.multihost_utils.sync_global_devices("start")
matmul = jax.jit(lambda x, w: x @ w, out_shardings=sharding)
_ = matmul(x, w)
y = matmul(x, w) # doesn't crash on second call
expected = x @ w
for shard in y.addressable_shards:
np.testing.assert_array_equal(shard.data, expected[shard.index])
def test_numpy_asarray_no_local_devices(self):
y, x = create_nonaddressable_array((8, 8), spec=P())
# In processes with local shards, we can fetch the value of the array using
# np.asarray, since the sharding is fully replicated. In processes with no
# local shards, attempting to fetch the NumPy array is an error.
if y.sharding.has_addressable_devices:
np.testing.assert_array_equal(np.asarray(y), x)
else:
with self.assertRaisesRegex(
RuntimeError,
r"Fetching value for `jax.Array` that spans non-addressable \(non"
r" process local\) devices is not possible."):
np.asarray(y)
def test_shard_map_no_local_devices(self):
x, x_np = create_nonaddressable_array((8, 8))
# shard_map works as expected when there are nonparticipating hosts.
shard_map_f = jax.shard_map(
lambda x: jax.lax.psum(x, "x"), mesh=x.sharding.mesh, in_specs=P("x"),
out_specs=P())
y = shard_map_f(x)
expected_y = sum(np.split(x_np, len(x.sharding.device_set)))
sharding_process_indices = x.sharding._internal_device_list.process_indices
expected_num_shards = (jax.local_device_count()
if jax.process_index() in sharding_process_indices
else 0)
self.assertLen(y.addressable_shards, expected_num_shards)
for shard in y.addressable_shards:
np.testing.assert_array_equal(shard.data, expected_y[shard.index])
def test_array_delete(self):
y, _ = create_nonaddressable_array((8, 8))
y.delete()
with self.assertRaisesRegex(RuntimeError, "Array has been deleted."):
y._check_if_deleted()
self.assertIsNone(y._npy_value)
self.assertIsNone(y._arrays)
def test_single_device_array_usage_after_delete(self):
y, _ = create_nonaddressable_array((8, 8))
y.delete()
with self.assertRaisesRegex(RuntimeError, "Array has been deleted."):
_ = y + 1
def test_repr(self):
y, _ = create_nonaddressable_array((8, 8))
if y.is_fully_addressable:
self.assertStartsWith(repr(y), "Array([[ 0., 1., 2., 3.,")
else:
self.assertEqual(repr(y), "Array(shape=(8, 8), dtype=float32)")
def test_str(self):
y, _ = create_nonaddressable_array((8, 8))
if y.is_fully_addressable:
self.assertStartsWith(str(y), "[[ 0. 1. 2. 3.")
else:
self.assertEqual(str(y), "Array(shape=(8, 8), dtype=float32)")
def test_format(self):
y, _ = create_nonaddressable_array((8, 8))
if y.is_fully_addressable:
self.assertStartsWith(format(y), "[[ 0. 1. 2. 3.")
else:
self.assertEqual(format(y), "Array(shape=(8, 8), dtype=float32)")
def test_array_astype(self):
y, _ = create_nonaddressable_array((8, 8))
y = y.astype(np.int32)
self.assertEqual(y.dtype, np.int32)
def test_sharded_add(self):
y, y_np = create_nonaddressable_array((8, 8))
z, z_np = create_nonaddressable_array((8, 8), spec=P())
out = y + z
expected = y_np + z_np
self.assertLen(out.addressable_shards, len(y.sharding.addressable_devices))
for shard in out.addressable_shards:
np.testing.assert_array_equal(shard.data, expected[shard.index])
def test_sharded_zeros_like(self):
y, _ = create_nonaddressable_array((8, 8))
out = jnp.zeros_like(y)
expected = jnp.zeros(y.shape, dtype=y.dtype)
self.assertLen(out.addressable_shards, len(y.sharding.addressable_devices))
for i in out.addressable_shards:
np.testing.assert_array_equal(i.data, expected[i.index])
def test_array_not_hashable(self):
y, _ = create_nonaddressable_array((8, 8))
with self.assertRaisesRegex(TypeError, "unhashable type"):
hash(y)
def test_on_device_size_in_bytes(self):
a, _ = create_nonaddressable_array((8, 8))
if not a.sharding.has_addressable_devices:
with self.assertRaisesRegex(
RuntimeError,
r"GetOnDeviceSizeInBytes\(\) is not yet supported for arrays with no "
r"addressable devices"):
a.on_device_size_in_bytes()
else:
shard_size = a.addressable_shards[0].data.on_device_size_in_bytes()
self.assertEqual(shard_size * len(a.global_shards),
a.on_device_size_in_bytes())
def test_array_is_ready(self):
y, _ = create_nonaddressable_array((8, 8))
y.is_ready() # doesn't crash
def test_array_copy_to_host_async(self):
y, x = create_nonaddressable_array((8, 8))
y.copy_to_host_async() # doesn't crash
for shard in y.addressable_shards:
np.testing.assert_array_equal(shard.data, x[shard.index])
def test_device_get_replicated(self):
y, x = create_nonaddressable_array((8, 8), spec=P())
if y.sharding.has_addressable_devices:
np.testing.assert_array_equal(jax.device_get(y), x)
else:
with self.assertRaisesRegex(
RuntimeError,
r"Fetching value for `jax.Array` that spans non-addressable \(non"
r" process local\) devices is not possible."):
jax.device_get(y)
# Skipped on GPU since there are two processes with one device each, so we
# can't construct a sharding that is nonaddressable in one of the processes
# and also not fully replicated (since the sharding must contain one device).
@jtu.skip_on_devices("gpu")
def test_device_get_sharded(self):
y, _ = create_nonaddressable_array((8, 8))
with self.assertRaisesRegex(
RuntimeError,
r"Fetching value for `jax.Array` that spans non-addressable \(non"
r" process local\) devices is not possible."):
jax.device_get(y)
def test_array_fully_replicated_shard(self):
y, x = create_nonaddressable_array((8, 8), spec=P())
if y.sharding.has_addressable_devices:
fs = y.addressable_data(0)
self.assertEqual(fs.shape, x.shape)
self.assertLen(fs.sharding.device_set, 1)
self.assertEqual(fs.devices(), {jax.local_devices()[0]})
np.testing.assert_array_equal(fs, x)
np.testing.assert_array_equal(y.addressable_data(0), x)
else:
with self.assertRaisesRegex(
RuntimeError, "FullyReplicatedShard: Array has no addressable shards."
):
y.addressable_data(0)
def test_array_iter_replicated(self):
y, _ = create_nonaddressable_array((8, 8), spec=P())
y_iter = iter(y)
self.assertLen(list(y_iter), 8)
# Skipped on GPU since the sharding contains one device and is therefore fully
# replicated.
@jtu.skip_on_devices("gpu")
def test_array_iter_sharded(self):
y, _ = create_nonaddressable_array((8, 8))
with self.assertRaises(AssertionError):
iter(y)
class CrossHostTransferTest(jt_multiprocess.MultiProcessTest):
@jtu.run_on_devices("cpu")
def test_cross_host_transfer_cpu_error(self):
x = np.arange(64).reshape(8, 8)
src_pid = 0
dst_pid = 1
src_sharding = jax.sharding.SingleDeviceSharding(
jax.local_devices(process_index=src_pid)[0])
dst_sharding = jax.sharding.SingleDeviceSharding(
jax.local_devices(process_index=dst_pid)[0])
y = jax.device_put(x, src_sharding)
with self.assertRaisesRegex(
ValueError, "does not support cross-host device transfers"):
jax.device_put(y, dst_sharding)
@parameterized.named_parameters(
("numpy", np.arange),
("uncommitted", jnp.arange),
)
@jtu.skip_on_devices("cpu")
def test_cross_host_transfer_single_device_sharding(self, arange_fn):
x = arange_fn(64).reshape(8, 8)
src_pid = 0
dst_pid = 1
src_sharding = jax.sharding.SingleDeviceSharding(
jax.local_devices(process_index=src_pid)[0])
dst_sharding = jax.sharding.SingleDeviceSharding(
jax.local_devices(process_index=dst_pid)[0])
y = jax.device_put(x, src_sharding)
z = jax.device_put(y, dst_sharding)
if jax.process_index() == dst_pid:
self.assertLen(z.addressable_shards, 1)
np.testing.assert_array_equal(z.addressable_shards[0].data, x)
else:
self.assertEmpty(z.addressable_shards)
@parameterized.named_parameters(
("numpy", np.arange),
("uncommitted", jnp.arange),
)
@jtu.skip_on_devices("cpu")
def test_cross_host_transfer_named_sharding(self, arange_fn):
x = arange_fn(64).reshape(8, 8)
n_local = jax.local_device_count()
src_pid = 0
dst_pid = 1
src_sharding = jax.sharding.NamedSharding(
jax.make_mesh((n_local,), ("x",),
devices=jax.local_devices(process_index=src_pid),
axis_types=(jax.sharding.AxisType.Explicit,)),
P("x"))
dst_sharding = jax.sharding.NamedSharding(
jax.make_mesh((n_local,), ("x",),
devices=jax.local_devices(process_index=dst_pid),
axis_types=(jax.sharding.AxisType.Explicit,)),
P("x"))
y = jax.device_put(x, src_sharding)
z = jax.device_put(y, dst_sharding)
if jax.process_index() == dst_pid:
self.assertLen(z.addressable_shards, n_local)
for shard in z.addressable_shards:
np.testing.assert_array_equal(shard.data, x[shard.index])
else:
self.assertEmpty(z.addressable_shards)
@jtu.skip_on_devices("cpu")
def test_cross_host_transfer_named_sharding_replicated(self):
x = np.arange(64).reshape(8, 8)
n_dev = jax.device_count() // 2
src_sharding = jax.sharding.NamedSharding(
jax.make_mesh((n_dev,), ("x",), devices=jax.devices()[:n_dev],
axis_types=(jax.sharding.AxisType.Explicit,)),
P()
)
dst_sharding = jax.sharding.NamedSharding(
jax.make_mesh((n_dev,), ("x",), devices=jax.devices()[n_dev:],
axis_types=(jax.sharding.AxisType.Explicit,)),
P()
)
y = jax.device_put(x, src_sharding)
z = jax.device_put(y, dst_sharding)
for shard in z.addressable_shards:
np.testing.assert_array_equal(shard.data, x[shard.index])
@parameterized.named_parameters(
("numpy", np.arange),
("uncommitted", jnp.arange),
)
@jtu.skip_on_devices("cpu")
def test_cross_host_transfer_batched(self, arange_fn):
if jaxlib_extension_version < 400 and arange_fn == np.arange:
self.skipTest("This functionality is not yet supported in jaxlib.")
num_arrays = 3
xs = []
for i in range(1, num_arrays + 1):
xs.append(arange_fn(64 * i).reshape(8, 8 * i))
# TODO(emilyaf): Smaller sizes fail on TPU because the dst buffer size
# returned by TransferSizeUtil::ShapeSizeCompact is larger than the src
# buffer size. Investigate this further.
# xs.append(jnp.arange(16 * i).reshape(8, 2 * i))
xs[0] = xs[0].astype(jnp.float32)
n_local = jax.local_device_count()
src_pid = 0
dst_pid = 1
src_sharding = jax.sharding.NamedSharding(
jax.make_mesh((n_local,), ("x",),
devices=jax.local_devices(process_index=src_pid),
axis_types=(jax.sharding.AxisType.Explicit,)),
P("x"))
dst_sharding = jax.sharding.NamedSharding(
jax.make_mesh((n_local,), ("x",),
devices=jax.local_devices(process_index=dst_pid),
axis_types=(jax.sharding.AxisType.Explicit,)),
P("x"))
ys = jax.device_put(xs, src_sharding)
zs = jax.device_put(ys, dst_sharding)
for (x, z) in zip(xs, zs):
if jax.process_index() == dst_pid:
self.assertLen(z.addressable_shards, n_local)
for shard in z.addressable_shards:
np.testing.assert_array_equal(shard.data, x[shard.index])
else:
self.assertEmpty(z.addressable_shards)
@jtu.skip_on_devices("cpu")
def test_device_to_cpu_transfer_jit(self):
x = jnp.arange(64).reshape(8, 8)
with self.assertWarnsRegex(
DeprecationWarning,
r"backend and device argument on jit is deprecated",
):
cpu_transfer_f = jax.jit(lambda x: x + 1, backend="cpu")
cpu_transfer_f(x) # Should not raise a cross-host transfer error.
@jtu.skip_on_devices("cpu")
def test_device_put_to_cpu(self):
x = jnp.arange(64).reshape(8, 8)
devices = jax.devices()
cpu_devices = jax.devices(backend="cpu")
num_devices = min(len(devices), len(cpu_devices))
# Create CPU and GPU/TPU shardings that are not fully addressable.
cpu_sharding = jax.sharding.NamedSharding(
jax.make_mesh(
(num_devices,), ("x",), devices=cpu_devices[:num_devices],
axis_types=(jax.sharding.AxisType.Explicit,)),
P("x"))
sharding = jax.sharding.NamedSharding(
jax.make_mesh(
(num_devices,), ("x",), devices=devices[:num_devices],
axis_types=(jax.sharding.AxisType.Explicit,)),
P("x"))
y = jax.device_put(x, sharding)
# device_put of a GPU/TPU array to the CPU sharding should raise a helpful
# error.
with self.assertRaisesRegex(
ValueError, ("For a cross-host reshard in multi-controller JAX|"
"device_put's second argument must be a Device")):
jax.device_put(y, cpu_sharding)
@jtu.skip_on_devices("cpu")
def test_device_put_with_mixed_local_and_remote_transfers(self):
if jaxlib_extension_version < 398:
self.skipTest("This functionality is not yet supported in jaxlib.")
if jax.local_device_count() < 2:
self.skipTest("Need at least 2 local devices for this test.")
x = jnp.arange(64).reshape(8, 8)
src_sharding = jax.sharding.NamedSharding(
jax.make_mesh((jax.local_device_count(),), ("x",),
devices=jax.local_devices(process_index=0),
axis_types=(jax.sharding.AxisType.Explicit,)),
P("x"))
# Half of the shards require cross-host transfers and half require local
# transfers.
dst_devices = (
jax.local_devices(process_index=1)[:jax.local_device_count() // 2]
+ jax.local_devices(process_index=0)[:jax.local_device_count() // 2])
dst_sharding = jax.sharding.NamedSharding(
jax.make_mesh((jax.local_device_count(),), ("x",), devices=dst_devices,
axis_types=(jax.sharding.AxisType.Explicit,)),
P("x"))
y = jax.device_put(x, src_sharding)
z = jax.device_put(y, dst_sharding)
if jax.process_index() in (0, 1):
self.assertLen(z.addressable_shards, jax.local_device_count() // 2)
for shard in z.addressable_shards:
np.testing.assert_array_equal(shard.data, x[shard.index])
@parameterized.named_parameters(
("numpy", np.arange),
("uncommitted", jnp.arange),
)
@jtu.skip_on_devices("cpu")
def test_device_put_to_device(self, arange_fn):
if jaxlib_extension_version < 400:
self.skipTest("This functionality is not yet supported in jaxlib.")
x = arange_fn(64).reshape(8, 8)
src_pid = 0
dst_pid = 1
src_device = jax.local_devices(process_index=src_pid)[0]
dst_device = jax.local_devices(process_index=dst_pid)[0]
y = jax.device_put(x, src_device)
z = jax.device_put(y, dst_device)
if jax.process_index() == dst_pid:
self.assertLen(z.addressable_shards, 1)
np.testing.assert_array_equal(z.addressable_shards[0].data, x)
else:
self.assertEmpty(z.addressable_shards)
if __name__ == "__main__":
jt_multiprocess.main()
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/multiprocess/array_test.py",
"license": "Apache License 2.0",
"lines": 1010,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/multiprocess/device_id_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import jax
from jax._src import test_multiprocess as jt_multiprocess
from jax._src import test_util as jtu
class DeviceIdTest(jt_multiprocess.MultiProcessTest):
def testDeviceIds(self):
# TODO(phawkins): TPU process IDs won't necessarily match the global
# process index.
if not jtu.test_device_matches(["tpu"]):
self.assertEqual(
jax.process_index(),
jt_multiprocess.MULTIPROCESS_TEST_WORKER_ID.value,
)
self.assertLen(
jax.devices(),
jt_multiprocess.NUM_PROCESSES.value * jax.local_device_count(),
)
self.assertEqual(
jax.local_devices()[0].process_index,
jax.process_index(),
)
def testPrimitive(self):
with jax.default_device(jax.local_devices(backend="cpu")[0]):
self.assertEqual(2, jax.lax.neg(jax.lax.neg(2)))
def testJit(self):
"""Verifies that local computation works inside a distributed job."""
x = jax.device_put(1)
self.assertEqual(x, 1)
y = jax.jit(lambda x: x + 1)(x)
self.assertEqual(y, 2)
def testDefaultDevicePlatformString(self):
with jax.default_device("cpu"):
result = jax.jit(lambda x: x + 1)(1)
self.assertEqual(result.device.platform, "cpu")
self.assertEqual(result.device, jax.local_devices(backend="cpu")[0])
result = jax.jit(lambda x: x + 1)(1)
self.assertEqual(result.device.platform, jax.default_backend())
self.assertEqual(result.device, jax.local_devices()[0])
# def testCrossProcessReduceScatter(self):
# i = multiprocess_test.MULTIPROCESS_TEST_WORKER_ID.value
# n = multiprocess_test.NUM_PROCESSES.value
# f = jax.pmap(
# lambda x: lax.psum_scatter(
# x,
# "i",
# ),
# axis_name="i",
# )
# x = np.arange(n * n).reshape(n, n)
# out = f(x[i : i + 1])
# expected = np.sum(x, axis=0)
# np.testing.assert_allclose(expected[i : i + 1], out)
if __name__ == "__main__":
jt_multiprocess.main()
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/multiprocess/device_id_test.py",
"license": "Apache License 2.0",
"lines": 66,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/multiprocess/host_callback_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for host_callback on multi-host setup."""
import unittest
import jax
from jax import lax
from jax import numpy as jnp
from jax._src import pjit
from jax._src import test_multiprocess as jt_multiprocess
from jax._src import test_util as jtu
from jax.experimental import io_callback
from jax.experimental import multihost_utils
from jax.sharding import PartitionSpec as P
import numpy as np
class _CollectCallbacks:
"""Collect the callback arguments."""
def __init__(self, test_method_name):
self.collected = []
self.test_method_name = test_method_name
def collect(self, what) -> None:
print(f"collect[{self.test_method_name}]: {what}")
self.collected.append(what)
callback_collector = None
NR_PROCESSES = 4
NR_LOCAL_DEVICES = 2
NR_DEVICES = NR_PROCESSES * NR_LOCAL_DEVICES
def sorted_devices():
devices = sorted(
jax.devices(),
key=lambda d: (d.process_index, getattr(d, "core_on_chip", 0)),
)
if len(devices) != NR_DEVICES:
raise unittest.SkipTest("Test assumes that it runs on 8 devices.")
if jax.process_count() != NR_PROCESSES:
raise unittest.SkipTest(f"Test assumes we have {NR_PROCESSES} processes.")
return devices
class IoCallbackMultiProcessTest(jtu.JaxTestCase,
jt_multiprocess.MultiProcessTest):
def setUp(self):
super(jtu.JaxTestCase, self).setUp()
global callback_collector
callback_collector = _CollectCallbacks(self._testMethodName)
def tearDown(self):
super(jtu.JaxTestCase, self).tearDown()
jax.effects_barrier()
def test_pure_callback_pmap(self):
# x_global: i32[D, 2] = [[0, 1], [10, 11], [20, 21], ...]
# x_local: i32[L, 2]
x_global = np.arange(100, dtype=np.int32).reshape((10, 10))[:NR_DEVICES, :2]
process_idx = jax.process_index()
local_device_idx = process_idx * NR_LOCAL_DEVICES
x_local = x_global[local_device_idx:local_device_idx + NR_LOCAL_DEVICES]
def func(x): # Runs on each device.
sum_global = jax.lax.psum(x, "d")
return jax.pure_callback(callback_func,
x, # result_shapes_dtype
lax.axis_index("d"), x, sum_global)
def callback_func(axis_index, x, sum_global):
callback_collector.collect((axis_index, x, sum_global))
return x * np.array(3, np.int32) + sum_global
pmap_func = jax.pmap(func, axis_name="d", devices=sorted_devices())
res = pmap_func(x_local)
expected_sum_global = np.sum(x_global, axis=0, dtype=np.int32)
# On each host we only get the local result.
self.assertAllClose(x_local * np.array(3, np.int32) + expected_sum_global,
res)
jax.effects_barrier()
# Each process gets only the callbacks for its local devices.
self.assertAllClose(
sorted(callback_collector.collected, key=lambda x: x[0]),
[(np.array(process_idx * NR_LOCAL_DEVICES, dtype=np.int32),
np.array([10 * local_device_idx,
10 * local_device_idx + 1], dtype=np.int32),
expected_sum_global),
(np.array(process_idx * NR_LOCAL_DEVICES + 1, dtype=np.int32),
np.array([10 * local_device_idx + 10,
10 * local_device_idx + 11], dtype=np.int32),
expected_sum_global)])
@jtu.ignore_warning(category=DeprecationWarning)
def test_io_callback_pjit(self):
devices = np.array(sorted_devices()).reshape(
(NR_PROCESSES, NR_LOCAL_DEVICES))
mesh = jax.sharding.Mesh(devices, ["p", "l"])
# x_global: i32[P, L, 3] = [[[0, 1, 2], [10, 11, 12]],
# [[100, 101, 102], [110, 111, 112]],
# ...]
# x_local: i32[1, L, 3]
# y: i32[3, 5]
x_global = jnp.arange(
1000, dtype=jnp.int32).reshape(
(10, 10, 10))[:NR_PROCESSES, :NR_LOCAL_DEVICES, :3]
process_id = jax.process_index()
x_local = x_global[process_id:process_id + 1]
def callback_times5_func(x):
callback_collector.collect(x)
return x * np.array(5, np.int32)
def fun(x_local):
return io_callback(callback_times5_func,
x_local, # result shape dtypes
x_local)
expected_res = x_local * np.array(5, np.int32)
pjit_fun = pjit.pjit(fun,
in_shardings=P("p", "l"),
out_shardings=P("p", "l"))
with mesh:
gx = multihost_utils.host_local_array_to_global_array(
x_local, mesh, P("p", "l"))
global_res = pjit_fun(gx)
res = multihost_utils.global_array_to_host_local_array(
global_res, mesh, P("p", "l"))
self.assertAllClose(expected_res, res)
jax.effects_barrier()
if jax.process_index() == 0:
# All calls are on the process 0; the 100s digit specifies the device
self.assertAllClose(callback_collector.collected,
[np.array([[[0, 1, 2],
[10, 11, 12]],
[[100, 101, 102],
[110, 111, 112]],
[[200, 201, 202],
[210, 211, 212]],
[[300, 301, 302],
[310, 311, 312]]], dtype=np.int32)])
else:
self.assertAllClose(callback_collector.collected, [])
if __name__ == "__main__":
jt_multiprocess.main()
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/multiprocess/host_callback_test.py",
"license": "Apache License 2.0",
"lines": 138,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/multiprocess/key_value_store_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Distributed key value store test."""
import jax
from jax._src import distributed
from jax._src import test_multiprocess as jt_multiprocess
class KeyValueStoreTest(jt_multiprocess.MultiProcessTest):
def testBlockingKeyValueGet(self):
client = distributed.global_state.client
key = 'test_key'
expected_value = 'JAX is great!'
timeout_in_ms = 1000
if jax.process_index() == 0:
client.key_value_set(key, expected_value)
actual_value = client.blocking_key_value_get(key, timeout_in_ms)
self.assertEqual(expected_value, actual_value)
def testBlockingKeyValueSetTwice(self):
client = distributed.global_state.client
key = 'test_key_' + str(jax.process_index())
expected_value = 'JAX is great!'
with self.assertRaisesRegex(
jax.errors.JaxRuntimeError,
r'ALREADY_EXISTS: key .* already exists.'
):
client.key_value_set(key, expected_value)
client.key_value_set(key, expected_value)
def testBlockingKeyValueSetTwice_Overwrite(self):
client = distributed.global_state.client
key = 'test_key_overwrite_' + str(jax.process_index())
initial_value = 'JAX is okay!'
overwritten_value = 'JAX is great!'
timeout_in_ms = 1000
client.key_value_set(key, initial_value)
client.key_value_set(key, overwritten_value, allow_overwrite=True)
actual_value = client.blocking_key_value_get(key, timeout_in_ms)
self.assertEqual(overwritten_value, actual_value)
def testBlockingKeyValueGetBytes(self):
client = distributed.global_state.client
key = 'test_key2'
expected_value = b'JAX is great!'
timeout_in_ms = 1000
if jax.process_index() == 0:
client.key_value_set_bytes(key, expected_value)
actual_value = client.blocking_key_value_get_bytes(key, timeout_in_ms)
self.assertEqual(expected_value, actual_value)
def testKeyValueTryGet(self):
client = distributed.global_state.client
key = 'test_key_try_get'
expected_value = 'JAX is great!'
if jax.process_index() == 0:
client.key_value_set(key, expected_value)
client.wait_at_barrier('kv_try_get_barrier', 1000) # 1 second.
actual_value = client.key_value_try_get(key)
self.assertEqual(expected_value, actual_value)
def testKeyValueTryGet_NotFound(self):
client = distributed.global_state.client
key = 'test_key_not_found'
with self.assertRaisesRegex(
jax.errors.JaxRuntimeError,
r'NOT_FOUND: Config key .* not found.'
):
client.key_value_try_get(key)
def testKeyValueTryGetBytes(self):
client = distributed.global_state.client
key = 'test_key_try_get_bytes'
expected_value = b'JAX is great!'
if jax.process_index() == 0:
client.key_value_set_bytes(key, expected_value)
client.wait_at_barrier('kv_try_get_bytes_barrier', 1000) # 1 second.
actual_value = client.key_value_try_get_bytes(key)
self.assertEqual(expected_value, actual_value)
def testKeyValueDirGet(self):
client = distributed.global_state.client
kvs = [('dir/key0', 'value0'), ('dir/key2', 'value2'),
('dir/nested/key3', 'value3')]
timeout_in_ms = 1000
if jax.process_index() == 0:
for kv in kvs:
client.key_value_set(kv[0], kv[1])
client.wait_at_barrier('wait_for_kv_set1', timeout_in_ms)
actual_kvs = client.key_value_dir_get('dir/')
self.assertSameElements(kvs, actual_kvs)
def testKeyValueDirGetBytes(self):
client = distributed.global_state.client
kvs = [('dir2/key0', b'value0'), ('dir2/key2', b'avalue2'),
('dir2/nested/key3', b'avalue3')]
timeout_in_ms = 1000
if jax.process_index() == 0:
for kv in kvs:
client.key_value_set_bytes(kv[0], kv[1])
client.wait_at_barrier('wait_for_kv_set2', timeout_in_ms)
actual_kvs = client.key_value_dir_get_bytes('dir2/')
self.assertSameElements(kvs, actual_kvs)
def testLargeKeyValueDirGet(self):
client = distributed.global_state.client
value_size = 1024 * 1024 # bytes
num_keys = 10
kvs = [(f'dir3/key{i}', 'x' * value_size) for i in range(num_keys)]
timeout_in_ms = 30 * 1000
if jax.process_index() == 0:
for kv in kvs:
client.key_value_set(kv[0], kv[1])
client.wait_at_barrier('wait_for_kv_set3', timeout_in_ms)
actual_kvs = client.key_value_dir_get('dir3/')
self.assertSameElements(kvs, actual_kvs)
if __name__ == '__main__':
jt_multiprocess.main()
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/multiprocess/key_value_store_test.py",
"license": "Apache License 2.0",
"lines": 118,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/multiprocess/multihost_utils_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Multihost tests for pjit."""
import math
import unittest
from absl.testing import parameterized
import jax
from jax import numpy as jnp
from jax._src import test_multiprocess as jt_multiprocess
from jax._src import test_util as jtu
from jax.experimental import multihost_utils
from jax.sharding import PartitionSpec as P
import numpy as np
class MultiHostUtilsTest(jt_multiprocess.MultiProcessTest):
def test_process_allgather_stacked(self):
elems_per_host = 4
num_processes = jax.process_count()
x = jnp.ones((4,)).reshape((2, 2))
out = multihost_utils.process_allgather(x, tiled=False)
self.assertEqual(out.shape, (num_processes, 2, 2))
np.testing.assert_array_equal(out, np.stack([x] * num_processes))
x = jnp.ones((64,)).reshape((8, 4, 2))
out = multihost_utils.process_allgather(x, tiled=False)
self.assertEqual(out.shape, (num_processes, 8, 4, 2))
np.testing.assert_array_equal(out, np.stack([x] * num_processes))
x = np.arange(elems_per_host) + jax.process_index() * elems_per_host
out = multihost_utils.process_allgather(x, tiled=False)
self.assertEqual(out.shape, (num_processes, 4))
np.testing.assert_array_equal(
out,
np.arange(elems_per_host * jax.process_count()).reshape(
num_processes, elems_per_host
),
)
x = np.array(0) + jax.process_index() * elems_per_host
out = multihost_utils.process_allgather(x, tiled=False)
self.assertEqual(out.shape, (num_processes,))
np.testing.assert_array_equal(
out, np.arange(num_processes) * elems_per_host
)
def test_process_allgather_concatenated(self):
elems_per_host = 4
num_processes = jax.process_count()
x = jnp.ones((4,)).reshape((2, 2))
out = multihost_utils.process_allgather(x, tiled=True)
self.assertEqual(out.shape, (2 * num_processes, 2))
np.testing.assert_array_equal(out, np.concatenate([x] * num_processes))
x = jnp.ones((64,)).reshape((8, 4, 2))
out = multihost_utils.process_allgather(x, tiled=True)
self.assertEqual(out.shape, (8 * num_processes, 4, 2))
np.testing.assert_array_equal(out, np.concatenate([x] * num_processes))
x = np.arange(elems_per_host) + jax.process_index() * elems_per_host
out = multihost_utils.process_allgather(x, tiled=True)
self.assertEqual(out.shape, (elems_per_host * num_processes,))
np.testing.assert_array_equal(
out, np.arange(elems_per_host * jax.process_count())
)
x = np.array(0) + jax.process_index() * elems_per_host
out = multihost_utils.process_allgather(x, tiled=True)
self.assertEqual(out.shape, (num_processes,))
np.testing.assert_array_equal(
out, np.arange(num_processes) * elems_per_host
)
def test_process_allgather_set_mesh(self):
devices = jax.devices()[1:] + [jax.devices()[0]]
user_mesh = jax.sharding.Mesh(
np.array(devices).reshape(jax.device_count(), 1, 1),
('x', 'y', 'z'),
)
x = jnp.ones((4,)).reshape((2, 2))
# process_allgather should not be impacted by any global mesh context.
with jax.set_mesh(user_mesh):
num_processes = jax.process_count()
out = multihost_utils.process_allgather(x, tiled=True)
self.assertEqual(out.shape, (2 * num_processes, 2))
np.testing.assert_array_equal(out, np.concatenate([x] * num_processes))
@jtu.ignore_warning(
category=DeprecationWarning,
message='jax.sharding.PmapSharding is deprecated',
)
def test_broadcast_one_to_all(self):
elems_per_host = 4
x = np.arange(elems_per_host) + jax.process_index() * elems_per_host
out = multihost_utils.broadcast_one_to_all((x, x))
jax.tree.map(
lambda x: np.testing.assert_array_equal( # pylint: disable=g-long-lambda
x, np.arange(elems_per_host)
),
out,
)
x = np.array(0) + jax.process_index() * elems_per_host
out = multihost_utils.broadcast_one_to_all(x)
np.testing.assert_array_equal(out, np.array(0))
@jtu.ignore_warning(
category=DeprecationWarning,
message='jax.sharding.PmapSharding is deprecated',
)
def test_broadcast_one_to_all_set_mesh(self):
devices = jax.devices()[1:] + [jax.devices()[0]]
user_mesh = jax.sharding.Mesh(
np.array(devices).reshape(jax.device_count(), 1, 1),
('x', 'y', 'z'),
)
# broadcast_one_to_all should not be impacted by any global mesh context.
with jax.set_mesh(user_mesh):
elems_per_host = 4
x = np.arange(elems_per_host) + jax.process_index() * elems_per_host
out = multihost_utils.broadcast_one_to_all((x, x))
jax.tree.map(
lambda x: np.testing.assert_array_equal( # pylint: disable=g-long-lambda
x, np.arange(elems_per_host)
),
out,
)
x = np.array(0) + jax.process_index() * elems_per_host
out = multihost_utils.broadcast_one_to_all(x)
np.testing.assert_array_equal(out, np.array(0))
@jtu.ignore_warning(
category=DeprecationWarning,
message='jax.sharding.PmapSharding is deprecated',
)
def test_broadcast_one_to_all_uint8(self):
elems_per_host = 4
x = (np.arange(elems_per_host, dtype=jnp.uint8) +
jax.process_index() * elems_per_host)
out = multihost_utils.broadcast_one_to_all((x, x))
jax.tree.map(
lambda x: np.testing.assert_array_equal( # pylint: disable=g-long-lambda
x, np.arange(elems_per_host, dtype=jnp.uint8)
),
out,
)
jax.tree.map(lambda o: self.assertEqual(o.dtype, jnp.uint8), out)
x = np.array(0, dtype=jnp.uint8) + jax.process_index() * elems_per_host
out = multihost_utils.broadcast_one_to_all(x)
self.assertEqual(out.dtype, jnp.uint8)
np.testing.assert_array_equal(out, np.array(0, dtype=jnp.uint8))
def test_sync_global_devices(self):
multihost_utils.sync_global_devices('test sync global devices')
def test_sync_global_devices_error(self):
# All processes should raise.
with self.assertRaises(AssertionError):
if jax.process_index() == 0:
multihost_utils.sync_global_devices('test message')
else:
multihost_utils.sync_global_devices('test message2')
def test_sync_global_devices_mesh_context_manager(self):
global_mesh = jtu.create_mesh((2, 2), ('x', 'y'), iota_order=True)
with global_mesh:
multihost_utils.sync_global_devices('test sync global devices')
def test_assert_equal_global(self):
mesh = jtu.create_mesh((8,), 'x')
shape = (8, 2)
np_inp = np.arange(math.prod(shape)).reshape(shape)
inp = jax.make_array_from_callback(
shape, jax.NamedSharding(mesh, P()), lambda idx: np_inp[idx])
multihost_utils.assert_equal(inp)
def test_process_allgather_cache_hit(self):
x = jnp.ones((4,)).reshape(2, 2)
y = jnp.arange(4.0).reshape(2, 2)
num_processes = jax.process_count()
with jtu.count_pjit_cpp_cache_miss() as count:
out = multihost_utils.process_allgather(x, tiled=False)
out2 = multihost_utils.process_allgather(y, tiled=False)
# Cpp cache hit.
self.assertEqual(count(), 1)
self.assertEqual(out.shape, (num_processes, 2, 2))
np.testing.assert_array_equal(out, np.stack([x] * num_processes))
self.assertEqual(out2.shape, (num_processes, 2, 2))
np.testing.assert_array_equal(out2, np.stack([y] * num_processes))
def test_reshard(self):
mesh1 = jtu.create_mesh((8,), 'x')
mesh2 = jax.sharding.Mesh(
np.asarray(jax.devices()[::-1]).reshape(4, 2), ('x', 'y')
)
shape = (8, 2)
np_inp = np.arange(math.prod(shape)).reshape(shape)
inp = jax.make_array_from_callback(
shape,
jax.sharding.NamedSharding(mesh1, P('x')),
lambda idx: np_inp[idx],
)
out = jax.device_put(inp, jax.sharding.NamedSharding(mesh2, P('x', 'y')))
self.assertIsInstance(out.sharding, jax.sharding.NamedSharding)
for s in out.addressable_shards:
np.testing.assert_array_equal(s.data, np_inp[s.index])
@parameterized.named_parameters(
('inp_replicated', P(), P('x', 'y')),
('target_replicated', P('x'), P()),
('both_replicated', P(), P()),
)
def test_reshard_replicated_sharding(self, inp_spec, target_spec):
mesh1 = jtu.create_mesh((8,), 'x')
mesh2 = jax.sharding.Mesh(
np.asarray(jax.devices()[::-1]).reshape(4, 2), ('x', 'y')
)
shape = (8, 2)
np_inp = np.arange(math.prod(shape)).reshape(shape)
inp = jax.make_array_from_callback(
shape,
jax.sharding.NamedSharding(mesh1, inp_spec),
lambda idx: np_inp[idx],
)
out = jax.device_put(inp, jax.sharding.NamedSharding(mesh2, target_spec))
self.assertIsInstance(out.sharding, jax.sharding.NamedSharding)
for s in out.addressable_shards:
np.testing.assert_array_equal(s.data, np_inp[s.index])
def test_reshard_same_device_assignment(self):
mesh1 = jtu.create_mesh((4, 2), ('x', 'y'))
mesh2 = jtu.create_mesh((2, 4), ('x', 'y'))
shape = (8, 2)
np_inp = np.arange(math.prod(shape)).reshape(shape)
inp = jax.make_array_from_callback(
shape,
jax.sharding.NamedSharding(mesh1, P('x', 'y')),
lambda idx: np_inp[idx],
)
out = jax.device_put(inp, jax.sharding.NamedSharding(mesh2, P('y')))
self.assertIsInstance(out.sharding, jax.sharding.NamedSharding)
for s in out.addressable_shards:
np.testing.assert_array_equal(s.data, np_inp[s.index])
def test_reshard_pytree(self):
mesh1 = jtu.create_mesh((8,), 'x')
dev = jax.devices()
if len(dev) < 8:
raise unittest.SkipTest('Test requires 8 devices')
dev_list = [dev[0], dev[7], dev[6], dev[2], dev[4], dev[3], dev[5], dev[1]]
mesh2 = jax.sharding.Mesh(
np.asarray(dev_list).reshape(2, 2, 2), ('x', 'y', 'z')
)
shape = (8, 2)
np_inp = np.arange(math.prod(shape)).reshape(shape)
inp = jax.make_array_from_callback(
shape,
jax.sharding.NamedSharding(mesh1, P('x')),
lambda idx: np_inp[idx],
)
out1, out2 = jax.device_put(
(inp, inp), jax.sharding.NamedSharding(mesh2, P('x', 'y'))
)
for out in (out1, out2):
self.assertIsInstance(out.sharding, jax.sharding.NamedSharding)
for s in out.addressable_shards:
np.testing.assert_array_equal(s.data, np_inp[s.index])
def test_reshard_different_devices(self):
if jtu.is_device_tpu('5', 'e'):
raise unittest.SkipTest('Test fails on v5e')
dev = jax.devices()
if len(dev) < 8:
raise unittest.SkipTest('Test requires 8 devices')
mesh1 = jax.sharding.Mesh([dev[0], dev[2], dev[4], dev[6]], 'x')
mesh2 = jax.sharding.Mesh(jax.devices(), 'x')
shape = (8, 2)
np_inp = np.arange(math.prod(shape)).reshape(shape)
inp = jax.make_array_from_callback(
shape,
jax.sharding.NamedSharding(mesh1, P('x')),
lambda idx: np_inp[idx],
)
with self.assertRaisesRegex(
ValueError,
'input and target sharding should have the same set of devices',
):
jax.device_put(inp, jax.sharding.NamedSharding(mesh2, P('x')))
def test_process_allgather_array_not_fully_addressable(self):
global_mesh = jtu.create_mesh((4, 2), ('x', 'y'))
global_input_shape = (8, 2)
global_input_data = np.arange(math.prod(global_input_shape)).reshape(
global_input_shape
)
arr = jax.make_array_from_callback(
global_input_shape,
jax.sharding.NamedSharding(global_mesh, P('x', 'y')),
lambda idx: global_input_data[idx],
)
out = multihost_utils.process_allgather(arr, tiled=True)
np.testing.assert_array_equal(out, global_input_data)
with self.assertRaisesRegex(
ValueError,
'Gathering global non-fully-addressable arrays only supports'
' tiled=True'):
multihost_utils.process_allgather(arr, tiled=False)
@jtu.ignore_warning(
category=DeprecationWarning,
message='jax.sharding.PmapSharding is deprecated',
)
def test_host_local_array_to_global_array_already_global(self):
global_mesh = jtu.create_mesh((4, 2), ('x', 'y'))
global_input_shape = (8, 2)
global_input_data = np.arange(math.prod(global_input_shape)).reshape(
global_input_shape
)
arr = jax.make_array_from_callback(
global_input_shape,
jax.sharding.NamedSharding(global_mesh, P('x', 'y')),
lambda idx: global_input_data[idx],
)
out = multihost_utils.host_local_array_to_global_array(
arr, global_mesh, P('x', 'y')
)
self.assertEqual(id(arr), id(out))
@jtu.ignore_warning(
category=DeprecationWarning,
message='jax.sharding.PmapSharding is deprecated',
)
def test_host_local_array_to_global_array_same_sharding_array(self):
if jtu.is_device_tpu('5', 'e'):
raise unittest.SkipTest('Test fails on v5e')
global_mesh = jtu.create_mesh((4, 2), ('x', 'y'), iota_order=True)
local_input_shape = (2, 2)
elems_per_host = 4
local_input_data = (
jnp.arange(elems_per_host) + jax.process_index() * elems_per_host
).reshape(local_input_shape)
arr = jax.make_array_from_callback(
local_input_shape,
jax.sharding.NamedSharding(global_mesh.local_mesh, P('x', 'y')),
lambda idx: local_input_data[idx],
)
out = multihost_utils.host_local_array_to_global_array(
arr, global_mesh, P('x', 'y')
)
expected_global_shape = (8, 2)
self.assertEqual(out.shape, expected_global_shape)
global_data = np.arange(math.prod(expected_global_shape)).reshape(
expected_global_shape
)
for a, o in zip(arr.addressable_shards, out.addressable_shards):
self.assertEqual(
a.data.unsafe_buffer_pointer(), o.data.unsafe_buffer_pointer()
)
np.testing.assert_array_equal(o.data, global_data[o.index])
@jtu.ignore_warning(
category=DeprecationWarning,
message='jax.sharding.PmapSharding is deprecated',
)
def test_host_local_to_global_reshard_committed_single_device_array(self):
if jtu.is_device_tpu('5', 'e'):
raise unittest.SkipTest('Test fails on v5e')
global_mesh = jtu.create_mesh((4, 2), ('x', 'y'), iota_order=True)
local_input_shape = (2, 2)
elems_per_host = 4
local_input_data = (
jnp.arange(elems_per_host) + jax.process_index() * elems_per_host
).reshape(local_input_shape)
arr = jax.make_array_from_callback(
local_input_shape,
jax.sharding.NamedSharding(global_mesh.local_mesh, P('x', 'y')),
lambda idx: local_input_data[idx],
)
out = multihost_utils.host_local_array_to_global_array(
arr, global_mesh, P('x', 'y')
)
expected_global_shape = (8, 2)
self.assertEqual(out.shape, expected_global_shape)
global_data = np.arange(math.prod(expected_global_shape)).reshape(
expected_global_shape
)
for a, o in zip(arr.addressable_shards, out.addressable_shards):
self.assertEqual(
a.data.unsafe_buffer_pointer(), o.data.unsafe_buffer_pointer()
)
np.testing.assert_array_equal(o.data, global_data[o.index])
@jtu.ignore_warning(category=DeprecationWarning)
def test_host_local_to_global_replicated(self):
num_local_devices = jax.local_device_count()
global_mesh = jax.sharding.Mesh(jax.devices(), axis_names=['x'])
local_input_shape = (2, 2)
local_input_data = jnp.arange(4).reshape(local_input_shape)
out = multihost_utils.host_local_array_to_global_array(
local_input_data, global_mesh, P()
)
expected_global_shape = (2, 2)
self.assertEqual(out.shape, expected_global_shape)
self.assertLen(out.addressable_shards, num_local_devices)
# Array is accessible on every host.
np.testing.assert_array_equal(out, local_input_data)
@jtu.ignore_warning(category=DeprecationWarning)
def test_host_local_to_global_locally_replicated(self):
# Make an array which is locally replicated but sharded across hosts.
num_processes = jax.process_count()
num_local_devices = jax.local_device_count()
global_mesh = jtu.create_mesh(
(num_processes, num_local_devices), ('host', 'dev'), iota_order=True)
local_input_shape = (2, 2)
host_id = jax.process_index()
local_input_data = jnp.arange(4).reshape(local_input_shape) * host_id
out = multihost_utils.host_local_array_to_global_array(
local_input_data, global_mesh, P('host', None))
global_data = np.concatenate([jnp.arange(4).reshape(local_input_shape) * i
for i in range(num_processes)])
expected_global_shape = global_data.shape
self.assertEqual(out.shape, expected_global_shape)
self.assertLen(out.addressable_shards, num_local_devices)
for o in out.addressable_shards:
# Each shard has the same shape matching local_input_shape and smae
# global index.
self.assertEqual(o.data.shape, local_input_shape)
self.assertEqual(o.index, out.addressable_shards[0].index)
np.testing.assert_array_equal(o.data, global_data[o.index])
@jtu.ignore_warning(
category=DeprecationWarning,
message='jax.sharding.PmapSharding is deprecated',
)
def test_global_array_to_host_local_array(self):
if jtu.is_device_tpu('5', 'e'):
raise unittest.SkipTest('Test fails on v5e')
global_mesh = jtu.create_mesh((4, 2), ('x', 'y'), iota_order=True)
global_shape = (8, 2)
global_data = np.arange(math.prod(global_shape)).reshape(global_shape)
arr = jax.make_array_from_callback(
global_shape,
jax.sharding.NamedSharding(global_mesh, P('x', 'y')),
lambda idx: global_data[idx],
)
out = multihost_utils.global_array_to_host_local_array(
arr, global_mesh, P('x')
)
self.assertEqual(out.shape, (2, 2))
self.assertEqual(
out.sharding, jax.sharding.NamedSharding(global_mesh.local_mesh, P('x'))
)
local_input_data = (np.arange(4) + jax.process_index() * 4).reshape(
out.shape
)
for s in out.addressable_shards:
np.testing.assert_array_equal(s.data, local_input_data)
def test_host_local_array_to_global_array_none_error(self):
global_mesh = jtu.create_mesh((4, 2), ('x', 'y'))
global_shape = (8, 2)
data = np.arange(math.prod(global_shape)).reshape(global_shape)
with self.assertRaisesRegex(
ValueError, '`None` is not a valid input to the pspecs argument'
):
multihost_utils.host_local_array_to_global_array(data, global_mesh, None)
with self.assertRaisesRegex(
ValueError, '`None` is not a valid input to the pspecs argument'
):
multihost_utils.global_array_to_host_local_array(data, global_mesh, None)
def test_live_devices(self):
with multihost_utils.live_devices(jax.devices()) as live:
self.assertEqual(set(live), set(jax.devices()))
if __name__ == '__main__':
jt_multiprocess.main()
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/multiprocess/multihost_utils_test.py",
"license": "Apache License 2.0",
"lines": 455,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/multiprocess/pgle_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Multihost tests for pgle."""
import functools
import math
import os
import tempfile
from absl.testing import parameterized
import jax
from jax._src import config
from jax._src import test_multiprocess as jt_multiprocess
from jax._src import test_util as jtu
import jax.numpy as jnp
from jax.sharding import NamedSharding
from jax.sharding import PartitionSpec
import numpy as np
class PgleTestMultiHost(jt_multiprocess.MultiProcessTest):
def get_fdo_profiles(self, dump_dir):
jit_f_fdo_profiles = [
x
for x in os.listdir(dump_dir)
if 'jit_f' in x and x.endswith('.fdo_profile')
]
return jit_f_fdo_profiles
@parameterized.parameters(True, False)
def testAutoPGLE(self, use_compilation_cache: bool):
mesh = jtu.create_mesh((jax.device_count(),), ('x',))
its = 500
with tempfile.TemporaryDirectory() as dump_dir:
@functools.partial(
jax.jit,
in_shardings=NamedSharding(mesh, PartitionSpec('x')),
out_shardings=NamedSharding(mesh, PartitionSpec('x')),
compiler_options={
'xla_gpu_enable_latency_hiding_scheduler': 'True',
# TODO(patrios): Remove this flag once b/376647494 is fixed.
'xla_gpu_graph_min_graph_size': '100000',
'xla_dump_to': dump_dir,
'xla_gpu_experimental_dump_fdo_profiles': 'True',
},
)
def f(x):
agg = x
for _ in range(its):
agg = agg @ x
return agg
shape = (16, 16)
x = jnp.arange(math.prod(shape)).reshape(shape).astype(np.float32)
num_runs = 2
with (
config.pgle_profiling_runs(num_runs),
config.enable_pgle(True),
config.enable_compilation_cache(use_compilation_cache),
config.raise_persistent_cache_errors(True),
config.raise_persistent_cache_errors(True),
config.persistent_cache_min_entry_size_bytes(0),
config.persistent_cache_min_compile_time_secs(0),
):
for _ in range(num_runs):
f(x)
# There should be 3 fdo profiles: before optimization, after
# SPMD-partitioning, and after optimization.
fdo_profiles_before_pgle = self.get_fdo_profiles(dump_dir)
self.assertLen(fdo_profiles_before_pgle, 3)
self.assertEqual(
os.path.getsize(
os.path.join(dump_dir, fdo_profiles_before_pgle[0])
),
0,
)
# Should recompile with the FDO profile.
f(x)
# Expect 3 additional non-empty fdo profiles.
fdo_profiles_after_pgle = self.get_fdo_profiles(dump_dir)
self.assertLen(fdo_profiles_after_pgle, 6)
for fdo_profile in fdo_profiles_after_pgle:
if fdo_profile not in fdo_profiles_before_pgle:
self.assertGreater(
os.path.getsize(os.path.join(dump_dir, fdo_profile)), 0
)
if __name__ == '__main__':
jt_multiprocess.main()
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/multiprocess/pgle_test.py",
"license": "Apache License 2.0",
"lines": 93,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/multiprocess/pjit_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Multihost tests for pjit."""
import collections
from concurrent import futures
import contextlib
import functools
import io
import math
import unittest
import jax
from jax import numpy as jnp
from jax._src import array
from jax._src import debugging
from jax._src import pjit
from jax._src import test_multiprocess as jt_multiprocess
from jax._src import test_util as jtu
from jax.sharding import PartitionSpec as P
import numpy as np
X_SIZE = 2
Y_SIZE = 2
CHIPS_SIZE = 2
ALL_AXES = ("x", "y", "chips")
def sorted_devices():
devices = sorted(
jax.devices(), key=lambda d: (d.host_id, getattr(d, "core_on_chip", 0))
)
if len(devices) != 8:
raise unittest.SkipTest("Test assumes that it runs on a TPU donut")
return devices
@contextlib.contextmanager
def use_default_mesh():
devices = sorted_devices()
mesh_devices = np.array(devices).reshape((X_SIZE, Y_SIZE, CHIPS_SIZE))
with jax.sharding.Mesh(mesh_devices, ("x", "y", "chips")):
yield
def create_2d_non_contiguous_mesh():
devices = sorted_devices()
device_mesh = np.array([
[devices[0], devices[2]],
[devices[3], devices[1]],
[devices[4], devices[6]],
[devices[7], devices[5]],
])
# On TPUv3, the mesh looks like this (the integers are process index):
# 0 1
# 1 0
# 2 3
# 3 2
return jax.sharding.Mesh(device_mesh, ("x", "y"))
def create_2d_non_contiguous_mesh2():
devices = sorted_devices()
device_mesh = np.array([
[devices[0], devices[2]],
[devices[1], devices[3]],
[devices[4], devices[6]],
[devices[5], devices[7]],
])
# On TPUv3, the mesh looks like this (the integers are process index):
# 0 1
# 0 1
# 2 3
# 2 3
return jax.sharding.Mesh(device_mesh, ("x", "y"))
# TODO(apaszke): Test with mesh that has host-tiled axes (especially nesting!)
class PJitTestMultiHost(jt_multiprocess.MultiProcessTest):
@jtu.ignore_warning(category=DeprecationWarning)
def testLocalInputsWithJaxArray(self):
# Note that this is too small to shard over the global mesh, but fine for
# the local mesh and so should be accepted.
mesh = jtu.create_mesh((4, 2), ("x", "y"))
elems_per_host = 4
x = jnp.arange(elems_per_host) + jax.process_index() * elems_per_host
iar = jax.sharding.PartitionSpec("x")
oar = jax.sharding.PartitionSpec("x")
with mesh:
f = pjit.pjit(lambda x, y: (x, y), in_shardings=iar, out_shardings=oar)
gx = jax.experimental.multihost_utils.host_local_array_to_global_array(
(x, x), mesh, iar
)
global_out = f(*gx)
out1, out2 = (
jax.experimental.multihost_utils.global_array_to_host_local_array(
global_out, mesh, oar
)
)
np.testing.assert_array_equal(out1, x)
np.testing.assert_array_equal(out2, x)
class ArrayPjitMultiHost(jt_multiprocess.MultiProcessTest):
def test_pjit_array_single_output(self):
global_mesh = jtu.create_mesh((4, 2), ("x", "y"))
global_input_shape = (8, 2)
mesh_axes = jax.sharding.PartitionSpec("x", "y")
global_input_data = np.arange(math.prod(global_input_shape)).reshape(
global_input_shape
)
s = jax.sharding.NamedSharding(global_mesh, mesh_axes)
arr = array.make_array_from_callback(
global_input_shape, s, lambda idx: global_input_data[idx]
)
@functools.partial(pjit.pjit, out_shardings=s)
def f(x):
return x @ x.T
expected_matrix_mul = global_input_data @ global_input_data.T
out = f(arr)
self.assertIsInstance(out, array.ArrayImpl)
self.assertEqual(out.shape, (8, 8))
self.assertEqual(out.addressable_shards[0].data.shape, (2, 4))
for s in out.addressable_shards:
np.testing.assert_array_equal(
np.asarray(s.data), expected_matrix_mul[s.index]
)
# Test does not work with non-contiguous device IDs.
@jtu.skip_on_devices("cpu")
def test_pjit_array_non_contiguous_mesh_2d(self):
global_mesh = create_2d_non_contiguous_mesh()
global_input_shape = (8, 2)
pspec = jax.sharding.PartitionSpec("x", "y")
input_data = np.arange(math.prod(global_input_shape)).reshape(
global_input_shape
)
in_sharding = jax.sharding.NamedSharding(global_mesh, pspec)
out_sharding = jax.sharding.NamedSharding(global_mesh, pspec)
a1 = array.make_array_from_callback(
global_input_shape, in_sharding, lambda idx: input_data[idx]
)
# device_id -> (index, replica_id)
expected_idx_rid = {
0: ((slice(0, 2), slice(0, 1)), 0),
1: ((slice(2, 4), slice(1, 2)), 0),
2: ((slice(0, 2), slice(1, 2)), 0),
3: ((slice(2, 4), slice(0, 1)), 0),
4: ((slice(4, 6), slice(0, 1)), 0),
5: ((slice(6, 8), slice(1, 2)), 0),
6: ((slice(4, 6), slice(1, 2)), 0),
7: ((slice(6, 8), slice(0, 1)), 0),
}
with global_mesh:
f = pjit.pjit(lambda x: x, out_shardings=out_sharding)
out = f(a1)
for s in out.addressable_shards:
device_id = s.device.id
expected_index = expected_idx_rid[device_id][0]
expected_replica_id = expected_idx_rid[device_id][1]
self.assertEqual(s.index, expected_index)
self.assertEqual(s.replica_id, expected_replica_id)
self.assertEqual(s.data.shape, (2, 1))
np.testing.assert_array_equal(s.data._value, input_data[expected_index])
with global_mesh:
f = pjit.pjit(lambda x: x)
out = f(a1)
for s in out.addressable_shards:
device_id = s.device.id
expected_index = expected_idx_rid[device_id][0]
expected_replica_id = expected_idx_rid[device_id][1]
self.assertEqual(s.index, expected_index)
self.assertEqual(s.replica_id, expected_replica_id)
self.assertEqual(s.data.shape, (2, 1))
np.testing.assert_array_equal(s.data._value, input_data[expected_index])
none_sharding = jax.sharding.NamedSharding(
global_mesh, jax.sharding.PartitionSpec(None)
)
with global_mesh:
f = pjit.pjit(
lambda x: x, in_shardings=none_sharding, out_shardings=out_sharding
)
# Fully replicated values allows a non-contiguous mesh.
out = f(input_data)
self.assertIsInstance(out, array.ArrayImpl)
a2 = array.make_array_from_callback(
global_input_shape, none_sharding, lambda idx: input_data[idx]
)
with global_mesh:
f = pjit.pjit(
lambda x, y: (x, y),
in_shardings=(none_sharding, none_sharding),
out_shardings=(out_sharding, out_sharding),
)
# Fully replicated values + Array allows a non-contiguous mesh.
out1, out2 = f(input_data, a2)
self.assertIsInstance(out1, array.ArrayImpl)
self.assertIsInstance(out2, array.ArrayImpl)
def test_sharded_add(self):
global_mesh = create_2d_non_contiguous_mesh()
input_shape = (8, 2)
input_data = np.arange(math.prod(input_shape)).reshape(input_shape)
a_s = jax.sharding.NamedSharding(global_mesh, P("x", "y"))
b_s = jax.sharding.NamedSharding(global_mesh, P("x"))
a = array.make_array_from_callback(
input_shape, a_s, lambda idx: input_data[idx]
)
b = array.make_array_from_callback(
input_shape, b_s, lambda idx: input_data[idx]
)
out = a + b
for s in out.addressable_shards:
np.testing.assert_array_equal(
s.data, (input_data + input_data)[s.index]
)
def test_sharded_jit_add(self):
global_mesh = create_2d_non_contiguous_mesh()
input_shape = (8, 2)
input_data = np.arange(math.prod(input_shape)).reshape(input_shape)
a_s = jax.sharding.NamedSharding(global_mesh, P("x", "y"))
b_s = jax.sharding.NamedSharding(global_mesh, P("x"))
a = array.make_array_from_callback(
input_shape, a_s, lambda idx: input_data[idx]
)
b = array.make_array_from_callback(
input_shape, b_s, lambda idx: input_data[idx]
)
out = jax.jit(lambda x, y: x + y)(a, b)
for s in out.addressable_shards:
np.testing.assert_array_equal(s.data, (input_data + input_data)[s.index])
def test_sharded_copy(self):
global_mesh = create_2d_non_contiguous_mesh()
input_shape = (8, 2)
input_data = np.arange(math.prod(input_shape)).reshape(input_shape)
s = jax.sharding.NamedSharding(global_mesh, P("x", "y"))
arr = array.make_array_from_callback(
input_shape, s, lambda idx: input_data[idx]
)
# Copy the array sharded over multiple devices across multiple processes.
copy_arr = jnp.copy(arr)
for c, a in zip(copy_arr.addressable_shards, arr.addressable_shards):
self.assertNotEqual(
c.data.unsafe_buffer_pointer(), a.data.unsafe_buffer_pointer()
)
self.assertEqual(c.index, a.index)
self.assertEqual(c.replica_id, a.replica_id)
self.assertEqual(c.device, a.device)
np.testing.assert_array_equal(c.data, a.data)
def test_sharded_mul(self):
global_mesh = create_2d_non_contiguous_mesh()
input_shape = (8, 2)
input_data = np.arange(math.prod(input_shape)).reshape(input_shape)
a_s = jax.sharding.NamedSharding(global_mesh, P("x", "y"))
a = array.make_array_from_callback(
input_shape, a_s, lambda idx: input_data[idx]
)
out = a @ a.T
for s in out.addressable_shards:
np.testing.assert_array_equal(
s.data, (input_data @ input_data.T)[s.index]
)
def test_pjit_array_eval_shape(self):
with jtu.create_mesh((8,), "x"):
@functools.partial(
pjit.pjit,
in_shardings=jax.sharding.PartitionSpec(None),
out_shardings=jax.sharding.PartitionSpec("x"),
)
def f():
return jnp.zeros([32, 10])
self.assertEqual(f().shape, (32, 10))
self.assertEqual(jax.eval_shape(f).shape, (32, 10))
def test_trace_with_global_avals(self):
devices = sorted_devices()
mesh_devices = np.array(devices[::2] + devices[1::2])
# The device order in the below mesh is:
# (0, 2, 4, 6, 1, 3, 5, 7)
# each having the following process index:
# (0, 1, 2, 3, 0, 1, 2, 3)
# self.assertListEqual([d.process_index for d in mesh_devices],
# [0, 1, 2, 3, 0, 1, 2, 3])
global_mesh = jax.sharding.Mesh(mesh_devices, ("x",))
x = jnp.arange(16)
def check_shape(x):
self.assertEqual(x.shape, (16,))
return x
with global_mesh:
f = pjit.pjit(
check_shape,
in_shardings=jax.sharding.PartitionSpec("x"),
out_shardings=None,
)
np.testing.assert_array_equal(f(x), jnp.arange(16))
@use_default_mesh()
def test_pjit_in_pjit(self):
# The global size of x is 16. The shape should remain constant i.e. (16,)
# within all `pjit`'s since with Array, pjit only accepts global shaped
# inputs and doesn't lift the shape.
x = jnp.arange(16)
def pjit_all(f):
return pjit.pjit(
f,
in_shardings=jax.sharding.PartitionSpec(ALL_AXES),
out_shardings=jax.sharding.PartitionSpec(ALL_AXES),
)
def check_shape(x):
assert x.shape == (16,)
return x
pjit_all(check_shape)(x)
pjit_all(pjit_all(check_shape))(x)
pjit_all(pjit_all(pjit_all(check_shape)))(x)
def test_compile_parallel(self):
x = jnp.arange(16)
global_mesh = jtu.create_mesh((4, 2), ("x", "y"))
def _lower_compile(inp):
with global_mesh:
f = pjit.pjit(
lambda x: x.sum(),
in_shardings=jax.sharding.PartitionSpec("x"),
out_shardings=None,
)
exe = f.lower(inp).compile()
return exe
with futures.ThreadPoolExecutor(max_workers=5) as executor:
result = executor.map(_lower_compile, [x] * 5)
expected_out = np.arange(16).sum()
for out in list(result):
np.testing.assert_array_equal(out(x), expected_out)
def test_fully_sharded_on_all_devices(self):
if jax.local_device_count() > 1:
self.skipTest("This test only works with 1 process per device.")
num_devices = jax.device_count()
x = jnp.arange(num_devices)
global_mesh = jtu.create_mesh((num_devices,), "x")
with global_mesh:
f = pjit.pjit(
lambda x: x,
in_shardings=jax.sharding.PartitionSpec("x"),
out_shardings=jax.sharding.PartitionSpec("x"),
)
out = f(x)
expected_out = np.arange(num_devices)
for s in out.addressable_shards:
np.testing.assert_array_equal(s.data, expected_out[s.index])
def test_on_device_size_in_bytes(self):
global_mesh = create_2d_non_contiguous_mesh()
input_shape = (8, 2)
input_data = np.arange(math.prod(input_shape)).reshape(input_shape)
a_s = jax.sharding.NamedSharding(global_mesh, P("x", "y"))
a = array.make_array_from_callback(
input_shape, a_s, lambda idx: input_data[idx]
)
shard_size = a.addressable_shards[0].data.on_device_size_in_bytes()
self.assertGreaterEqual(shard_size, 4 * 2)
self.assertEqual(
shard_size * len(a.global_shards), a.on_device_size_in_bytes()
)
def test_numpy_input_error_with_non_trivial_sharding(self):
global_mesh = jtu.create_mesh((8,), "x")
inp = np.arange(8)
with global_mesh:
f = pjit.pjit(
lambda x: x,
in_shardings=jax.sharding.PartitionSpec(None),
out_shardings=jax.sharding.PartitionSpec(None),
)
out = f(inp)
np.testing.assert_array_equal(out, inp)
# If no in_axis_resources are specified, then pjit assumes that the
# numpy input is fully replicated.
f = pjit.pjit(lambda x: x, out_shardings=jax.sharding.PartitionSpec(None))
out = f(inp)
np.testing.assert_array_equal(out, inp)
f = pjit.pjit(
lambda x: x,
in_shardings=jax.sharding.PartitionSpec("x"),
out_shardings=jax.sharding.PartitionSpec("x"),
)
with self.assertRaisesRegex(
ValueError,
"Passing non-trivial shardings for numpy inputs is not allowed",
):
f(inp)
def test_non_contiguous_mesh_fetch_to_host(self):
if jax.local_device_count() != 2:
raise unittest.SkipTest("Test assumes 2 devices per process")
global_mesh = create_2d_non_contiguous_mesh()
input_shape = (8, 2)
input_data = np.arange(math.prod(input_shape)).reshape(input_shape)
a_s = jax.sharding.NamedSharding(global_mesh, P(None, "y"))
a = array.make_array_from_callback(
input_shape, a_s, lambda idx: input_data[idx]
)
np.testing.assert_array_equal(a, input_data)
def test_non_contiguous_mesh_fetch_to_host2(self):
global_mesh = create_2d_non_contiguous_mesh2()
input_shape = (8, 2)
input_data = np.arange(math.prod(input_shape)).reshape(input_shape)
a_s = jax.sharding.NamedSharding(global_mesh, P(None, "y"))
a = array.make_array_from_callback(
input_shape, a_s, lambda idx: input_data[idx]
)
with self.assertRaisesRegex(
RuntimeError,
r"Fetching value for `jax.Array` that spans non-addressable \(non"
r" process local\) devices is not possible",
):
_ = a._value
def test_no_python_shard_arg_fallback(self):
global_mesh = jtu.create_mesh((4, 2), ("x", "y"))
input_shape = (8, 2)
input_data = np.arange(math.prod(input_shape)).reshape(input_shape)
a_s = jax.sharding.NamedSharding(global_mesh, P("x", "y"))
arr = array.make_array_from_callback(
input_shape, a_s, lambda idx: input_data[idx])
@jax.jit
def f(x):
return x * 2
with jtu.count_jax_array_shard_arg_calls() as count:
f(arr)
f(arr)
self.assertEqual(count(), 1)
@contextlib.contextmanager
def capture_stdout():
with unittest.mock.patch("sys.stdout", new_callable=io.StringIO) as fp:
def _read() -> str:
return fp.getvalue()
yield _read
class MultiHostDebuggingTest(jt_multiprocess.MultiProcessTest):
def _assert_lines_equal(self, text1, text2):
def _count(lines):
return collections.Counter(lines)
self.assertDictEqual(_count(text1.split("\n")), _count(text2.split("\n")))
@use_default_mesh()
def test_print_in_multihost_pjit_array(self):
x = jnp.arange(16, dtype=jnp.int32)
def f(x):
debugging.debug_print("{}", x, ordered=False)
return x
f = pjit.pjit(
f,
in_shardings=jax.sharding.PartitionSpec(ALL_AXES),
out_shardings=jax.sharding.PartitionSpec(ALL_AXES),
)
with capture_stdout() as output:
f(x)
jax.effects_barrier()
if jax.process_index() == 0:
self.assertEqual(output(), f"{np.arange(16, dtype=np.int32)}\n")
else:
self.assertEqual(output(), "")
def test_print_in_multihost_shard_map(self):
devices = jax.devices()
mesh = jax.sharding.Mesh(devices, ("i",))
num_devices = jax.local_device_count()
local_x = (
jnp.arange(num_devices, dtype=jnp.int32)
+ jax.process_index() * num_devices
)
global_shape = (jax.device_count(),)
sharding = jax.NamedSharding(mesh, jax.P("i"))
global_x = jax.make_array_from_process_local_data(sharding, local_x, global_shape)
@jax.jit
@jax.shard_map(mesh=mesh, in_specs=jax.P("i"), out_specs=jax.P("i"))
def f(x):
debugging.debug_print("{}", x[0], ordered=False)
return x
with capture_stdout() as output:
out = f(global_x)
out.block_until_ready()
jax.effects_barrier()
lines = [f"{i}" for i in local_x] + [""]
self._assert_lines_equal(output(), "\n".join(lines))
if __name__ == "__main__":
jt_multiprocess.main()
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/multiprocess/pjit_test.py",
"license": "Apache License 2.0",
"lines": 470,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/multiprocess/pmap_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Multihost tests for pmap."""
import unittest
from absl.testing import parameterized
import jax
from jax import lax
from jax._src import array
from jax._src import sharding_impls
from jax._src import test_multiprocess as jt_multiprocess
from jax._src import test_util as jtu
import jax.numpy as jnp
import numpy as np
def sorted_devices():
devices = sorted(
jax.devices(), key=lambda d: (d.process_index(), d.core_on_chip))
if len(devices) != 8:
raise unittest.SkipTest("Test assumes that it runs on a TPU donut")
return devices
class PmapTestMultiHost(jt_multiprocess.MultiProcessTest):
@jtu.ignore_warning(category=DeprecationWarning)
def testBasic(self):
elems_per_host = 4
devices = jax.local_devices()
x = [np.arange(i, i + elems_per_host) + jax.process_index() * elems_per_host
for i in range(len(devices))]
y = jax.device_put_sharded(x, devices)
f = jax.pmap(lambda x: lax.psum(x, "i"), axis_name="i")
out = f(y)
expected_out = np.array([
np.arange(i, i + elems_per_host) + p * elems_per_host # pylint: disable=g-complex-comprehension
for p in range(jax.process_count()) for i in range(len(devices))
])
self.assertIsInstance(out, array.ArrayImpl)
if jax.config.jax_pmap_shmap_merge:
self.assertIsInstance(out.sharding, jax.sharding.NamedSharding)
else:
self.assertIsInstance(out.sharding, sharding_impls.PmapSharding)
np.testing.assert_array_equal(
out, np.array([expected_out.sum(axis=0)] * len(devices)))
def testLocalPmap(self):
z = jax.pmap(
lambda x: lax.axis_index("i"),
axis_name="i",
devices=jax.local_devices(),
)(np.arange(jax.local_device_count()))
np.testing.assert_array_equal(z, np.arange(jax.local_device_count()))
@parameterized.named_parameters(
("sharded_dim_0", 0),
("sharded_dim_1", 1),
)
@jtu.ignore_warning(category=DeprecationWarning)
def test_default_pmap_sharding(self, sharded_dim):
if jax.config.jax_pmap_shmap_merge:
self.skipTest("Does not apply for pmap shard_map merge")
n = jax.local_device_count()
shape = (n, 1) if sharded_dim == 0 else (1, n)
ps = sharding_impls.PmapSharding.default(shape, sharded_dim)
inp = jnp.arange(np.prod(shape)).reshape(shape)
compiled = jax.pmap(lambda x: x, in_axes=sharded_dim).lower(inp).compile()
pmap_in_sharding, = compiled._executable.unsafe_call.in_handler.in_shardings
self.assertEqual(ps._device_assignment, pmap_in_sharding._device_assignment)
self.assertEqual(ps.sharding_spec, pmap_in_sharding.sharding_spec)
@jtu.ignore_warning(category=DeprecationWarning)
def test_global_axis_size_initial_style(self):
xs = jnp.ones(jax.local_device_count())
pmapped_f = jax.pmap(lambda x: jax.lax.all_gather(x, "i"), axis_name="i")
jaxpr = jax.make_jaxpr(pmapped_f)(xs)
jax.core.eval_jaxpr(jaxpr.jaxpr, jaxpr.consts, xs) # does not crash
@jtu.ignore_warning(category=DeprecationWarning)
def test_array_device_size_mismatch_with_mesh(self):
"""Test pmap when input array's device count differs from pmap mesh."""
local_devices = jax.local_devices()
n = len(local_devices)
local_mesh = jax.sharding.Mesh(np.array(local_devices), ("x",))
local_sharding = jax.sharding.NamedSharding(
local_mesh, jax.sharding.PartitionSpec("x")
)
local_data = jnp.arange(n, dtype=jnp.float32)
local_arr = jax.device_put(local_data, local_sharding)
f = jax.pmap(lambda x: x + 1, devices=local_devices)
out = f(local_arr)
expected = np.arange(n, dtype=np.float32) + 1
np.testing.assert_array_equal(out, expected)
@jtu.ignore_warning(category=DeprecationWarning)
def test_pmap_with_scalars(self):
"""Test pmap with scalar inputs."""
n = jax.local_device_count()
scalars = [1.0] * n
f = jax.pmap(lambda x: x + 1)
out = f(np.array(scalars))
np.testing.assert_array_equal(out, np.array([2.0] * n))
@jtu.ignore_warning(category=DeprecationWarning)
def test_pmap_with_numpy_arrays(self):
"""Test pmap with numpy array inputs."""
n = jax.local_device_count()
np_input = np.arange(n * 4, dtype=np.float32).reshape((n, 4))
f = jax.pmap(lambda x: x * 2)
out = f(np_input)
np.testing.assert_array_equal(out, np_input * 2)
@jtu.ignore_warning(category=DeprecationWarning)
def test_pmap_with_prng_keys(self):
"""Test pmap with PRNGKey inputs."""
n = jax.local_device_count()
keys = jax.random.split(jax.random.key(0), n)
f = jax.pmap(lambda k: jax.random.normal(k, shape=(2,)))
out = f(keys)
self.assertEqual(out.shape, (n, 2))
for i in range(n):
for j in range(i + 1, n):
self.assertFalse(np.allclose(out.addressable_data(i), out.addressable_data(j)))
@jtu.ignore_warning(category=DeprecationWarning)
def test_pmap_with_float0(self):
"""Test pmap with float0 dtype arrays (used in autodiff for integer args)."""
n = jax.local_device_count()
float0_arr = np.zeros((n, 3), dtype=jax.dtypes.float0)
f = jax.pmap(lambda x: x)
out = f(float0_arr)
self.assertEqual(out.shape, (n, 3))
self.assertEqual(out.dtype, np.dtype(bool))
@jtu.ignore_warning(category=UserWarning,
message=".*Using jit-of-pmap can lead to inefficient data movement")
def test_replicated_output_sharding_multi_process(self):
if not jax.config.jax_pmap_shmap_merge:
self.skipTest("Only applies to pmap shmap merge")
f = jax.pmap(lambda x: x, axis_name="i", out_axes=None)
x = jnp.arange(jax.local_device_count())
out = f(x)
self.assertIsInstance(out.sharding, jax.sharding.NamedSharding)
self.assertEqual(out.sharding.spec, jax.sharding.PartitionSpec())
self.assertEqual(out.sharding.mesh.size, jax.local_device_count())
if __name__ == "__main__":
jt_multiprocess.main()
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/multiprocess/pmap_test.py",
"license": "Apache License 2.0",
"lines": 144,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/multiprocess/tpu_device_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test TpuDevice API on multiprocess setup."""
import unittest
import jax
from jax._src import test_multiprocess as jt_multiprocess
class TpuDeviceTest(jt_multiprocess.MultiProcessTest):
def test_coords(self):
for device in jax.local_devices():
coords = device.coords
self.assertIsInstance(coords, list)
self.assertLen(coords, 3)
for coord in coords:
self.assertIsInstance(coord, int)
def test_core(self):
for device in jax.local_devices():
core = device.core_on_chip
self.assertIsInstance(core, int)
self.assertGreaterEqual(core, 0)
self.assertLess(core, 2)
def test_missing_attribute(self):
for device in jax.local_devices():
with self.assertRaises(AttributeError):
device.gpu_type # pylint: disable=pointless-statement
def test_memory(self):
for device in jax.devices():
device_is_local = device.process_index == jax.process_index()
self.assertLen(device.addressable_memories(), 3)
hbm = device.addressable_memories()[0]
self.assertEqual(
hbm.process_index == device.process_index, device_is_local)
self.assertEqual(hbm.platform, device.platform)
self.assertEqual(hbm.kind, 'device')
self.assertEqual(hbm, device.memory(hbm.kind))
self.assertListEqual(hbm.addressable_by_devices(), [device])
host = device.addressable_memories()[1]
self.assertEqual(
host.process_index == device.process_index, device_is_local)
self.assertEqual(host.platform, device.platform)
self.assertEqual(host.kind, 'pinned_host')
self.assertEqual(host, device.memory(host.kind))
self.assertListEqual(host.addressable_by_devices(), [device])
with self.assertRaisesRegex(
jax.errors.JaxRuntimeError,
'INVALID_ARGUMENT: Could not find memory addressable by device TPU.*'
' Device TPU.* can address the following memory kinds: device,'
' pinned_host, unpinned_host. Got memory kind: gpu_hbm',
):
device.memory('gpu_hbm')
def test_host_memory_id(self):
if jax.local_device_count() < 2:
raise unittest.SkipTest('test requires 2 devices per process')
self.assertGreaterEqual(len(jax.local_devices()), 2)
host_0 = jax.local_devices()[0].memory('unpinned_host')
host_1 = jax.local_devices()[1].memory('unpinned_host')
self.assertNotEqual(id(host_0), id(host_1))
if __name__ == '__main__':
jt_multiprocess.main()
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/multiprocess/tpu_device_test.py",
"license": "Apache License 2.0",
"lines": 69,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/multiprocess/wait_barrier_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Wait barrier test."""
import jax
from jax._src import distributed
from jax._src import test_multiprocess as jt_multiprocess
class WaitBarrierTest(jt_multiprocess.MultiProcessTest):
def test_only_participants_call_succeeds(self):
client = distributed.global_state.client
timeout_in_ms = 1000
# Only even process ids will participate in the barrier.
barrier_participants = []
for process_index in range(jax.process_count()):
if process_index % 2 == 0:
barrier_participants.append(process_index)
if jax.process_index() % 2 == 0:
client.wait_at_barrier(
'only_even_participants_call',
timeout_in_ms,
process_ids=barrier_participants,
)
# This test is intended to implicitly verify that no exceptions are raised
# when the barrier is called if only the barrier participants including
# each one of them call the barrier. Thus there are no explicit assertions.
def test_non_participant_calls_fails(self):
client = distributed.global_state.client
timeout_in_ms = 1000
process_group = []
for process_index in range(jax.process_count()):
if process_index % 2 == 0:
process_group.append(process_index)
# Processes 0, 2, 4 ... wait here.
# Processes 1, 3, 5 ... go ahead to the barrier call.
if jax.process_index() % 2 == 0:
client.blocking_key_value_get('sync', timeout_in_ms=1000)
# 1, 3, 5 ... arrive and hit an error as they are non-participating.
# 0, 2, 4 ... has not yet arrived here. They will arrive once 1 unblocks
# them after leaving the barrier. But when they arrive at the barrier, they
# would see the error state even though they are participating.
with self.assertRaisesRegex(
jax.errors.JaxRuntimeError,
r'INVALID_ARGUMENT: A non-participating task.*'
):
client.wait_at_barrier(
'non_participant_calls', timeout_in_ms, process_ids=process_group
)
# 1 unblocks 0, 2 and 4.
if jax.process_index() == 1:
client.key_value_set('sync', 'process 1 exiting')
def test_all_participate_succeeds(self):
client = distributed.global_state.client
timeout_in_ms = 1000
client.wait_at_barrier('all_processes_call', timeout_in_ms)
# This test checks that processes do wait in `wait_at_barrier`and do not
# leave until all participating processes arrive.
def test_one_participant_never_calls_fails(self):
client = distributed.global_state.client
timeout_in_ms = 1000
if jax.process_index() != 0:
with self.assertRaisesRegex(
jax.errors.JaxRuntimeError, r'DEADLINE_EXCEEDED: Barrier timed out.*'
):
client.wait_at_barrier('one_participant_never_calls', timeout_in_ms)
if __name__ == '__main__':
jt_multiprocess.main()
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/multiprocess/wait_barrier_test.py",
"license": "Apache License 2.0",
"lines": 76,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/pallas/gpu_pallas_distributed_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for distributed pallas GPU operations."""
import functools
import os
import tempfile
from absl.testing import absltest
from absl.testing import parameterized
import jax
from jax import lax
from jax._src import test_multiprocess as jt_multiprocess
from jax._src import test_util as jtu
from jax._src.config import config
from jax.experimental import multihost_utils
from jax.experimental import pallas as pl
import jax.experimental.mosaic.gpu as mgpu
from jax.experimental.pallas import mosaic_gpu as plgpu
from jax.experimental.pallas.ops.gpu.all_gather_mgpu import all_gather
from jax.experimental.pallas.ops.gpu.reduce_scatter_mgpu import reduce_scatter
import jax.numpy as jnp
import numpy as np
P = jax.sharding.PartitionSpec
partial = functools.partial
def is_nvshmem_used():
return (
"XLA_FLAGS" in os.environ
and "--xla_gpu_experimental_enable_nvshmem" in os.environ["XLA_FLAGS"])
class TestCase(jt_multiprocess.MultiProcessTest if is_nvshmem_used() is None else parameterized.TestCase):
def setUp(self):
if jtu.test_device_matches(["rocm"]):
self.skipTest("Mosaic not supported on ROCm currently.")
if (not jtu.test_device_matches(["cuda"]) or
not jtu.is_cuda_compute_capability_at_least("9.0")):
self.skipTest("Only works on GPU with capability >= sm90")
if not mgpu.supports_cross_device_collectives():
self.skipTest(
"Skip test since cross-device collectives are not supported"
" (either NVSHMEM is not available in multi-process mode, or mixed"
" mode is used).")
if os.environ.get("XLA_PYTHON_CLIENT_ALLOCATOR", "") == "platform":
self.skipTest("NVSHMEM doesn't work with the platform allocator.")
super().setUp()
class PallasCallRemoteDMATest(TestCase):
def test_remote_dma_basic(self):
if jax.process_index() > 2:
return # Only 2 processes needed.
def kernel(x_ref, y_ref, ready_sem, recv_sem):
other_dev_id = 1 - lax.axis_index('x')
y_ref[...] = x_ref[...]
pl.semaphore_signal(ready_sem, device_id=other_dev_id)
pl.semaphore_wait(ready_sem)
neighbor_ptr = plgpu.remote_ref(y_ref, other_dev_id)
neighbor_ptr[...] = x_ref[...]
pl.semaphore_signal(recv_sem, device_id=other_dev_id)
pl.semaphore_wait(recv_sem)
x = jnp.arange(2 * 8 * 128.0, dtype=jnp.float32).reshape((2 * 8, 128))
def body(x):
return pl.pallas_call(
kernel,
in_specs=[pl.BlockSpec(memory_space=plgpu.GMEM)],
out_specs=pl.BlockSpec(memory_space=plgpu.GMEM),
out_shape=jax.ShapeDtypeStruct((8, 128), jnp.float32),
scratch_shapes=[
plgpu.SemaphoreType.REGULAR,
plgpu.SemaphoreType.REGULAR,
],
compiler_params=plgpu.CompilerParams(),
)(x)
devices = jax.devices()[:2]
mesh = jax.sharding.Mesh(devices, ["x"])
y = jax.jit(
jax.shard_map(
body,
mesh=mesh,
in_specs=P("x"),
out_specs=P("x"),
check_vma=False,
)
)(x)
expected = x[8:] if jax.process_index() == 0 else x[:8]
np.testing.assert_allclose(y.addressable_shards[0].data, expected)
# Test verifies an execution of HLO with several slightly different mosaic
# custom calls. The difference is needed to validate correct initialization
# of the collective metadata before each kernel execution.
def test_remote_dma_several_mosaic_ops(self):
if jax.process_index() > 2:
return # Only 2 processes needed.
def kernel(x_ref, y_ref, done_sem):
other_dev_id = 1 - lax.axis_index("x")
pl.semaphore_signal(done_sem, device_id=other_dev_id)
pl.semaphore_wait(done_sem)
neighbor_ptr = plgpu.remote_ref(y_ref, other_dev_id)
neighbor_ptr[...] = x_ref[...]
pl.semaphore_signal(done_sem, device_id=other_dev_id)
pl.semaphore_wait(done_sem)
def different_kernel(x_ref, y_ref, wait_sem, ready_sem):
other_dev_id = 1 - lax.axis_index("x")
pl.semaphore_signal(wait_sem, device_id=other_dev_id)
pl.semaphore_wait(wait_sem)
neighbor_ptr = plgpu.remote_ref(y_ref, other_dev_id)
neighbor_ptr[...] = x_ref[...]
pl.semaphore_signal(ready_sem, device_id=other_dev_id)
pl.semaphore_wait(ready_sem)
def body(x):
result = x
for _ in range(25):
result = pl.pallas_call(
kernel,
in_specs=[pl.BlockSpec(memory_space=plgpu.GMEM)],
out_specs=pl.BlockSpec(memory_space=plgpu.GMEM),
out_shape=jax.ShapeDtypeStruct((8, 128), jnp.float32),
scratch_shapes=[
plgpu.SemaphoreType.REGULAR,
],
)(result)
result = pl.pallas_call(
different_kernel,
in_specs=[pl.BlockSpec(memory_space=plgpu.GMEM)],
out_specs=pl.BlockSpec(memory_space=plgpu.GMEM),
out_shape=jax.ShapeDtypeStruct((8, 128), jnp.float32),
scratch_shapes=[
plgpu.SemaphoreType.REGULAR,
plgpu.SemaphoreType.REGULAR,
],
)(result)
return result
x = jnp.arange(2 * 8 * 128.0, dtype=jnp.float32).reshape((2 * 8, 128))
devices = jax.devices()[:2]
mesh = jax.sharding.Mesh(devices, ["x"])
y = jax.jit(
jax.shard_map(
body,
mesh=mesh,
in_specs=P("x"),
out_specs=P("x"),
check_vma=False,
)
)(x)
expected = x[:8] if jax.process_index() == 0 else x[8:]
np.testing.assert_allclose(y.addressable_shards[0].data, expected)
def test_remote_dma_with_retries(self):
if jax.process_index() > 2:
return # Only 2 processes needed.
def kernel(x_ref, y_ref, ready_sem, recv_sem):
other_dev_id = 1 - lax.axis_index('x')
y_ref[...] = x_ref[...]
pl.semaphore_signal(ready_sem, device_id=other_dev_id)
pl.semaphore_wait(ready_sem)
neighbor_ptr = plgpu.remote_ref(y_ref, other_dev_id)
neighbor_ptr[...] = x_ref[...]
pl.semaphore_signal(recv_sem, device_id=other_dev_id)
pl.semaphore_wait(recv_sem)
x = jnp.arange(2 * 8 * 128.0, dtype=jnp.float32).reshape((2 * 8, 128))
def body(x):
return pl.pallas_call(
kernel,
in_specs=[pl.BlockSpec(memory_space=plgpu.GMEM)],
out_specs=pl.BlockSpec(memory_space=plgpu.GMEM),
out_shape=jax.ShapeDtypeStruct((8, 128), jnp.float32),
scratch_shapes=[
plgpu.SemaphoreType.REGULAR,
plgpu.SemaphoreType.REGULAR,
],
compiler_params=plgpu.CompilerParams(),
)(x)
devices = jax.devices()[:2]
mesh = jax.sharding.Mesh(devices, ['x'])
jit_body = jax.jit(
jax.shard_map(
body, mesh=mesh, in_specs=P('x'), out_specs=P('x'),
check_vma=False,
)
)
y = x
for _ in range(51):
y = jit_body(y)
expected = x[8:] if jax.process_index() == 0 else x[:8]
np.testing.assert_allclose(y.addressable_shards[0].data, expected)
def test_remote_dma_with_profiler(self):
if jax.process_index() > 2:
return # Only 2 processes needed.
def kernel(x_ref, y_ref, ready_sem, recv_sem):
other_dev_id = 1 - lax.axis_index('x')
y_ref[...] = x_ref[...]
pl.semaphore_signal(ready_sem, device_id=other_dev_id)
pl.semaphore_wait(ready_sem)
neighbor_ptr = plgpu.remote_ref(y_ref, other_dev_id)
neighbor_ptr[...] = x_ref[...]
pl.semaphore_signal(recv_sem, device_id=other_dev_id)
pl.semaphore_wait(recv_sem)
# Ignore the warning about the profile already existing since in a
# single-process mode both device results will try to write to the same
# profile file.
with jtu.ignore_warning(category=UserWarning,
message=".*profile already exists.*"):
with tempfile.TemporaryDirectory() as tmpdir:
x = jnp.arange(2 * 8 * 128.0, dtype=jnp.float32).reshape((2 * 8, 128))
def body(x):
return pl.pallas_call(
kernel,
in_specs=[pl.BlockSpec(memory_space=plgpu.GMEM)],
out_specs=pl.BlockSpec(memory_space=plgpu.GMEM),
out_shape=jax.ShapeDtypeStruct((8, 128), jnp.float32),
scratch_shapes=[
plgpu.SemaphoreType.REGULAR,
plgpu.SemaphoreType.REGULAR,
],
compiler_params=plgpu.CompilerParams(
profile_space=1, profile_dir=tmpdir
),
)(x)
devices = jax.devices()[:2]
mesh = jax.sharding.Mesh(devices, ['x'])
y = jax.jit(
jax.shard_map(
body, mesh=mesh, in_specs=P('x'), out_specs=P('x'), check_vma=False,
)
)(x)
expected = x[8:] if jax.process_index() == 0 else x[:8]
np.testing.assert_allclose(y.addressable_shards[0].data, expected)
def test_remote_dma_in_loop(self):
if jax.process_index() > 2:
return # Only 2 processes needed.
def kernel(x_ref, y_ref, ready_sem, recv_sem):
device_id = lax.axis_index('x')
other_dev_id = 1 - device_id
neighbor_ptr = plgpu.remote_ref(y_ref, other_dev_id)
def body(i, _):
y_ref.at[0, i].set(x_ref.at[0, i].get())
pl.semaphore_signal(ready_sem, device_id=other_dev_id)
pl.semaphore_wait(ready_sem)
neighbor_ptr.at[0, i].set(x_ref.at[0, i].get())
pl.semaphore_signal(recv_sem, device_id=other_dev_id)
pl.semaphore_wait(recv_sem)
lax.fori_loop(0, 128, body, init_val=None, unroll=False)
x = jnp.arange(2 * 128.0, dtype=jnp.float32).reshape((2, 128))
def body(x):
return pl.pallas_call(
kernel,
in_specs=[pl.BlockSpec(memory_space=plgpu.GMEM)],
out_specs=pl.BlockSpec(memory_space=plgpu.GMEM),
out_shape=jax.ShapeDtypeStruct((1, 128), jnp.float32),
scratch_shapes=[
plgpu.SemaphoreType.REGULAR,
plgpu.SemaphoreType.REGULAR,
],
compiler_params=plgpu.CompilerParams(),
)(x)
devices = jax.devices()[:2]
mesh = jax.sharding.Mesh(devices, ['x'])
y = jax.jit(
jax.shard_map(
body, mesh=mesh, in_specs=P('x'), out_specs=P('x'), check_vma=False,
)
)(x)
expected = x[1:] if jax.process_index() == 0 else x[:1]
np.testing.assert_allclose(y.addressable_shards[0].data, expected)
def test_remote_dma_dynamic_index(self):
if jax.process_index() > 2:
return # Only 2 processes needed.
def kernel(x_ref, y_ref, ready_sem, recv_sem):
other_dev_id = jnp.sum(x_ref[...] == 1, dtype=jnp.int32)
y_ref[...] = x_ref[...]
pl.semaphore_signal(ready_sem, device_id=other_dev_id)
pl.semaphore_wait(ready_sem)
neighbor_ptr = plgpu.remote_ref(y_ref, other_dev_id)
neighbor_ptr[...] = x_ref[...]
pl.semaphore_signal(recv_sem, device_id=other_dev_id)
pl.semaphore_wait(recv_sem)
x = jnp.zeros((2, 128), dtype=jnp.int32)
x = x.at[0, 0].set(1)
def body(x):
return pl.pallas_call(
kernel,
in_specs=[pl.BlockSpec(memory_space=plgpu.GMEM)],
out_specs=pl.BlockSpec(memory_space=plgpu.GMEM),
out_shape=jax.ShapeDtypeStruct((1, 128), jnp.int32),
scratch_shapes=[
plgpu.SemaphoreType.REGULAR,
plgpu.SemaphoreType.REGULAR,
],
compiler_params=plgpu.CompilerParams(),
)(x)
devices = jax.devices()[:2]
mesh = jax.sharding.Mesh(devices, ['x'])
y = jax.jit(
jax.shard_map(
body, mesh=mesh, in_specs=P('x'), out_specs=P('x'), check_vma=False,
)
)(x)
expected = x[1:] if jax.process_index() == 0 else x[:1]
np.testing.assert_allclose(y.addressable_shards[0].data, expected)
@parameterized.parameters(('x',), ('y',))
def test_remote_dma_2d_mesh(self, axis):
if (jax.process_count() < 4 and
(jax.process_count() != 1 or jax.local_device_count() < 4)):
self.skipTest('Test requires at least 4 devices either accessible by a'
'single process or 4 processes with 1 device each.')
if jax.process_index() > 4:
return # Only 4 processes needed.
def kernel(x_ref, y_ref, recv_sem):
other_dev_id = {axis: 1 - lax.axis_index(axis)}
other_y_ref = plgpu.remote_ref(y_ref, other_dev_id)
other_y_ref[...] = x_ref[...]
pl.semaphore_signal(recv_sem, device_id=other_dev_id)
pl.semaphore_wait(recv_sem)
x = jnp.arange(2 * 8 * 128.0, dtype=jnp.float32).reshape((2 * 8, 128))
def body(x):
return pl.pallas_call(
kernel,
in_specs=[pl.BlockSpec(memory_space=plgpu.GMEM)],
out_specs=pl.BlockSpec(memory_space=plgpu.GMEM),
out_shape=jax.ShapeDtypeStruct((8, 128), jnp.float32),
scratch_shapes=[plgpu.SemaphoreType.REGULAR],
compiler_params=plgpu.CompilerParams(),
)(x)
devices = jax.devices()[:4]
mesh = jax.sharding.Mesh(np.asarray(devices).reshape(2, 2), ['x', 'y'])
y = jax.jit(
jax.shard_map(
body, mesh=mesh, in_specs=P(axis), out_specs=P(axis), check_vma=False,
)
)(x)
expected = x[8:] if jax.process_index() == 0 else x[:8]
np.testing.assert_allclose(y.addressable_shards[0].data, expected)
def test_wait_twice(self):
if jax.process_index() > 2:
return # Only 2 processes needed.
def kernel(y_ref, sem):
other_dev_id = 1 - lax.axis_index('x')
pl.semaphore_signal(sem, 2, device_id=other_dev_id)
pl.semaphore_wait(sem)
pl.semaphore_wait(sem)
y_ref[...] = jnp.ones_like(y_ref)
kernel_call = pl.pallas_call(
kernel,
out_specs=pl.BlockSpec(memory_space=plgpu.GMEM),
out_shape=jax.ShapeDtypeStruct((8, 128), jnp.float32),
scratch_shapes=[plgpu.SemaphoreType.REGULAR],
compiler_params=plgpu.CompilerParams(),
)
devices = jax.devices()[:2]
mesh = jax.sharding.Mesh(devices, ['x'])
y = jax.jit(
jax.shard_map(
kernel_call, mesh=mesh, in_specs=(), out_specs=P(None), check_vma=False,
)
)()
np.testing.assert_allclose(y, jnp.ones_like(y))
def test_wait_nodec(self):
if jax.process_index() > 2:
return # Only 2 processes needed.
def kernel(y_ref, sem):
other_dev_id = 1 - lax.axis_index('x')
pl.semaphore_signal(sem, 2, device_id=other_dev_id)
pl.semaphore_wait(sem, decrement=False)
pl.semaphore_wait(sem, 2, decrement=False)
pl.semaphore_wait(sem, 2)
y_ref[...] = jnp.ones_like(y_ref)
kernel_call = pl.pallas_call(
kernel,
out_specs=pl.BlockSpec(memory_space=plgpu.GMEM),
out_shape=jax.ShapeDtypeStruct((8, 128), jnp.float32),
scratch_shapes=[plgpu.SemaphoreType.REGULAR],
compiler_params=plgpu.CompilerParams(),
)
devices = jax.devices()[:2]
mesh = jax.sharding.Mesh(devices, ['x'])
y = jax.jit(
jax.shard_map(
kernel_call, mesh=mesh, in_specs=(), out_specs=P(None), check_vma=False,
)
)()
np.testing.assert_allclose(y, jnp.ones_like(y))
def test_signal_parallel(self):
if jax.process_index() > 2:
return # Only 2 processes needed.
def kernel(y_ref, sem, sem2):
other_dev_id = 1 - lax.axis_index('x')
plgpu.semaphore_signal_parallel(
plgpu.SemaphoreSignal(sem, device_id=other_dev_id),
plgpu.SemaphoreSignal(sem2, device_id=other_dev_id),
)
pl.semaphore_wait(sem)
pl.semaphore_wait(sem2)
y_ref[...] = jnp.ones_like(y_ref)
kernel_call = pl.pallas_call(
kernel,
out_specs=pl.BlockSpec(memory_space=plgpu.GMEM),
out_shape=jax.ShapeDtypeStruct((8, 128), jnp.float32),
scratch_shapes=[plgpu.SemaphoreType.REGULAR] * 2,
compiler_params=plgpu.CompilerParams(),
)
devices = jax.devices()[:2]
mesh = jax.sharding.Mesh(devices, ['x'])
y = jax.jit(
jax.shard_map(
kernel_call, mesh=mesh, in_specs=(), out_specs=P(None), check_vma=False,
)
)()
np.testing.assert_allclose(y, jnp.ones_like(y))
def test_semaphore_signal_collective_axes(self):
# TODO(b/476264413): Support multimem in multi-thread mode.
if jax.local_device_count() > 1:
return # Multimem not supported in multi-thread mode yet.
if jax.process_index() > 2:
return # Only 2 processes needed.
def kernel(y_ref, sem):
plgpu.semaphore_signal_multicast(sem, collective_axes='x')
# Wait for the multicast signal (each device gets signaled by all devices)
pl.semaphore_wait(sem, 2) # Wait for signals from both devices
y_ref[...] = jnp.ones_like(y_ref)
kernel_call = pl.pallas_call(
kernel,
out_specs=pl.BlockSpec(memory_space=plgpu.GMEM),
out_shape=jax.ShapeDtypeStruct((8, 128), jnp.float32),
scratch_shapes=[plgpu.SemaphoreType.REGULAR],
compiler_params=plgpu.CompilerParams(),
)
devices = jax.devices()[:2]
mesh = jax.sharding.Mesh(devices, ['x'])
y = jax.jit(
jax.shard_map(
kernel_call, mesh=mesh, in_specs=(), out_specs=P(None), check_vma=False,
)
)()
np.testing.assert_allclose(y, jnp.ones_like(y))
def test_permuted_mesh(self):
def kernel(y_ref, sem):
other_dev_id = 1 - lax.axis_index('x')
pl.semaphore_signal(sem, 1, device_id=other_dev_id)
pl.semaphore_wait(sem)
kernel_call = pl.pallas_call(
kernel,
out_specs=pl.BlockSpec(memory_space=plgpu.GMEM),
out_shape=jax.ShapeDtypeStruct((8, 128), jnp.float32),
scratch_shapes=[plgpu.SemaphoreType.REGULAR],
compiler_params=plgpu.CompilerParams(),
)
mesh = jax.sharding.Mesh(jax.devices()[::-1], ['x']) # Reverse the devices.
f = jax.jit(
jax.shard_map(
kernel_call, mesh=mesh, in_specs=(), out_specs=P(None), check_vma=False,
)
)
msg = (
'Mosaic GPU only supports meshes with device ordering that follows'
' row-major device ids.'
)
with self.assertRaisesRegex(NotImplementedError, msg):
f()
@parameterized.parameters(False, True)
def test_copy_tma(self, use_dict):
if jax.process_index() > 2:
return # Only 2 processes needed.
def kernel(y_ref, smem_ref, sem):
dev_id = lax.axis_index("y")
other_dev_id = 1 - dev_id
if use_dict:
ids = lambda x, y: dict(x=x, y=y)
else:
ids = lambda x, y: (x, y)
# Device ID must be an int32.
zero = jnp.int32(0)
@pl.when(dev_id == zero)
def _store():
output = plgpu.layout_cast(lax.broadcasted_iota(jnp.int32, (128, 128), 1), plgpu.Layout.WGMMA)
smem_ref[...] = output
plgpu.copy_smem_to_gmem(smem_ref, plgpu.remote_ref(y_ref, ids(zero, dev_id)))
plgpu.copy_smem_to_gmem(smem_ref, plgpu.remote_ref(y_ref, ids(zero, other_dev_id)))
plgpu.wait_smem_to_gmem(0)
pl.semaphore_signal(sem, 1, device_id=ids(zero, other_dev_id))
pl.semaphore_wait(sem)
transforms = (plgpu.TilingTransform((8, 32)), plgpu.SwizzleTransform(128))
kernel_call = pl.pallas_call(
kernel,
out_specs=pl.BlockSpec(memory_space=plgpu.GMEM),
out_shape=jax.ShapeDtypeStruct((128, 128), jnp.int32),
scratch_shapes=[
plgpu.SMEM((128, 128), jnp.int32, transforms=transforms),
plgpu.SemaphoreType.REGULAR,
],
compiler_params=plgpu.CompilerParams(),
)
mesh = jtu.create_mesh((1, 2), ("x", "y"))
y = jax.jit(
jax.shard_map(
kernel_call, mesh=mesh, in_specs=(), out_specs=P("y"), check_vma=False,
)
)()
if jax.local_device_count() == 1:
y = multihost_utils.process_allgather(y, tiled=True)
ref = lax.broadcasted_iota(jnp.int32, (128, 128), 1)
np.testing.assert_array_equal(y, np.concat([ref, ref], axis=0))
class PallasCallMultimemTest(TestCase):
def setUp(self):
if jax.local_device_count() > 1:
self.skipTest("Multimem not supported in multi-thread mode yet.")
super().setUp()
def _get_reduction_impl(self, reduction):
match reduction:
case "add":
return jnp.add
case "min":
return jnp.minimum
case "max":
return jnp.maximum
case "and":
return jnp.bitwise_and
case "or":
return jnp.bitwise_or
case "xor":
return jnp.bitwise_xor
case _:
raise ValueError(reduction)
def test_multimem_store_regs(self):
if jax.process_index() > 2:
return # Only 2 processes needed.
def kernel(y_ref, sem):
@pl.when(lax.axis_index('x') == 0)
def _store():
output = plgpu.layout_cast(lax.broadcasted_iota(jnp.int32, (128, 128), 1), plgpu.Layout.WGMMA)
plgpu.multimem_store(output, y_ref, 'x')
other_dev_id = 1 - lax.axis_index('x')
pl.semaphore_signal(sem, 1, device_id=other_dev_id)
pl.semaphore_wait(sem)
kernel_call = pl.pallas_call(
kernel,
out_specs=pl.BlockSpec(memory_space=plgpu.GMEM),
out_shape=jax.ShapeDtypeStruct((128, 128), jnp.int32),
scratch_shapes=[plgpu.SemaphoreType.REGULAR],
compiler_params=plgpu.CompilerParams(),
)
mesh = jax.sharding.Mesh(jax.devices(), ['x'])
y = jax.jit(
jax.shard_map(
kernel_call, mesh=mesh, in_specs=(), out_specs=P("x"), check_vma=False,
)
)()
y = multihost_utils.process_allgather(y, tiled=True)
ref = lax.broadcasted_iota(jnp.int32, (128, 128), 1)
np.testing.assert_array_equal(y, np.concat([ref, ref], axis=0))
def test_multimem_store_tma(self):
if jax.process_index() > 2:
return # Only 2 processes needed.
def kernel(y_ref, smem_ref, sem):
@pl.when(lax.axis_index('x') == 0)
def _store():
output = plgpu.layout_cast(lax.broadcasted_iota(jnp.int32, (128, 128), 1), plgpu.Layout.WGMMA)
smem_ref[...] = output
plgpu.copy_smem_to_gmem(smem_ref, plgpu.multicast_ref(y_ref, 'x'))
plgpu.wait_smem_to_gmem(0)
other_dev_id = 1 - lax.axis_index('x')
pl.semaphore_signal(sem, 1, device_id=other_dev_id)
pl.semaphore_wait(sem)
transforms = (plgpu.TilingTransform((8, 32)), plgpu.SwizzleTransform(128))
kernel_call = pl.pallas_call(
kernel,
out_specs=pl.BlockSpec(memory_space=plgpu.GMEM),
out_shape=jax.ShapeDtypeStruct((128, 128), jnp.int32),
scratch_shapes=[
plgpu.SMEM((128, 128), jnp.int32, transforms=transforms),
plgpu.SemaphoreType.REGULAR,
],
compiler_params=plgpu.CompilerParams(),
)
mesh = jax.sharding.Mesh(jax.devices(), ['x'])
y = jax.jit(
jax.shard_map(
kernel_call, mesh=mesh, in_specs=(), out_specs=P("x"), check_vma=False,
)
)()
y = multihost_utils.process_allgather(y, tiled=True)
ref = lax.broadcasted_iota(jnp.int32, (128, 128), 1)
np.testing.assert_array_equal(y, np.concat([ref, ref], axis=0))
@parameterized.parameters(
(jnp.int32, 1, "add"),
(jnp.int32, 1, "min"),
(jnp.int32, 1, "max"),
(jnp.int32, 1, "and"),
(jnp.int32, 1, "or"),
(jnp.int32, 1, "xor"),
(jnp.float32, 1, "add"),
(jnp.float32, 2, "add", True),
(jnp.float32, 4, "add"),
(jnp.float16, 2, "add"),
(jnp.float16, 2, "min"),
(jnp.float16, 4, "max"),
(jnp.float16, 8, "add", True),
(jnp.bfloat16, 2, "max"),
(jnp.bfloat16, 8, "add"),
(jnp.float8_e5m2, 4, "add"),
(jnp.float8_e5m2, 8, "min"),
(jnp.float8_e5m2, 16, "max", True),
(jnp.float8_e4m3fn, 4, "min", True),
(jnp.float8_e4m3fn, 8, "max"),
(jnp.float8_e4m3fn, 16, "add"),
)
def test_multimem_load_reduce(self, dtype, vector_length, reduction, tiled_layout=False):
if dtype in (
jnp.float8_e5m2,
jnp.float8_e4m3fn,
) and not jtu.is_cuda_compute_capability_at_least("10.0"):
self.skipTest("Only works on GPU with capability >= sm100")
if jax.process_index() > 2:
return # Only 2 processes needed.
devices = jax.devices()[:2]
def kernel(x_ref, y_ref, _, sem_ref):
if tiled_layout:
layout = plgpu.Layout.TILED(
plgpu.Tiling(
(
(64, 2 * vector_length),
(16, 2 * vector_length),
(vector_length,),
)
),
warp_dims=(-5,),
lane_dims=(-3, -2),
vector_dim=-1,
)
else:
layout = plgpu.Layout.WG_STRIDED((64, 32), vec_size=vector_length)
y_ref[...] = plgpu.layout_cast(
plgpu.multimem_load_reduce(
x_ref.at[16:-16], collective_axes="x", reduction_op=reduction,
),
layout
)
my_device = lax.axis_index("x")
other_device = 1 - my_device
pl.semaphore_signal(sem_ref, 1, device_id=other_device)
pl.semaphore_wait(sem_ref)
# The rounding we see in low precision types seems to be different from
# what JAX/XLA use.
match jnp.dtype(dtype).itemsize:
case 4:
bound = 800000
case 2:
bound = 128
case 1:
bound = 4
case _:
raise ValueError(f"Unsupported dtype: {dtype}")
x_local = jax.random.randint(
jax.random.key(1234), (128 + 64, 32), dtype=jnp.int32, minval=-bound, maxval=bound,
).astype(dtype)
mesh = jax.sharding.Mesh(devices, ("x",))
x_shard = jax.ShapeDtypeStruct((64 + 32, 32), dtype)
y_shape = jax.ShapeDtypeStruct((64, 32), dtype)
y, _ = jax.jit(
jax.shard_map(
pl.pallas_call(
kernel,
in_specs=[pl.BlockSpec(memory_space=plgpu.GMEM)],
out_specs=[
pl.BlockSpec(memory_space=plgpu.SMEM),
pl.BlockSpec(memory_space=plgpu.GMEM),
],
out_shape=(y_shape, x_shard),
scratch_shapes=[plgpu.SemaphoreType.REGULAR],
# TODO(b/448323639): Without aliasing XLA doesn't actually
# insert the copy that puts the operand in symmetric memory,
# which causes the kernel to crash.
input_output_aliases={0: 1},
compiler_params=plgpu.CompilerParams(),
),
mesh=mesh,
in_specs=P("x"),
out_specs=P("x"), # Not really, but lets us test.
check_vma=False,
)
)(x_local)
y = multihost_utils.process_allgather(y, tiled=True)
np_reduction = self._get_reduction_impl(reduction)
np.testing.assert_array_equal(
y.astype(jnp.float32),
np.tile(np_reduction(x_local[16:64+16], x_local[64+48:128+48]), (2, 1)),
)
def _test_reduce_scatter(
self,
shape,
dtype,
reduction,
scatter_dimension=0,
tile_size=None,
vec_size=None,
num_blocks=None,
):
if jax.process_index() > 2:
return
devices = jax.devices()[:2]
mesh = jax.sharding.Mesh(devices, ["x"])
if jnp.issubdtype(dtype, jnp.floating):
x = jax.random.uniform(jax.random.key(42), shape, dtype=dtype, minval=-1.0, maxval=1.0)
else:
x = jax.random.randint(jax.random.key(42), shape, dtype=dtype, minval=-1000, maxval=1000)
def body(x):
return reduce_scatter(
x,
axis_name="x",
scatter_dimension=scatter_dimension,
reduction=reduction,
vec_size=vec_size,
tile_size=tile_size,
num_blocks=num_blocks,
)
spec = P(*([None] * scatter_dimension), "x")
y = jax.jit(
jax.shard_map(
body, mesh=mesh, in_specs=spec, out_specs=spec, check_vma=False
)
)(x)
y = multihost_utils.process_allgather(y, tiled=True)
np_reduction = self._get_reduction_impl(reduction)
split_idx = x.shape[scatter_dimension] // 2
slices_first = [slice(None)] * len(shape)
slices_first[scatter_dimension] = slice(None, split_idx)
slices_second = [slice(None)] * len(shape)
slices_second[scatter_dimension] = slice(split_idx, None)
expected = np_reduction(x[tuple(slices_first)], x[tuple(slices_second)])
tol = 1e-5 if reduction == "add" else 0
np.testing.assert_allclose(y, expected, rtol=tol, atol=tol)
@parameterized.parameters(
(jnp.float32, "add", 1),
(jnp.float16, "add", 2),
(jnp.bfloat16, "add", 2),
(jnp.float16, "min", 4),
(jnp.float16, "max", 8),
(jnp.int32, "add", 1),
)
def test_reduce_scatter(self, dtype, reduction, vec_size):
# 16 rows * 64 cols = 1024 elements = 8 elements per thread
self._test_reduce_scatter(
(1024, 64), dtype, reduction, tile_size=1024, vec_size=vec_size, num_blocks=4
)
def test_reduce_scatter_large_minor_dims(self):
self._test_reduce_scatter(
(512, 32768), jnp.float16, "add", tile_size=8192, vec_size=4, num_blocks=4
)
@parameterized.parameters(2048, 256, None)
def test_reduce_scatter_auto_vec_size(self, tile_size):
self._test_reduce_scatter(
(1024, 64), jnp.float16, "add", tile_size=tile_size, vec_size=None, num_blocks=4
)
@parameterized.parameters(2048, 256, None)
def test_reduce_scatter_auto_vec_size_int(self, tile_size):
self._test_reduce_scatter(
(1024, 64), jnp.int32, "add", tile_size=tile_size, vec_size=None, num_blocks=4
)
@parameterized.parameters(1, 2)
def test_reduce_scatter_different_axes(self, axis):
if axis == 1:
shape = (64, 1024, 32)
tile_size = 2048
else: # axis == 2
shape = (32, 64, 1024)
tile_size = 2048
self._test_reduce_scatter(
shape, jnp.float16, "add", scatter_dimension=axis, tile_size=tile_size, vec_size=None, num_blocks=4
)
@parameterized.parameters(
(jnp.float16, "add"),
(jnp.float32, "add"),
(jnp.bfloat16, "max"),
)
def test_all_reduce(self, dtype, reduction):
"""Test all-reduce functionality when scatter_dimension=None."""
self._test_all_reduce(
(1024, 1024), dtype, reduction, tile_size=512, vec_size=None, num_blocks=4
)
def _test_all_reduce(
self,
shape,
dtype,
reduction,
tile_size=None,
vec_size=None,
num_blocks=None,
):
"""Helper function to test all-reduce functionality."""
devices = jax.devices()[:2]
mesh = jax.sharding.Mesh(devices, ['x'])
x = jax.random.normal(jax.random.key(42), (2, *shape), dtype)
def body(x):
return reduce_scatter(
x,
axis_name="x",
scatter_dimension=None, # All-reduce mode
reduction=reduction,
vec_size=vec_size,
tile_size=tile_size,
num_blocks=num_blocks,
)
spec = P("x")
y = jax.jit(
jax.shard_map(
body, mesh=mesh, in_specs=spec, out_specs=spec, check_vma=False
)
)(x)
y = multihost_utils.process_allgather(y, tiled=True)
np_reduction = self._get_reduction_impl(reduction)
expected = np_reduction(x[0], x[1])
tol = 1e-5 if reduction == "add" else 0
for ys in y:
# It seems that the rounding used by the switch is different from what
# XLA uses.
y_rounded = np.nextafter(ys, expected)
np.testing.assert_allclose(y_rounded, expected, rtol=tol, atol=tol)
def _test_all_gather(
self,
shape,
dtype,
gather_dimension=0,
tile_size=None,
vec_size=None,
num_blocks=None,
):
if jax.process_index() > 2:
return
if jnp.issubdtype(dtype, jnp.floating):
x = jax.random.uniform(jax.random.key(42), shape, dtype=dtype, minval=-1.0, maxval=1.0)
else:
x = jax.random.randint(jax.random.key(42), shape, dtype=dtype, minval=-1000, maxval=1000)
def body(x):
return all_gather(
x,
axis_name="x",
gather_dimension=gather_dimension,
vec_size=vec_size,
tile_size=tile_size,
num_blocks=num_blocks,
)
spec = P(*([None] * gather_dimension), "x")
devices = jax.devices()[:2]
mesh = jax.sharding.Mesh(devices, ["x"])
y = jax.jit(
jax.shard_map(
body, mesh=mesh, in_specs=spec, out_specs=spec, check_vma=False
)
)(x)
y = multihost_utils.process_allgather(y, tiled=True)
repeats = [1] * len(x.shape)
repeats[gather_dimension] = 2
np.testing.assert_array_equal(y, np.tile(x, repeats))
@parameterized.parameters(
(jnp.float32, 1),
(jnp.float16, 2),
(jnp.bfloat16, 2),
(jnp.float16, 4),
(jnp.float16, 8),
(jnp.int32, 1),
)
def test_all_gather(self, dtype, vec_size):
# 16 rows * 64 cols = 1024 elements = 8 elements per thread
self._test_all_gather(
(1024, 64), dtype, tile_size=1024, vec_size=vec_size, num_blocks=4
)
def test_all_gather_large_minor_dims(self):
self._test_all_gather(
(512, 32768), jnp.float16, tile_size=8192, vec_size=4, num_blocks=4
)
@parameterized.parameters(2048, 256, None)
def test_all_gather_auto_vec_size(self, tile_size):
self._test_all_gather(
(1024, 64), jnp.float16, tile_size=tile_size, vec_size=None, num_blocks=4
)
@parameterized.parameters(2048, 256, None)
def test_all_gather_auto_vec_size_int(self, tile_size):
self._test_all_gather(
(1024, 64), jnp.int32, tile_size=tile_size, vec_size=None, num_blocks=4
)
@parameterized.parameters(1, 2)
def test_all_gather_different_axes(self, axis):
if axis == 1:
shape = (64, 1024, 32)
tile_size = 2048
else: # axis == 2
shape = (32, 64, 1024)
tile_size = 2048
self._test_all_gather(
shape, jnp.float16, gather_dimension=axis, tile_size=tile_size, vec_size=None, num_blocks=4
)
if __name__ == '__main__':
# This test doesn't work with the platform allocator, so we override it
# if it's ran alone. If it's part of a larger test suite and the platform
# allocator is used, setUp will skip the test.
os.environ['XLA_PYTHON_CLIENT_MEM_FRACTION'] = '0.01'
os.environ['XLA_PYTHON_CLIENT_ALLOCATOR'] = 'default'
# TODO(b/483671897) re-enable once command buffers supported with collectives.
additional_xla_flags = "--xla_gpu_enable_command_buffer=''"
if "XLA_FLAGS" in os.environ:
os.environ["XLA_FLAGS"] = (
f"{os.environ['XLA_FLAGS']} {additional_xla_flags}"
)
else:
os.environ["XLA_FLAGS"] = additional_xla_flags
if is_nvshmem_used():
jt_multiprocess.main()
else:
config.config_with_absl()
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/pallas/gpu_pallas_distributed_test.py",
"license": "Apache License 2.0",
"lines": 913,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/pallas/mgpu_collective_matmul_test.py | # Copyright 2025 The JAX Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Test different parameterizations of our Mosaic GPU collective matmul."""
import functools
import os
from absl.testing import absltest
from absl.testing import parameterized # pylint: disable=g-multiple-import
import jax
from jax import lax
from jax import random
from jax._src import test_multiprocess as jt_multiprocess
from jax._src import test_util as jtu
from jax._src.config import config as jax_config
from jax.experimental.mosaic import gpu as mgpu
from jax.experimental.pallas.ops.gpu import collective_matmul_mgpu
import jax.numpy as jnp
import numpy as np
P = jax.sharding.PartitionSpec
def is_nvshmem_used() -> bool:
return (
"XLA_FLAGS" in os.environ
and "--xla_gpu_experimental_enable_nvshmem" in os.environ["XLA_FLAGS"]
)
@jtu.with_config(jax_traceback_filtering="off")
class CollectiveMatmulTestCase(jtu.JaxTestCase):
def setUp(self):
super().setUp()
if collective_matmul_mgpu is None:
self.skipTest("Mosaic GPU not available.")
if (not jtu.test_device_matches(["cuda"]) or
not jtu.is_cuda_compute_capability_equal("9.0")):
self.skipTest("Only works on GPU with capability sm90a")
if not mgpu.supports_cross_device_collectives():
if "FAIL_ON_NVSHMEM_UNAVAILABLE" in os.environ:
raise ValueError("NVSHMEM library unavailable.")
else:
self.skipTest(
"Skip test since cross-device collectives are not supported"
" (either NVSHMEM is not available in multi-process mode, or"
"several processes with several devices per process are used)."
)
if is_nvshmem_used() and jax.process_count() == 1:
self.skipTest("Test requires multiple processes.")
if os.environ.get("XLA_PYTHON_CLIENT_ALLOCATOR", "") == "platform":
self.skipTest("NVSHMEM doesn't work with the platform allocator.")
num_devices = jax.device_count()
mesh = jax.make_mesh(
(num_devices,), ("x",), axis_types=(jax.sharding.AxisType.Explicit,)
)
self.enter_context(jax.set_mesh(mesh))
@parameterized.product(
m_shard=(3072,),
n_shard=(256, 576),
k=(4096,),
tile_m=(64, 128, 192),
tile_n=(64, 128, 192),
tile_k=(64, 128),
grid_minor_dim=(collective_matmul_mgpu.MatmulDimension.N,),
grid_tile_width=(1,),
wg_dimension=(collective_matmul_mgpu.MatmulDimension.N,),
max_concurrent_steps=(2, 4),
dtype=(jnp.bfloat16,),
)
def test_all_gather_lhs_matmul(
self,
m_shard,
n_shard,
k,
tile_m,
tile_n,
tile_k,
max_concurrent_steps,
grid_minor_dim,
grid_tile_width,
wg_dimension,
dtype,
):
num_devices = jax.device_count()
epi_tile_size = 64 * 64
num_epi_tiles = tile_m * tile_n // epi_tile_size
cta_tile_m = tile_m * (1 + (wg_dimension == collective_matmul_mgpu.MatmulDimension.M))
cta_tile_n = tile_n * (1 + (wg_dimension == collective_matmul_mgpu.MatmulDimension.N))
if (
(cta_tile_m + cta_tile_n) * tile_k * max_concurrent_steps
+ 2 * min(2, num_epi_tiles) * epi_tile_size
) * 2 > 228000:
self.skipTest("Tile too big to fit into SMEM")
if n_shard % cta_tile_n:
self.skipTest("n_shard must be divisible by block_n for now.")
if m_shard % cta_tile_m:
self.skipTest("m_shard must be divisible by block_m for now.")
k1, k2 = random.split(random.key(1234), num=2)
lhs = random.normal(k1, (num_devices * m_shard, k), dtype)
rhs = random.normal(k2, (k, num_devices * n_shard), dtype)
lhs = jax.sharding.reshard(lhs, P("x", None))
rhs = jax.sharding.reshard(rhs, P(None, "x"))
def run(body):
out = jax.jit(
jax.shard_map(body, out_specs=P(None, "x"), check_vma=False)
)(lhs, rhs)
# Gather output, for NumPy comparison on the host.
out = jax.shard_map(
lambda x: lax.all_gather(x, "x", axis=1, tiled=True),
out_specs=P(None), check_vma=False,
)(out)
return out
ref_out = run(lambda x, y: lax.all_gather(x, "x", axis=0, tiled=True) @ y)
config = collective_matmul_mgpu.TuningConfig(
tile_m=tile_m,
tile_n=tile_n,
tile_k=tile_k,
max_concurrent_steps=max_concurrent_steps,
grid_minor_dim=grid_minor_dim,
grid_tile_width=grid_tile_width,
wg_dimension=wg_dimension,
)
out = run(
functools.partial(
collective_matmul_mgpu.all_gather_lhs_matmul,
axis_name="x",
config=config,
dtype=dtype,
)
)
np.testing.assert_allclose(out, ref_out)
if __name__ == "__main__":
# This test doesn't work with the platform allocator, so we override it
# if it's ran alone. If it's part of a larger test suite and the platform
# allocator is used, setUp will skip the test.
os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = "0.01"
os.environ["XLA_PYTHON_CLIENT_ALLOCATOR"] = "default"
os.environ["XLA_FLAGS"] = (
os.environ.get("XLA_FLAGS", "") + " --xla_gpu_autotune_level=0"
)
if is_nvshmem_used():
jt_multiprocess.main()
else:
jax_config.config_with_absl()
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/pallas/mgpu_collective_matmul_test.py",
"license": "Apache License 2.0",
"lines": 151,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/pallas/mgpu_examples_test.py | # Copyright 2025 The JAX Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for examples from Pallas:MGPU documentation."""
import dataclasses
import functools
import itertools
import statistics
from absl.testing import absltest
from absl.testing import parameterized
from jax import lax
from jax._src import config
from jax._src import test_util as jtu
import jax.experimental.mosaic.gpu # noqa: F401
from jax.experimental.mosaic.gpu import profiler
import jax.experimental.pallas as pl
import jax.experimental.pallas.mosaic_gpu as plgpu
from jax.extend import backend
import jax.numpy as jnp
import numpy as np
config.parse_flags_with_absl()
@dataclasses.dataclass(frozen=True)
class TuningConfig:
tile_m: int
tile_n: int
tile_k: int
max_concurrent_steps: int
epilogue_tile_n: int = 64
grid_minor_dim: int = 0
grid_tile_width: int = 1
def matmul0(a, b, config: TuningConfig):
dtype = a.dtype
m, k = a.shape
_, n = b.shape
tile_m, tile_n, tile_k = config.tile_m, config.tile_n, config.tile_k
swizzle = plgpu.find_swizzle(tile_k * jnp.dtype(dtype).itemsize * 8)
swizzle_elems = swizzle // jnp.dtype(dtype).itemsize
transforms = (
plgpu.TilingTransform((8, swizzle_elems)), plgpu.SwizzleTransform(swizzle)
)
if m % tile_m != 0:
raise ValueError(f"{m=} must be divisible by {tile_m=}")
if n % tile_n != 0:
raise ValueError(f"{n=} must be divisible by {tile_n=}")
if k % tile_k != 0:
raise ValueError(f"{k=} must be divisible by {tile_k=}")
m_iters = m // tile_m
n_iters = n // tile_n
k_iters = k // tile_k
max_concurrent_steps = config.max_concurrent_steps
def kernel(a_gmem, b_gmem, out_gmem, acc_tmem, acc_smem, consumed_barriers):
mi = lax.axis_index("m")
ni = lax.axis_index("n")
m_slice = pl.ds(mi * tile_m, tile_m)
n_slice = pl.ds(ni * tile_n, tile_n)
def do_mma(idxs, a_smem, b_smem):
(ki,) = idxs
arrive_barrier_slot = ki % 2
wait_barrier_slot = 1 - arrive_barrier_slot
plgpu.tcgen05_mma(
acc_tmem,
a_smem,
b_smem,
barrier=consumed_barriers.at[arrive_barrier_slot],
accumulate=(ki > 0),
)
plgpu.barrier_wait(consumed_barriers.at[wait_barrier_slot])
# Make sure the wait succeeds in the first iteration.
plgpu.barrier_arrive(consumed_barriers.at[1])
block_kwargs = dict(transforms=transforms, delay_release=1)
plgpu.emit_pipeline(
do_mma,
in_specs=[
plgpu.BlockSpec((tile_m, tile_k), lambda ki: (mi, ki), **block_kwargs),
plgpu.BlockSpec((tile_k, tile_n), lambda ki: (ki, ni), **block_kwargs),
],
grid=(k_iters,),
max_concurrent_steps=max_concurrent_steps,
)(a_gmem, b_gmem)
final_barrier = 1 - (k_iters % 2)
plgpu.barrier_wait(consumed_barriers.at[final_barrier])
acc_smem[...] = plgpu.async_load_tmem(acc_tmem).astype(dtype)
plgpu.commit_smem()
plgpu.copy_smem_to_gmem(acc_smem, out_gmem.at[m_slice, n_slice])
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
f = plgpu.kernel(
kernel,
out_shape=jax.ShapeDtypeStruct((m, n), dtype),
grid=(m_iters, n_iters),
grid_names=("m", "n"),
scratch_shapes=dict(
acc_tmem=plgpu.TMEM((tile_m, tile_n), jnp.float32),
acc_smem=plgpu.SMEM((tile_m, tile_n), dtype, transforms=transforms),
consumed_barriers=plgpu.Barrier(
num_arrivals=1, num_barriers=2, orders_tensor_core=True
),
),
)
return f(a, b)
def matmul1(a, b, config: TuningConfig):
dtype = a.dtype
m, k = a.shape
_, n = b.shape
tile_m, tile_n, tile_k = config.tile_m, config.tile_n, config.tile_k
swizzle = plgpu.find_swizzle(tile_k * jnp.dtype(dtype).itemsize * 8)
swizzle_elems = swizzle // jnp.dtype(dtype).itemsize
transforms = (
plgpu.TilingTransform((8, swizzle_elems)), plgpu.SwizzleTransform(swizzle)
)
if m % tile_m != 0:
raise ValueError(f"{m=} must be divisible by {tile_m=}")
if n % tile_n != 0:
raise ValueError(f"{n=} must be divisible by {tile_n=}")
if k % tile_k != 0:
raise ValueError(f"{k=} must be divisible by {tile_k=}")
m_iters = m // tile_m
n_iters = n // tile_n
k_iters = k // tile_k
max_concurrent_steps = config.max_concurrent_steps
def kernel(a_gmem, b_gmem, out_gmem,
a_smem, b_smem, acc_tmem, acc_smem,
load_barriers, consumed_barriers, mma_done_barrier):
m_index = lax.axis_index("m")
n_index = lax.axis_index("n")
m_slice = pl.ds(m_index * tile_m, tile_m)
n_slice = pl.ds(n_index * tile_n, tile_n)
@pl.core_map(plgpu.WarpMesh(axis_name="warp"))
def _per_warp():
warp_id = lax.axis_index("warp")
@pl.when(warp_id == 0)
def _memory():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
@pl.when(ki >= max_concurrent_steps)
def _(): # Make sure the data has been consumed before overwriting.
plgpu.barrier_wait(consumed_barriers.at[slot])
k_slice = pl.ds(ki * tile_k, tile_k)
plgpu.copy_gmem_to_smem(
a_gmem.at[m_slice, k_slice], a_smem.at[slot], load_barriers.at[slot]
)
plgpu.copy_gmem_to_smem(
b_gmem.at[k_slice, n_slice], b_smem.at[slot], load_barriers.at[slot]
)
lax.fori_loop(0, k_iters, _loop_body, None)
@pl.when(warp_id == 1)
def _compute():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
plgpu.barrier_wait(load_barriers.at[slot]) # Wait for data to arrive.
plgpu.tcgen05_mma(
acc_tmem,
a_smem.at[slot],
b_smem.at[slot],
consumed_barriers.at[slot],
accumulate=(ki > 0),
)
lax.fori_loop(0, k_iters, _loop_body, None)
plgpu.tcgen05_commit_arrive(mma_done_barrier)
plgpu.barrier_wait(mma_done_barrier)
acc_smem[...] = plgpu.async_load_tmem(acc_tmem).astype(dtype)
plgpu.commit_smem()
plgpu.copy_smem_to_gmem(acc_smem, out_gmem.at[m_slice, n_slice])
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
f = plgpu.kernel(
kernel,
out_shape=jax.ShapeDtypeStruct((m, n), dtype),
grid=(m_iters, n_iters),
grid_names=("m", "n"),
scratch_shapes=dict(
a_smem=plgpu.SMEM(
(max_concurrent_steps, tile_m, tile_k),
dtype,
transforms=transforms,
),
b_smem=plgpu.SMEM(
(max_concurrent_steps, tile_k, tile_n),
dtype,
transforms=transforms,
),
acc_tmem=plgpu.TMEM((tile_m, tile_n), jnp.float32),
acc_smem=plgpu.SMEM((tile_m, tile_n), dtype, transforms=transforms),
load_barriers=plgpu.Barrier(
num_arrivals=2, num_barriers=max_concurrent_steps
),
consumed_barriers=plgpu.Barrier(
num_arrivals=1,
num_barriers=max_concurrent_steps,
orders_tensor_core=True,
),
mma_done_barrier=plgpu.Barrier(
num_arrivals=1, num_barriers=1, orders_tensor_core=True
),
),
)
return f(a, b)
def matmul2(a, b, config: TuningConfig):
dtype = a.dtype
m, k = a.shape
_, n = b.shape
tile_m, tile_n, tile_k = config.tile_m, config.tile_n, config.tile_k
swizzle = plgpu.find_swizzle(tile_k * jnp.dtype(dtype).itemsize * 8)
swizzle_elems = swizzle // jnp.dtype(dtype).itemsize
transforms = (
plgpu.TilingTransform((8, swizzle_elems)), plgpu.SwizzleTransform(swizzle)
)
if m % tile_m != 0:
raise ValueError(f"{m=} must be divisible by {tile_m=}")
if n % tile_n != 0:
raise ValueError(f"{n=} must be divisible by {tile_n=}")
if k % tile_k != 0:
raise ValueError(f"{k=} must be divisible by {tile_k=}")
m_iters = m // tile_m
n_iters = n // tile_n
k_iters = k // tile_k
max_concurrent_steps = config.max_concurrent_steps
def kernel(a_gmem, b_gmem, out_gmem,
a_smem, b_smem, acc_tmem, acc_smem,
load_barriers, consumed_barriers, mma_done_barrier):
m_index = lax.axis_index("m")
n_index = lax.axis_index("n")
m_slice = pl.ds(m_index * tile_m, tile_m)
n_slice = pl.ds(n_index * tile_n, tile_n)
@pl.core_map(plgpu.WarpMesh(axis_name="warp"))
def _per_warp():
warp_id = lax.axis_index("warp")
@pl.when(warp_id == 0)
def _memory():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
@pl.when(ki >= max_concurrent_steps)
def _(): # Make sure the data has been consumed before overwriting.
plgpu.barrier_wait(consumed_barriers.at[slot])
k_slice = pl.ds(ki * tile_k, tile_k)
plgpu.copy_gmem_to_smem(
a_gmem.at[m_slice, k_slice], a_smem.at[slot], load_barriers.at[slot]
)
plgpu.copy_gmem_to_smem(
b_gmem.at[k_slice, n_slice], b_smem.at[slot], load_barriers.at[slot]
)
lax.fori_loop(0, k_iters, _loop_body, None)
@pl.when(warp_id == 1)
def _compute():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
plgpu.barrier_wait(load_barriers.at[slot]) # Wait for data to arrive.
plgpu.tcgen05_mma(
acc_tmem,
a_smem.at[slot],
b_smem.at[slot],
consumed_barriers.at[slot],
accumulate=(ki > 0),
)
lax.fori_loop(0, k_iters, _loop_body, None)
plgpu.tcgen05_commit_arrive(mma_done_barrier)
plgpu.barrier_wait(mma_done_barrier)
out_gmem_window = out_gmem.at[m_slice, n_slice]
for ni in range(tile_n // config.epilogue_tile_n):
acc_smem_ni = acc_smem.at[ni % 2]
ni_slice = pl.ds(ni * config.epilogue_tile_n, config.epilogue_tile_n)
# Make sure that previous copy is done before we overwrite.
plgpu.wait_smem_to_gmem(1, wait_read_only=True)
acc_smem_ni[...] = plgpu.async_load_tmem(acc_tmem.at[:, ni_slice]).astype(dtype)
plgpu.commit_smem()
plgpu.copy_smem_to_gmem(acc_smem_ni, out_gmem_window.at[:, ni_slice])
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
f = plgpu.kernel(
kernel,
out_shape=jax.ShapeDtypeStruct((m, n), dtype),
grid=(m_iters, n_iters),
grid_names=("m", "n"),
scratch_shapes=dict(
a_smem=plgpu.SMEM(
(max_concurrent_steps, tile_m, tile_k), dtype, transforms=transforms
),
b_smem=plgpu.SMEM(
(max_concurrent_steps, tile_k, tile_n), dtype, transforms=transforms
),
acc_tmem=plgpu.TMEM((tile_m, tile_n), jnp.float32),
acc_smem=plgpu.SMEM((2, tile_m, config.epilogue_tile_n), dtype, transforms=transforms),
load_barriers=plgpu.Barrier(num_arrivals=2, num_barriers=max_concurrent_steps),
consumed_barriers=plgpu.Barrier(
num_arrivals=1,
num_barriers=max_concurrent_steps,
orders_tensor_core=True,
),
mma_done_barrier=plgpu.Barrier(num_arrivals=1, num_barriers=1, orders_tensor_core=True),
)
)
return f(a, b)
def matmul3(a, b, config: TuningConfig):
dtype = a.dtype
m, k = a.shape
_, n = b.shape
tile_m, tile_n, tile_k = config.tile_m, config.tile_n, config.tile_k
swizzle = plgpu.find_swizzle(tile_k * jnp.dtype(dtype).itemsize * 8)
swizzle_elems = swizzle // jnp.dtype(dtype).itemsize
transforms = (
plgpu.TilingTransform((8, swizzle_elems)), plgpu.SwizzleTransform(swizzle)
)
if m % tile_m != 0:
raise ValueError(f"{m=} must be divisible by {tile_m=}")
if n % tile_n != 0:
raise ValueError(f"{n=} must be divisible by {tile_n=}")
if k % tile_k != 0:
raise ValueError(f"{k=} must be divisible by {tile_k=}")
cluster_tile_m = 2 * tile_m
cluster_tile_n = 2 * tile_n
m_iters = m // cluster_tile_m
n_iters = n // cluster_tile_n
k_iters = k // tile_k
max_concurrent_steps = config.max_concurrent_steps
def kernel(a_gmem, b_gmem, out_gmem,
a_smem, b_smem, acc_tmem, acc_smem,
load_barriers, consumed_barriers, mma_done_barrier):
is_lead_block = lax.axis_index("cluster") == 0
m_index = lax.axis_index("m")
n_index = lax.axis_index("n")
m_slice = pl.ds(m_index * cluster_tile_m, cluster_tile_m)
n_slice = pl.ds(n_index * cluster_tile_n, cluster_tile_n)
@pl.core_map(plgpu.WarpMesh(axis_name="warp"))
def _per_warp():
warp_id = lax.axis_index("warp")
@pl.when(warp_id == 0)
def _memory():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
@pl.when(ki >= max_concurrent_steps)
def _(): # Make sure the data has been consumed before overwriting.
plgpu.barrier_wait(consumed_barriers.at[slot])
k_slice = pl.ds(ki * tile_k, tile_k)
plgpu.copy_gmem_to_smem(
a_gmem.at[m_slice, k_slice], a_smem.at[slot], load_barriers.at[slot],
collective_axes="cluster", partitioned_axis=0
)
plgpu.copy_gmem_to_smem(
b_gmem.at[k_slice, n_slice], b_smem.at[slot], load_barriers.at[slot],
collective_axes="cluster", partitioned_axis=1
)
lax.fori_loop(0, k_iters, _loop_body, None)
@pl.when(jnp.logical_and(warp_id == 1, is_lead_block))
def _compute():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
plgpu.barrier_wait(load_barriers.at[slot]) # Wait for data to arrive.
plgpu.tcgen05_mma(
acc_tmem,
a_smem.at[slot],
b_smem.at[slot],
consumed_barriers.at[slot],
accumulate=(ki > 0),
collective_axis="cluster",
)
lax.fori_loop(0, k_iters, _loop_body, None)
plgpu.tcgen05_commit_arrive(mma_done_barrier, collective_axis="cluster")
plgpu.barrier_wait(mma_done_barrier)
out_m_index = m_index * 2 + lax.axis_index("cluster")
out_m_slice = pl.ds(out_m_index * tile_m, tile_m)
out_gmem_window = out_gmem.at[out_m_slice, n_slice]
for ni in range(cluster_tile_n // config.epilogue_tile_n):
acc_smem_ni = acc_smem.at[ni % 2]
ni_slice = pl.ds(ni * config.epilogue_tile_n, config.epilogue_tile_n)
# Make sure that previous copy is done before we overwrite.
plgpu.wait_smem_to_gmem(1, wait_read_only=True)
acc_smem_ni[...] = plgpu.async_load_tmem(acc_tmem.at[:, ni_slice]).astype(dtype)
plgpu.commit_smem()
plgpu.copy_smem_to_gmem(acc_smem_ni, out_gmem_window.at[:, ni_slice])
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
f = plgpu.kernel(
kernel,
out_shape=jax.ShapeDtypeStruct((m, n), dtype),
grid=(m_iters, n_iters),
grid_names=("m", "n"),
cluster=(2,),
cluster_names=("cluster",),
scratch_shapes=dict(
a_smem=plgpu.SMEM(
(max_concurrent_steps, tile_m, tile_k), dtype, transforms=transforms,
),
b_smem=plgpu.SMEM(
(max_concurrent_steps, tile_k, tile_n), dtype, transforms=transforms,
),
acc_tmem=plgpu.TMEM((tile_m, cluster_tile_n), jnp.float32, collective=True),
acc_smem=plgpu.SMEM((2, tile_m, config.epilogue_tile_n), dtype, transforms=transforms),
load_barriers=plgpu.Barrier(num_arrivals=2, num_barriers=max_concurrent_steps),
consumed_barriers=plgpu.Barrier(
num_arrivals=1,
num_barriers=max_concurrent_steps,
orders_tensor_core=True,
),
mma_done_barrier=plgpu.Barrier(num_arrivals=1, num_barriers=1, orders_tensor_core=True),
)
)
return f(a, b)
def matmul4(a, b, config: TuningConfig):
dtype = a.dtype
m, k = a.shape
_, n = b.shape
tile_m, tile_n, tile_k = config.tile_m, config.tile_n, config.tile_k
swizzle = plgpu.find_swizzle(tile_k * jnp.dtype(dtype).itemsize * 8)
swizzle_elems = swizzle // jnp.dtype(dtype).itemsize
transforms = (
plgpu.TilingTransform((8, swizzle_elems)), plgpu.SwizzleTransform(swizzle)
)
if m % tile_m != 0:
raise ValueError(f"{m=} must be divisible by {tile_m=}")
if n % tile_n != 0:
raise ValueError(f"{n=} must be divisible by {tile_n=}")
if k % tile_k != 0:
raise ValueError(f"{k=} must be divisible by {tile_k=}")
cluster_tile_m = 2 * tile_m
cluster_tile_n = 2 * tile_n
m_iters = m // cluster_tile_m
n_iters = n // cluster_tile_n
k_iters = k // tile_k
max_concurrent_steps = config.max_concurrent_steps
def kernel(a_gmem, b_gmem, out_gmem,
a_smem, b_smem, acc_tmem, acc_smem,
load_barriers, consumed_barriers, mma_done_barrier):
is_lead_block = lax.axis_index("cluster") == 0
@plgpu.nd_loop((m_iters, n_iters), collective_axes="cluster_grid")
def _mn_loop(loop_info: plgpu.NDLoopInfo):
m_index, n_index = loop_info.index
m_slice = pl.ds(m_index * cluster_tile_m, cluster_tile_m)
n_slice = pl.ds(n_index * cluster_tile_n, cluster_tile_n)
@pl.core_map(plgpu.WarpMesh(axis_name="warp"))
def _per_warp():
warp_id = lax.axis_index("warp")
@pl.when(warp_id == 0)
def _memory():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
@pl.when(jnp.logical_or(ki >= max_concurrent_steps, loop_info.local_index > 0))
def _(): # Make sure the data has been consumed before overwriting.
plgpu.barrier_wait(consumed_barriers.at[slot])
k_slice = pl.ds(ki * tile_k, tile_k)
plgpu.copy_gmem_to_smem(
a_gmem.at[m_slice, k_slice], a_smem.at[slot], load_barriers.at[slot],
collective_axes="cluster", partitioned_axis=0
)
plgpu.copy_gmem_to_smem(
b_gmem.at[k_slice, n_slice], b_smem.at[slot], load_barriers.at[slot],
collective_axes="cluster", partitioned_axis=1
)
lax.fori_loop(0, k_iters, _loop_body, None)
@pl.when(jnp.logical_and(warp_id == 1, is_lead_block))
def _compute():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
plgpu.barrier_wait(load_barriers.at[slot]) # Wait for data to arrive.
plgpu.tcgen05_mma(
acc_tmem,
a_smem.at[slot],
b_smem.at[slot],
consumed_barriers.at[slot],
accumulate=(ki > 0),
collective_axis="cluster",
)
lax.fori_loop(0, k_iters, _loop_body, None)
plgpu.tcgen05_commit_arrive(
mma_done_barrier,
collective_axis="cluster",
)
plgpu.wait_smem_to_gmem(0, wait_read_only=True) # Make sure that previous store is done.
plgpu.barrier_wait(mma_done_barrier)
out_m_index = m_index * 2 + lax.axis_index("cluster")
out_m_slice = pl.ds(out_m_index * tile_m, tile_m)
out_gmem_window = out_gmem.at[out_m_slice, n_slice]
for ni in range(cluster_tile_n // config.epilogue_tile_n):
acc_smem_ni = acc_smem.at[ni % 2]
ni_slice = pl.ds(ni * config.epilogue_tile_n, config.epilogue_tile_n)
# Make sure that previous copy is done before we overwrite.
plgpu.wait_smem_to_gmem(1, wait_read_only=True)
acc_smem_ni[...] = plgpu.async_load_tmem(acc_tmem.at[:, ni_slice]).astype(dtype)
plgpu.commit_smem()
plgpu.copy_smem_to_gmem(acc_smem_ni, out_gmem_window.at[:, ni_slice])
plgpu.wait_load_tmem() # Load must complete before MMA can overwrite TMEM.
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
num_sms = backend.get_default_device().core_count
f = plgpu.kernel(
kernel,
out_shape=jax.ShapeDtypeStruct((m, n), dtype),
grid=(num_sms // 2,),
grid_names=("cluster_grid",),
cluster=(2,),
cluster_names=("cluster",),
scratch_shapes=dict(
a_smem=plgpu.SMEM(
(max_concurrent_steps, tile_m, tile_k), dtype, transforms=transforms,
),
b_smem=plgpu.SMEM(
(max_concurrent_steps, tile_k, tile_n), dtype, transforms=transforms,
),
acc_tmem=plgpu.TMEM((tile_m, cluster_tile_n), jnp.float32, collective=True),
acc_smem=plgpu.SMEM((2, tile_m, config.epilogue_tile_n), dtype, transforms=transforms),
load_barriers=plgpu.Barrier(num_arrivals=2, num_barriers=max_concurrent_steps),
consumed_barriers=plgpu.Barrier(
num_arrivals=1,
num_barriers=max_concurrent_steps,
orders_tensor_core=True,
),
mma_done_barrier=plgpu.Barrier(num_arrivals=1, num_barriers=1, orders_tensor_core=True),
),
)
return f(a, b)
def matmul5(a, b, config: TuningConfig):
dtype = a.dtype
m, k = a.shape
_, n = b.shape
tile_m, tile_n, tile_k = config.tile_m, config.tile_n, config.tile_k
swizzle = plgpu.find_swizzle(tile_k * jnp.dtype(dtype).itemsize * 8)
swizzle_elems = swizzle // jnp.dtype(dtype).itemsize
transforms = (
plgpu.TilingTransform((8, swizzle_elems)), plgpu.SwizzleTransform(swizzle)
)
if m % tile_m != 0:
raise ValueError(f"{m=} must be divisible by {tile_m=}")
if n % tile_n != 0:
raise ValueError(f"{n=} must be divisible by {tile_n=}")
if k % tile_k != 0:
raise ValueError(f"{k=} must be divisible by {tile_k=}")
cluster_tile_m = 2 * tile_m
cluster_tile_n = 2 * tile_n
m_iters = m // cluster_tile_m
n_iters = n // cluster_tile_n
k_iters = k // tile_k
max_concurrent_steps = config.max_concurrent_steps
def kernel(a_gmem, b_gmem, out_gmem,
a_smem, b_smem, acc_tmem, acc_smem,
load_barriers, consumed_barriers, mma_done_barrier, store_done_barrier):
wg_idx = lax.axis_index("wg")
is_lead_block = lax.axis_index("cluster") == 0
@plgpu.nd_loop((m_iters, n_iters), collective_axes="cluster_grid")
def _mn_loop(loop_info: plgpu.NDLoopInfo):
m_index, n_index = loop_info.index
m_slice = pl.ds(m_index * cluster_tile_m, cluster_tile_m)
n_slice = pl.ds(n_index * cluster_tile_n, cluster_tile_n)
acc_slot = lax.rem(loop_info.local_index, jnp.int32(2))
mn_acc_tmem = acc_tmem.at[:, pl.ds(acc_slot * cluster_tile_n, cluster_tile_n)]
@pl.when(wg_idx == 0)
def _compute_wg():
@pl.core_map(plgpu.WarpMesh(axis_name="warp"))
def _per_warp():
warp_id = lax.axis_index("warp")
@pl.when(warp_id == 0)
def _memory():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
@pl.when(jnp.logical_or(ki >= max_concurrent_steps, loop_info.local_index > 0))
def _(): # Make sure the data has been consumed before overwriting.
plgpu.barrier_wait(consumed_barriers.at[slot])
k_slice = pl.ds(ki * tile_k, tile_k)
plgpu.copy_gmem_to_smem(
a_gmem.at[m_slice, k_slice], a_smem.at[slot], load_barriers.at[slot],
collective_axes="cluster", partitioned_axis=0
)
plgpu.copy_gmem_to_smem(
b_gmem.at[k_slice, n_slice], b_smem.at[slot], load_barriers.at[slot],
collective_axes="cluster", partitioned_axis=1
)
lax.fori_loop(0, k_iters, _loop_body, None)
# Wait for store to complete (except for the first two steps).
@pl.when(jnp.logical_and(warp_id == 1, loop_info.local_index >= 2))
def _wait_store():
plgpu.barrier_wait(store_done_barrier.at[acc_slot])
@pl.when(jnp.logical_and(warp_id == 1, is_lead_block))
def _compute():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
plgpu.barrier_wait(load_barriers.at[slot]) # Wait for data to arrive.
plgpu.tcgen05_mma(
mn_acc_tmem,
a_smem.at[slot],
b_smem.at[slot],
consumed_barriers.at[slot],
accumulate=(ki > 0),
collective_axis="cluster",
)
lax.fori_loop(0, k_iters, _loop_body, None)
plgpu.tcgen05_commit_arrive(
mma_done_barrier.at[acc_slot],
collective_axis="cluster",
)
@pl.when(wg_idx == 1)
def _store_wg():
# Ensure that copies from the previous mn step have completed.
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
plgpu.barrier_wait(mma_done_barrier.at[acc_slot])
out_m_index = m_index * 2 + lax.axis_index("cluster")
out_m_slice = pl.ds(out_m_index * tile_m, tile_m)
out_gmem_window = out_gmem.at[out_m_slice, n_slice]
for ni in range(cluster_tile_n // config.epilogue_tile_n):
acc_smem_ni = acc_smem.at[ni % 2]
ni_slice = pl.ds(ni * config.epilogue_tile_n, config.epilogue_tile_n)
# Make sure that previous copy is done before we overwrite.
plgpu.wait_smem_to_gmem(1, wait_read_only=True)
acc_smem_ni[...] = plgpu.async_load_tmem(mn_acc_tmem.at[:, ni_slice]).astype(dtype)
plgpu.commit_smem()
plgpu.copy_smem_to_gmem(acc_smem_ni, out_gmem_window.at[:, ni_slice])
plgpu.wait_load_tmem() # Load must complete before we signal.
plgpu.barrier_arrive(store_done_barrier.at[acc_slot])
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
num_sms = backend.get_default_device().core_count
f = plgpu.kernel(
kernel,
out_shape=jax.ShapeDtypeStruct((m, n), dtype),
grid=(num_sms // 2,),
grid_names=("cluster_grid",),
cluster=(2,),
cluster_names=("cluster",),
num_threads=2,
thread_name="wg",
scratch_shapes=dict(
a_smem=plgpu.SMEM(
(max_concurrent_steps, tile_m, tile_k), dtype, transforms=transforms,
),
b_smem=plgpu.SMEM(
(max_concurrent_steps, tile_k, tile_n), dtype, transforms=transforms,
),
acc_tmem=plgpu.TMEM((tile_m, 2 * cluster_tile_n), jnp.float32, collective=True),
acc_smem=plgpu.SMEM((2, tile_m, config.epilogue_tile_n), dtype, transforms=transforms),
load_barriers=plgpu.Barrier(num_arrivals=2, num_barriers=max_concurrent_steps),
consumed_barriers=plgpu.Barrier(
num_arrivals=1,
num_barriers=max_concurrent_steps,
orders_tensor_core=True,
),
mma_done_barrier=plgpu.Barrier(num_arrivals=1, num_barriers=2, orders_tensor_core=True),
store_done_barrier=plgpu.ClusterBarrier(
collective_axes=("cluster",),
num_arrivals=1,
num_barriers=2,
orders_tensor_core=True,
),
),
)
return f(a, b)
def matmul6(a, b, config: TuningConfig):
dtype = a.dtype
m, k = a.shape
_, n = b.shape
tile_m, tile_n, tile_k = config.tile_m, config.tile_n, config.tile_k
swizzle = plgpu.find_swizzle(tile_k * jnp.dtype(dtype).itemsize * 8)
swizzle_elems = swizzle // jnp.dtype(dtype).itemsize
transforms = (
plgpu.TilingTransform((8, swizzle_elems)), plgpu.SwizzleTransform(swizzle)
)
if m % tile_m != 0:
raise ValueError(f"{m=} must be divisible by {tile_m=}")
if n % tile_n != 0:
raise ValueError(f"{n=} must be divisible by {tile_n=}")
if k % tile_k != 0:
raise ValueError(f"{k=} must be divisible by {tile_k=}")
cluster_tile_m = 2 * tile_m
cluster_tile_n = 2 * tile_n
m_iters = m // cluster_tile_m
n_iters = n // cluster_tile_n
k_iters = k // tile_k
max_concurrent_steps = config.max_concurrent_steps
def kernel(a_gmem, b_gmem, out_gmem,
a_smem, b_smem, acc_tmem, acc_smem,
load_barriers, consumed_barriers, mma_done_barrier, store_done_barrier):
wg_idx = lax.axis_index("wg")
is_lead_block = lax.axis_index("cluster") == 0
@plgpu.nd_loop((m_iters * n_iters,), collective_axes="cluster_grid")
def _mn_loop(loop_info: plgpu.NDLoopInfo):
(lin_idx,) = loop_info.index
m_index, n_index = plgpu.planar_snake(
lin_idx,
(m_iters, n_iters),
config.grid_minor_dim,
config.grid_tile_width,
)
m_slice = pl.ds(m_index * cluster_tile_m, cluster_tile_m)
n_slice = pl.ds(n_index * cluster_tile_n, cluster_tile_n)
acc_slot = lax.rem(loop_info.local_index, jnp.int32(2))
mn_acc_tmem = acc_tmem.at[:, pl.ds(acc_slot * cluster_tile_n, cluster_tile_n)]
@pl.when(wg_idx == 0)
def _compute_wg():
@pl.core_map(plgpu.WarpMesh(axis_name="warp"))
def _per_warp():
warp_id = lax.axis_index("warp")
@pl.when(warp_id == 0)
def _memory():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
@pl.when(jnp.logical_or(ki >= max_concurrent_steps, loop_info.local_index > 0))
def _(): # Make sure the data has been consumed before overwriting.
plgpu.barrier_wait(consumed_barriers.at[slot])
k_slice = pl.ds(ki * tile_k, tile_k)
plgpu.copy_gmem_to_smem(
a_gmem.at[m_slice, k_slice], a_smem.at[slot], load_barriers.at[slot],
collective_axes="cluster", partitioned_axis=0
)
plgpu.copy_gmem_to_smem(
b_gmem.at[k_slice, n_slice], b_smem.at[slot], load_barriers.at[slot],
collective_axes="cluster", partitioned_axis=1
)
lax.fori_loop(0, k_iters, _loop_body, None)
# Wait for store to complete (except for the first two steps).
@pl.when(jnp.logical_and(warp_id == 1, loop_info.local_index >= 2))
def _wait_store():
plgpu.barrier_wait(store_done_barrier.at[acc_slot])
@pl.when(jnp.logical_and(warp_id == 1, is_lead_block))
def _compute():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
plgpu.barrier_wait(load_barriers.at[slot]) # Wait for data to arrive.
plgpu.tcgen05_mma(
mn_acc_tmem,
a_smem.at[slot],
b_smem.at[slot],
consumed_barriers.at[slot],
accumulate=(ki > 0),
collective_axis="cluster",
)
lax.fori_loop(0, k_iters, _loop_body, None)
plgpu.tcgen05_commit_arrive(
mma_done_barrier.at[acc_slot],
collective_axis="cluster",
)
@pl.when(wg_idx == 1)
def _store_wg():
# Ensure that copies from the previous mn step have completed.
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
plgpu.barrier_wait(mma_done_barrier.at[acc_slot])
out_m_index = m_index * 2 + lax.axis_index("cluster")
out_m_slice = pl.ds(out_m_index * tile_m, tile_m)
out_gmem_window = out_gmem.at[out_m_slice, n_slice]
for ni in range(cluster_tile_n // config.epilogue_tile_n):
acc_smem_ni = acc_smem.at[ni % 2]
ni_slice = pl.ds(ni * config.epilogue_tile_n, config.epilogue_tile_n)
# Make sure that previous copy is done before we overwrite.
plgpu.wait_smem_to_gmem(1, wait_read_only=True)
acc_smem_ni[...] = plgpu.async_load_tmem(mn_acc_tmem.at[:, ni_slice]).astype(dtype)
plgpu.commit_smem()
plgpu.copy_smem_to_gmem(acc_smem_ni, out_gmem_window.at[:, ni_slice])
plgpu.wait_load_tmem() # Load must complete before we signal.
plgpu.barrier_arrive(store_done_barrier.at[acc_slot])
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
num_sms = backend.get_default_device().core_count
f = plgpu.kernel(
kernel,
out_shape=jax.ShapeDtypeStruct((m, n), dtype),
grid=(num_sms // 2,),
grid_names=("cluster_grid",),
cluster=(2,),
cluster_names=("cluster",),
num_threads=2,
thread_name="wg",
scratch_shapes=dict(
a_smem=plgpu.SMEM(
(max_concurrent_steps, tile_m, tile_k), dtype, transforms=transforms
),
b_smem=plgpu.SMEM(
(max_concurrent_steps, tile_k, tile_n), dtype, transforms=transforms
),
acc_tmem=plgpu.TMEM((tile_m, 2 * cluster_tile_n), jnp.float32, collective=True),
acc_smem=plgpu.SMEM((2, tile_m, config.epilogue_tile_n), dtype, transforms=transforms),
load_barriers=plgpu.Barrier(num_arrivals=2, num_barriers=max_concurrent_steps),
consumed_barriers=plgpu.Barrier(
num_arrivals=1,
num_barriers=max_concurrent_steps,
orders_tensor_core=True,
),
mma_done_barrier=plgpu.Barrier(num_arrivals=1, num_barriers=2, orders_tensor_core=True),
store_done_barrier=plgpu.ClusterBarrier(
collective_axes=("cluster",),
num_arrivals=1,
num_barriers=2,
orders_tensor_core=True,
),
)
)
return f(a, b)
@jtu.with_config(jax_traceback_filtering="off")
class MatmulTutorialTCGen05Test(jtu.JaxTestCase, jtu.CudaArchSpecificTest):
BENCHMARK = False
def setUp(self):
super().setUp()
if not jtu.test_device_matches(["cuda"]):
self.skipTest("Test requires an NVIDIA GPU")
self.skip_unless_tcgen05()
def benchmark(self, matmul_impl, a, b, config_search_space):
if not self.BENCHMARK:
return
config_names = config_search_space.keys()
config_all_values = config_search_space.values()
peak_flops = 2250e12 # f16 TensorCore peak = 2250 TFLOPS
matmul_flops = 2 * a.shape[0] * b.shape[0] * b.shape[1]
optimal_time_us = matmul_flops / peak_flops * 1e6 # us
best_util = 0.0
ref = jnp.dot(a, b, precision=jax.lax.DotAlgorithmPreset.F16_F16_F32)
for config_values in itertools.product(*config_all_values):
config = TuningConfig(**dict(zip(config_names, config_values)))
try:
out, runtimes_ms = profiler.measure(
functools.partial(matmul_impl, config=config), iterations=100
)(a, b)
except ValueError as e:
if "exceeds available shared memory" in e.args[0]: # Ignore SMEM OOMs.
continue
raise
assert runtimes_ms is not None
runtime_ms = statistics.median(runtimes_ms)
runtime_us = runtime_ms * 1e3 # type: ignore
achieved_tc_util = optimal_time_us / runtime_us * 100
print(f"{config} {achieved_tc_util:.2f}% TC utilization")
if achieved_tc_util > best_util:
best_util = achieved_tc_util
np.testing.assert_allclose(out, ref)
print(f"Best result for {matmul_impl.__name__}: {best_util:.2f}% TC utilization")
_, runtimes_ms = profiler.measure(
functools.partial(
jnp.dot, precision=jax.lax.DotAlgorithmPreset.F16_F16_F32
),
iterations=100,
)(a, b)
runtime_ms = statistics.median(runtimes_ms)
runtime_us = runtime_ms * 1e3 # type: ignore
achieved_tc_util = optimal_time_us / runtime_us * 100
print(f"Reference: {achieved_tc_util:.2f}% TC utilization")
def _test_matmul(self, matmul_impl, example_config, config_search_space):
dtype = jnp.float16
m = 4096
n = 8192
k = 4096
k1, k2, = jax.random.split(jax.random.key(42), 2)
a = jax.random.normal(k1, (m, k), dtype)
b = jax.random.normal(k2, (k, n), dtype)
out = matmul_impl(a, b, example_config)
out_ref = jnp.dot(a, b, precision=jax.lax.DotAlgorithmPreset.F16_F16_F32)
np.testing.assert_allclose(out, out_ref)
self.benchmark(matmul_impl, a, b, config_search_space)
@parameterized.parameters(matmul0, matmul1, matmul2)
def test_matmul(self, matmul_impl):
example_config = TuningConfig(
tile_m=128, tile_n=128, tile_k=64, max_concurrent_steps=4,
)
config_search_space = {
"tile_m": (128,),
"tile_n": (128, 256, 512),
"tile_k": (64,),
"max_concurrent_steps": (4, 6),
}
self._test_matmul(matmul_impl, example_config, config_search_space)
def test_matmul3(self):
example_config = TuningConfig(
tile_m=128, tile_n=128, tile_k=64, max_concurrent_steps=4,
)
config_search_space = {
"tile_m": (128,),
"tile_n": (128,),
"tile_k": (64,),
"max_concurrent_steps": (6,),
}
self._test_matmul(matmul3, example_config, config_search_space)
def test_matmul4(self):
example_config = TuningConfig(
tile_m=128, tile_n=128, tile_k=64, max_concurrent_steps=4,
)
config_search_space = {
"tile_m": (128,),
"tile_n": (128,),
"tile_k": (64,),
"max_concurrent_steps": (6,),
}
self._test_matmul(matmul4, example_config, config_search_space)
def test_matmul5(self):
example_config = TuningConfig(
tile_m=128, tile_n=128, tile_k=64, max_concurrent_steps=4,
)
config_search_space = {
"tile_m": (128,),
"tile_n": (128,),
"tile_k": (64,),
"max_concurrent_steps": (6,),
}
self._test_matmul(matmul5, example_config, config_search_space)
def test_matmul6(self):
example_config = TuningConfig(
tile_m=128, tile_n=128, tile_k=64, max_concurrent_steps=4,
grid_minor_dim=0, grid_tile_width=6,
)
config_search_space = {
"tile_m": (128,),
"tile_n": (128,),
"tile_k": (64,),
"max_concurrent_steps": (6,),
"grid_minor_dim": (0, 1),
"grid_tile_width": (1, 4, 12, 16),
}
self._test_matmul(matmul6, example_config, config_search_space)
if __name__ == "__main__":
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/pallas/mgpu_examples_test.py",
"license": "Apache License 2.0",
"lines": 905,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/pallas/mgpu_matmul_test.py | # Copyright 2025 The JAX Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Test different parameterizations of matrix multiplication."""
import os
from absl.testing import absltest
from absl.testing import parameterized
import jax
from jax._src import config
from jax._src import dtypes
from jax._src import test_util as jtu
import jax.experimental.mosaic.gpu # noqa: F401
from jax.experimental.pallas.ops.gpu import blackwell_matmul_mgpu
from jax.experimental.pallas.ops.gpu import hopper_matmul_mgpu
from jax.experimental.pallas.ops.gpu import hopper_mixed_type_matmul_mgpu
import jax.numpy as jnp
import numpy as np
config.parse_flags_with_absl()
os.environ["XLA_FLAGS"] = (
os.environ.get("XLA_FLAGS", "") + " --xla_gpu_autotune_level=0")
def exceeds_h100_smem(alloc_bytes: int) -> bool:
"""Whether the given allocation will exceed the amount of SMEM on H100."""
return alloc_bytes > 228000
@jtu.with_config(jax_traceback_filtering="off")
class MatrixMultiplicationTCGen05Test(jtu.JaxTestCase, jtu.CudaArchSpecificTest):
def setUp(self):
super().setUp()
if not jtu.test_device_matches(["cuda"]):
self.skipTest("Test requires an NVIDIA GPU")
@parameterized.product(
m=(1024, 4096),
k=(1024, 4096),
n=(1024, 4096),
dtype=(jnp.float16,),
)
def test_blackwell_matmul(
self,
m,
n,
k,
dtype,
):
self.skip_unless_tcgen05()
k1, k2, = jax.random.split(jax.random.key(42), 2)
a = jax.random.normal(k1, (m, k), dtype)
b = jax.random.normal(k2, (k, n), dtype)
out = blackwell_matmul_mgpu.matmul_kernel(
a,
b,
blackwell_matmul_mgpu.TuningConfig(
tile_m=128, tile_n=128, tile_k=128,
max_concurrent_steps=2,
collective=False,
),
)
out_ref = a @ b
np.testing.assert_allclose(out, out_ref, atol=2e-3, rtol=1e-3)
@jtu.with_config(jax_traceback_filtering="off")
class MatrixMultiplicationSm90ATest(jtu.JaxTestCase):
def setUp(self):
super().setUp()
if not jtu.test_device_matches(["cuda"]):
self.skipTest("Test requires an NVIDIA GPU")
@parameterized.product(
m=(4096,),
k=(4096,),
n=(4096,),
tile_m=(64, 128),
tile_n=(64, 128),
tile_k=(64, 128),
max_concurrent_steps=(2, 4),
dtype=(jnp.float16,),
epi_tile_n=(None, 64),
epi_tile_m=(None, 64),
wg_dimension=tuple(hopper_matmul_mgpu.MatmulDimension),
c_dtype=(None, jnp.float32),
)
def test_hopper_matmul(self, *args, **kwargs):
self.check_hopper_matmul(*args, **kwargs)
# Grid tiling doesn't really interact with many other options so we can test
# it separately.
@parameterized.product(
grid_minor_dim=tuple(hopper_matmul_mgpu.MatmulDimension),
grid_tile_width=(1, 3, 4),
)
def test_hopper_matmul_grid_tiling(self, grid_minor_dim, grid_tile_width):
self.check_hopper_matmul(
m=4096,
k=4096,
n=4096,
dtype=jnp.float16,
tile_m=64,
tile_n=64,
tile_k=64,
max_concurrent_steps=2,
epi_tile_m=64,
epi_tile_n=64,
wg_dimension=hopper_matmul_mgpu.MatmulDimension.M,
grid_minor_dim=grid_minor_dim,
grid_tile_width=grid_tile_width,
)
@parameterized.product(
tile_m=(64, 128),
tile_n=(64, 128),
wg_dimension=tuple(hopper_matmul_mgpu.MatmulDimension),
cluster_dimension=tuple(hopper_matmul_mgpu.MatmulDimension),
)
def test_hopper_matmul_cluster(self, tile_m, tile_n, wg_dimension, cluster_dimension):
self.check_hopper_matmul(
m=4096,
k=4096,
n=4096,
dtype=jnp.float16,
tile_m=tile_m,
tile_n=tile_n,
tile_k=64,
max_concurrent_steps=4,
epi_tile_m=64,
epi_tile_n=64,
wg_dimension=wg_dimension,
cluster_dimension=cluster_dimension,
)
def check_hopper_matmul(
self,
m,
n,
k,
dtype,
tile_m,
tile_n,
tile_k,
max_concurrent_steps,
epi_tile_m,
epi_tile_n,
wg_dimension,
c_dtype=None,
**kwargs
):
if not jtu.is_cuda_compute_capability_equal("9.0"):
self.skipTest("Only works on GPU with capability sm90a")
epi_tile_size = (epi_tile_m or tile_m) * (epi_tile_n or tile_n)
num_epi_tiles = tile_m * tile_n // epi_tile_size
cta_tile_m = tile_m * (1 + (wg_dimension == hopper_matmul_mgpu.MatmulDimension.M))
cta_tile_n = tile_n * (1 + (wg_dimension == hopper_matmul_mgpu.MatmulDimension.N))
if exceeds_h100_smem(
((cta_tile_m + cta_tile_n) * tile_k * max_concurrent_steps
+ 2 * min(2, num_epi_tiles) * epi_tile_size) * 2
):
self.skipTest("Tile too big to fit into SMEM")
key = jax.random.key(42)
if c_dtype is None:
k1, k2 = jax.random.split(key, 2)
a = jax.random.normal(k1, (m, k), dtype)
b = jax.random.normal(k2, (k, n), dtype)
c = None
rtol = 1e-7
else:
# Uniform avoids too many values around zero which cause precision issues.
k1, k2, k3 = jax.random.split(key, 3)
a = jax.random.uniform(k1, (m, k), dtype)
b = jax.random.uniform(k2, (k, n), dtype)
c = jax.random.uniform(k3, (m, n), c_dtype)
rtol = 5e-3
spec = hopper_matmul_mgpu.TuningConfig(
tile_m=tile_m,
tile_n=tile_n,
tile_k=tile_k,
max_concurrent_steps=max_concurrent_steps,
epi_tile_m=epi_tile_m,
epi_tile_n=epi_tile_n,
wg_dimension=wg_dimension,
**kwargs,
)
out = hopper_matmul_mgpu.matmul(a, b, c, spec)
out_ref = jnp.dot(a, b, precision=jax.lax.DotAlgorithmPreset.F16_F16_F32)
if c is not None:
out_ref = out_ref.astype(c.dtype) + c
np.testing.assert_allclose(out, out_ref, rtol=rtol)
@parameterized.product(
m=(4096,),
k=(4096,),
n=(4096,),
tile_m=(64, 128),
tile_n=(64, 128, 256),
tile_k=(64, 128),
epi_tile_m=(None, 64),
epi_tile_n=(None, 64),
max_concurrent_steps=(2, 4),
lhs_dtype=(jnp.int8,), # TODO(bchetioui): add int4.
rhs_dtype=(jnp.bfloat16, jnp.float16),
wg_dimension=tuple(hopper_mixed_type_matmul_mgpu.MatmulDimension),
)
def test_hopper_mixed_type_matmul(self, *args, **kwargs):
self.check_hopper_mixed_type_matmul(*args, **kwargs)
def check_hopper_mixed_type_matmul(
self,
m,
n,
k,
tile_m,
tile_n,
tile_k,
max_concurrent_steps,
epi_tile_m,
epi_tile_n,
wg_dimension,
lhs_dtype,
rhs_dtype,
**kwargs,
):
if not jtu.is_cuda_compute_capability_equal("9.0"):
self.skipTest("Only works on GPU with capability sm90a")
out_dtype = rhs_dtype
lhs_bits = dtypes.itemsize_bits(lhs_dtype)
rhs_bits = dtypes.itemsize_bits(rhs_dtype)
out_bits = dtypes.itemsize_bits(out_dtype)
cta_tile_m = tile_m * (1 + (wg_dimension == hopper_mixed_type_matmul_mgpu.MatmulDimension.M))
cta_tile_n = tile_n * (1 + (wg_dimension == hopper_mixed_type_matmul_mgpu.MatmulDimension.N))
lhs_smem_bytes = cta_tile_m * tile_k * lhs_bits // 8
rhs_smem_bytes = tile_k * cta_tile_n * rhs_bits // 8
epi_tile_size = (epi_tile_m or tile_m) * (epi_tile_n or tile_n)
num_epi_tiles = tile_m * tile_n // epi_tile_size
out_smem_bytes = 2 * min(2, num_epi_tiles) * epi_tile_size * out_bits // 8
if exceeds_h100_smem(
max_concurrent_steps * (lhs_smem_bytes + rhs_smem_bytes)
+ out_smem_bytes
):
self.skipTest("Tile too big to fit into SMEM")
(k1, k2) = jax.random.split(jax.random.key(42), 2)
lhs = jax.random.randint(
k1, (m, k), minval=-5, maxval=5, dtype=jnp.int8
).astype(lhs_dtype)
rhs = jax.random.normal(k2, (k, n), rhs_dtype)
tuning_config = hopper_mixed_type_matmul_mgpu.TuningConfig(
tile_m=tile_m,
tile_n=tile_n,
tile_k=tile_k,
epi_tile_m=epi_tile_m,
epi_tile_n=epi_tile_n,
max_concurrent_steps=max_concurrent_steps,
wg_dimension=wg_dimension,
**kwargs,
)
out = hopper_mixed_type_matmul_mgpu.mixed_matmul_kernel(
lhs, rhs, out_dtype=out_dtype, config=tuning_config
)
precision = {
jnp.float16: jax.lax.DotAlgorithmPreset.F16_F16_F32,
jnp.bfloat16: jax.lax.DotAlgorithmPreset.BF16_BF16_F32,
}[rhs_dtype]
out_ref = jnp.dot(
lhs.astype(rhs_dtype), rhs, precision=precision,
).astype(out_dtype)
np.testing.assert_allclose(out, out_ref, strict=True)
# Grid tiling doesn't really interact with many other options so we can test
# it separately.
@parameterized.product(
grid_minor_dim=tuple(hopper_matmul_mgpu.MatmulDimension),
grid_tile_width=(1, 3, 4),
)
def test_hopper_mixed_type_matmul_grid_tiling(
self, grid_minor_dim, grid_tile_width
):
self.check_hopper_mixed_type_matmul(
m=4096,
k=4096,
n=4096,
lhs_dtype=jnp.int8,
rhs_dtype=jnp.float16,
tile_m=64,
tile_n=64,
tile_k=64,
max_concurrent_steps=2,
epi_tile_m=64,
epi_tile_n=64,
wg_dimension=hopper_matmul_mgpu.MatmulDimension.M,
grid_minor_dim=grid_minor_dim,
grid_tile_width=grid_tile_width,
)
@parameterized.product(
tile_m=(64, 128),
tile_n=(64, 128),
wg_dimension=tuple(hopper_matmul_mgpu.MatmulDimension),
cluster_dimension=tuple(hopper_matmul_mgpu.MatmulDimension),
)
def test_hopper_mixed_type_matmul_cluster(
self, tile_m, tile_n, wg_dimension, cluster_dimension
):
self.check_hopper_mixed_type_matmul(
m=4096,
k=4096,
n=4096,
lhs_dtype=jnp.int8,
rhs_dtype=jnp.float16,
tile_m=tile_m,
tile_n=tile_n,
tile_k=64,
max_concurrent_steps=4,
epi_tile_m=64,
epi_tile_n=64,
wg_dimension=wg_dimension,
cluster_dimension=cluster_dimension,
)
if __name__ == "__main__":
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/pallas/mgpu_matmul_test.py",
"license": "Apache License 2.0",
"lines": 316,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/pallas/mgpu_ragged_dot_test.py | # Copyright 2025 The JAX Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Test different parameterizations of our Mosaic GPU ragged dot kernel."""
import os
from absl.testing import absltest, parameterized # pylint: disable=g-multiple-import
import jax
from jax import random
from jax._src import config
from jax._src import test_util as jtu
from jax.experimental.pallas.ops.gpu import blackwell_ragged_dot_mgpu
from jax.experimental.pallas.ops.gpu import ragged_dot_mgpu
from jax.experimental.pallas.ops.gpu import transposed_ragged_dot_mgpu
import jax.numpy as jnp
import numpy as np
config.parse_flags_with_absl()
# TODO(justinfu): Test empty groups
def sample_inputs(
key, m, k, n, num_groups, dtype=jnp.float16, transposed=False,
):
kx, ky, kz = random.split(key, num=3)
if transposed:
lhs = jax.random.normal(kx, (k, m), dtype)
rhs = jax.random.normal(ky, (k, n), dtype)
batch_size = k
else:
lhs = jax.random.normal(kx, (m, k), dtype)
rhs = jax.random.normal(ky, (num_groups, k, n), dtype)
batch_size = m
group_boundaries = jax.lax.sort(
jax.random.randint(kz, (num_groups - 1,), 0, batch_size, jnp.int32)
)
group_starts = jax.lax.concatenate(
[jnp.array([0], dtype=jnp.int32), group_boundaries], 0
)
group_ends = jax.lax.concatenate(
[group_boundaries, jnp.array([batch_size], dtype=jnp.int32)], 0
)
group_sizes = group_ends - group_starts
assert group_sizes.shape == (num_groups,)
return lhs, rhs, group_sizes
@jtu.with_config(jax_traceback_filtering="off")
class RaggedDotTestCase(jtu.JaxTestCase):
def setUp(self):
super().setUp()
if ragged_dot_mgpu is None:
self.skipTest("Mosaic GPU not available.")
if (not jtu.test_device_matches(["cuda"]) or
not jtu.is_cuda_compute_capability_equal("9.0")):
self.skipTest("Only works on GPU with capability sm90a")
@parameterized.product(
block_m=(64, 128),
block_n=(64, 128, 192),
block_k=(64, 128),
grid_block_n=(2, 4),
max_concurrent_steps=(2, 4),
num_groups=(1, 3, 16),
transpose_rhs=(False, True),
)
def test_ragged_dot(
self,
block_m,
block_n,
block_k,
grid_block_n,
max_concurrent_steps,
num_groups,
transpose_rhs,
):
dtype = jnp.float16
lhs_smem_size = block_m * block_k * max_concurrent_steps * 2
rhs_smem_size = block_k * block_n * max_concurrent_steps * 2
# H100 SMEM limit is 228kB.
if lhs_smem_size + rhs_smem_size > 228_000:
self.skipTest("This configuration requires too much SMEM.")
m, k, n = 16 * 1024, 2048, 16 * 1024
lhs, rhs, group_sizes = sample_inputs(
random.key(1234), m, k, n, num_groups, dtype
)
out = ragged_dot_mgpu.ragged_dot(
lhs,
jnp.transpose(rhs, (0, 2, 1)) if transpose_rhs else rhs,
group_sizes=group_sizes,
block_m=block_m,
block_n=block_n,
block_k=block_k,
max_concurrent_steps=max_concurrent_steps,
grid_block_n=grid_block_n,
transpose_rhs=transpose_rhs,
)
out_ref = jax.lax.ragged_dot(lhs, rhs, group_sizes=group_sizes)
np.testing.assert_allclose(out, out_ref, atol=1e-3, rtol=1e-3)
@parameterized.product(
block_m=(64, 128),
block_n=(64, 128),
block_k=(64, 128),
grid_block_n=(2, 4),
max_concurrent_steps=(1, 2, 4),
)
def test_ragged_dot_transposed(
self,
block_m,
block_n,
block_k,
grid_block_n,
max_concurrent_steps,
):
# See log at
# https://github.com/jax-ml/jax/actions/runs/20821451405/job/59813460647.
self.skipTest("TODO(bchetioui): this test has broken in CI. Investigate.")
dtype = jnp.float16
lhs_smem_size = block_m * block_k * max_concurrent_steps * 2
rhs_smem_size = block_k * block_n * max_concurrent_steps * 2
# H100 SMEM limit is 228kB.
if lhs_smem_size + rhs_smem_size > 228_000:
self.skipTest("This configuration requires too much SMEM.")
k, m, n, num_groups = 16 * 1024, 2048, 2048, 16
lhs, rhs, group_sizes = sample_inputs(
random.key(1234), m, k, n, num_groups,
dtype=dtype, transposed=True,
)
with jax.numpy_dtype_promotion("standard"):
# We need standard dtype promotion for dynamic grid size to work, because
# python integers are treated as int64, and some of the dtypes inside
# emit_pipeline are hardcoded to use int32.
out = transposed_ragged_dot_mgpu.transposed_ragged_dot(
lhs,
rhs,
group_sizes=group_sizes,
block_m=block_m,
block_n=block_n,
block_k=block_k,
max_concurrent_steps=max_concurrent_steps,
grid_block_n=grid_block_n,
)
out_ref = jax.lax.ragged_dot_general(
lhs, rhs, group_sizes,
ragged_dot_dimension_numbers=jax.lax.RaggedDotDimensionNumbers(
dot_dimension_numbers=(((0,), (0,)), ((), ())),
lhs_ragged_dimensions=[0],
rhs_group_dimensions=[],
)
)
np.testing.assert_allclose(out, out_ref, atol=1e-3, rtol=1e-3)
@jtu.with_config(jax_traceback_filtering="off")
class RaggedDotTCGen05TestCase(jtu.JaxTestCase, jtu.CudaArchSpecificTest):
def setUp(self):
super().setUp()
if blackwell_ragged_dot_mgpu is None:
self.skipTest("Mosaic GPU not available.")
self.skip_unless_tcgen05()
@parameterized.product(
grid_tile_width=(1, 8, 16),
grid_minor_dim=(0, 1),
max_concurrent_steps=(2, 4),
num_groups=(1, 3, 16),
tile_k=(64, 128)
)
def test_ragged_dot(
self,
grid_tile_width,
grid_minor_dim,
max_concurrent_steps,
num_groups,
tile_k,
):
# Kernel does not support other tiling on M and N dimensions currently.
tile_m = 128
tile_n = 128
lhs_smem_size = tile_m * tile_k * max_concurrent_steps * 2
rhs_smem_size = tile_k * tile_n * max_concurrent_steps * 2
# B200 SMEM limit is 228kB.
if lhs_smem_size + rhs_smem_size > 228_000:
self.skipTest("This configuration requires too much SMEM.")
dtype = jnp.float16
m, k, n = 16 * 1024, 2048, 16 * 1024
lhs, rhs, group_sizes = sample_inputs(
random.key(1234), m, k, n, num_groups, dtype
)
tuning_config = blackwell_ragged_dot_mgpu.TuningConfig(
tile_m=tile_m,
tile_n=tile_n,
tile_k=tile_k,
grid_tile_width=grid_tile_width,
grid_minor_dim=grid_minor_dim,
max_concurrent_steps=max_concurrent_steps,
collective=True,
)
out = blackwell_ragged_dot_mgpu.ragged_dot_kernel(
lhs,
rhs,
group_sizes=group_sizes,
config=tuning_config,
)
out_ref = jax.lax.ragged_dot(lhs, rhs, group_sizes=group_sizes,
preferred_element_type=dtype)
np.testing.assert_allclose(out, out_ref, atol=1e-3, rtol=1e-3)
if __name__ == "__main__":
os.environ["XLA_FLAGS"] = (
os.environ.get("XLA_FLAGS", "") + " --xla_gpu_autotune_level=0"
)
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/pallas/mgpu_ragged_dot_test.py",
"license": "Apache License 2.0",
"lines": 213,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/pallas/mgpu_torch_test.py | # Copyright 2025 The JAX Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import functools
from absl.testing import absltest
import jax
from jax._src import config
from jax._src import test_util as jtu
from jax.experimental import pallas as pl
from jax.experimental.pallas import mosaic_gpu as plgpu
import jax.numpy as jnp
import numpy as np
try:
import torch
except ImportError:
torch = None
# pylint: disable=g-import-not-at-top
try:
# We only import this to see if Mosaic is available.
import jax.experimental.mosaic.gpu # noqa: F401
except ImportError:
attention_mgpu = None
else:
from jax.experimental.pallas.ops.gpu import attention_mgpu
config.parse_flags_with_absl()
class TorchTest(jtu.JaxTestCase):
def setUp(self):
super().setUp()
if torch is None:
self.skipTest("Test requires PyTorch")
if attention_mgpu is None:
self.skipTest("Mosaic GPU not available.")
if (not jtu.test_device_matches(["cuda"]) or
not jtu.is_cuda_compute_capability_at_least("9.0")):
self.skipTest("Only works on GPU with capability sm90a+")
def test_simple_pallas_call(self):
@plgpu.as_torch_kernel
@functools.partial(
pl.pallas_call, out_shape=jax.ShapeDtypeStruct([128], jnp.int32)
)
def kernel(x_ref, y_ref, o_ref):
o_ref[...] = x_ref[...] + y_ref[0]
x = torch.arange(128, dtype=torch.int32, device="cuda")
y = torch.arange(128, dtype=torch.int32, device="cuda")
np.testing.assert_array_equal(kernel(x, y).cpu(), (x + y[0]).cpu())
def test_simple_plgpu_kernel(self):
@plgpu.as_torch_kernel
@functools.partial(
plgpu.kernel, out_shape=jax.ShapeDtypeStruct([128], jnp.int32)
)
def kernel(x_ref, y_ref, o_ref):
o_ref[...] = x_ref[...] + y_ref[0]
x = torch.arange(128, dtype=torch.int32, device="cuda")
y = torch.arange(128, dtype=torch.int32, device="cuda")
np.testing.assert_array_equal(kernel(x, y).cpu(), (x + y[0]).cpu())
def test_flip(self):
@functools.partial(
pl.pallas_call, out_shape=(jax.ShapeDtypeStruct([128], jnp.int32),) * 2
)
def kernel(x_ref, y_ref, x_o_ref, y_o_ref):
x_o_ref[...] = x_ref[...]
y_o_ref[...] = y_ref[...]
x = torch.arange(128, dtype=torch.int32, device="cuda")
y = torch.arange(128, dtype=torch.int32, device="cuda")
yo, xo = plgpu.as_torch_kernel(lambda x, y: kernel(x, y)[::-1])(x, y)
np.testing.assert_array_equal(xo.cpu(), x.cpu())
np.testing.assert_array_equal(yo.cpu(), y.cpu())
def test_not_all_returned(self):
@functools.partial(
pl.pallas_call, out_shape=(jax.ShapeDtypeStruct([128], jnp.int32),) * 2
)
def kernel(x_ref, y_ref, x_o_ref, y_o_ref):
x_o_ref[...] = x_ref[...]
y_o_ref[...] = y_ref[...]
x = torch.arange(128, dtype=torch.int32, device="cuda")
y = torch.arange(128, dtype=torch.int32, device="cuda")
xo = plgpu.as_torch_kernel(lambda x, y: kernel(x, y)[0])(x, y)
np.testing.assert_array_equal(xo.cpu(), x.cpu())
def test_invalid(self):
@functools.partial(
pl.pallas_call, out_shape=(jax.ShapeDtypeStruct([128], jnp.int32),) * 2
)
def kernel(x_ref, y_ref, x_o_ref, y_o_ref):
x_o_ref[...] = x_ref[...]
y_o_ref[...] = y_ref[...]
x = torch.arange(128, dtype=torch.int32, device="cuda")
y = torch.arange(128, dtype=torch.int32, device="cuda")
with self.assertRaisesRegex(ValueError, "Unsupported operation .* stablehlo.add"):
plgpu.as_torch_kernel(lambda x, y: x + y)(x, y)
with self.assertRaisesRegex(ValueError, "Multiple Mosaic GPU kernels"):
plgpu.as_torch_kernel(lambda x, y: kernel(*kernel(x, y)))(x, y)
with self.assertRaisesRegex(ValueError, "Unsupported operation .* stablehlo.add"):
plgpu.as_torch_kernel(lambda x, y: kernel(x, y + jnp.ones_like(x)))(x, y)
with self.assertRaisesRegex(ValueError, "The function can only return kernel results"):
plgpu.as_torch_kernel(lambda x, y: (kernel(x, y), x, y))(x, y)
def test_attention(self):
if not jtu.is_cuda_compute_capability_equal("9.0"):
self.skipTest("Test requires compute capability == 9.0")
batch_size = 1
q_seq_len = 4096
kv_seq_len = 4096
head_dim = 64
num_q_heads, num_kv_heads = 4, 1
block_q = block_kv = 64
q = torch.randn(
(batch_size, q_seq_len, num_q_heads, head_dim),
dtype=torch.float16,
device="cuda",
)
k = torch.randn(
(batch_size, kv_seq_len, num_kv_heads, head_dim),
dtype=torch.float16,
device="cuda",
)
v = torch.randn(
(batch_size, kv_seq_len, num_kv_heads, head_dim),
dtype=torch.float16,
device="cuda",
)
kernel_fn = functools.partial(
attention_mgpu.attention,
config=attention_mgpu.TuningConfig(
block_q=block_q,
block_kv=block_kv,
max_concurrent_steps=2,
),
)
np.testing.assert_array_equal(
plgpu.as_torch_kernel(kernel_fn)(q, k, v).cpu(),
kernel_fn(jnp.asarray(q), jnp.asarray(k), jnp.asarray(v)),
)
def test_torch_aliasing(self):
@pl.kernel(mesh=plgpu.Mesh(), out_shape=(), compiler_params=plgpu.CompilerParams())
def kernel(x_ref):
x_ref[...] = jnp.ones_like(x_ref)
x = torch.zeros(128, dtype=torch.float32, device="cuda")
plgpu.as_torch_kernel(kernel)(x) # Run for side effects
np.testing.assert_array_equal(
x.cpu(), torch.ones((128,), dtype=torch.float32, device="cpu")
)
if __name__ == "__main__":
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/pallas/mgpu_torch_test.py",
"license": "Apache License 2.0",
"lines": 153,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/pallas/pipelining/schedule_api_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import dataclasses
from typing import Any
from absl.testing import absltest
import jax
from jax import numpy as jnp
from jax._src import core as jax_core
from jax._src import test_util as jtu
from jax._src.pallas.pipelining import pipeline_test_util as test_util
from jax._src.pallas.pipelining import schedule_api
from jax._src.state import types as state_types
import numpy as np
jax.config.parse_flags_with_absl()
@dataclasses.dataclass(frozen=True)
class MemoryRef:
shape: tuple[int, ...]
dtype: np.dtype
memory_space: Any | None = None
def get_ref_aval(self) -> state_types.AbstractRef:
return state_types.AbstractRef(
inner_aval=jax_core.ShapedArray(shape=self.shape, dtype=self.dtype),
memory_space=self.memory_space,
)
class ApiTest(absltest.TestCase):
def setUp(self):
super().setUp()
if not jtu.test_device_matches(["cpu"]):
self.skipTest("Only works on CPU")
def test_basic_pipeline(self):
# Use reads/writes to mimic the Ref effects of DMAs.
copy_in = schedule_api.AsyncStage(max_in_flight=2)
@copy_in.def_start
def copy_in_start(_, x_ref, o_ref):
del o_ref
# dma_start creates a write_effect to x_ref
x_ref[...] = jnp.ones_like(x_ref)
@copy_in.def_end
def copy_in_end(_, x_ref, o_ref):
del o_ref
# dma_end creates a write_effect to x_ref
x_ref[...] = jnp.ones_like(x_ref)
@schedule_api.stage(max_in_flight=2)
def kernel_body(_, x_ref, o_ref):
o_ref[...] = x_ref[...] + 1.0
copy_out = schedule_api.AsyncStage(max_in_flight=2)
@copy_out.def_start
def copy_out_start(_, x_ref, o_ref):
del x_ref
# dma_start creates a read_effect to o_ref
_ = o_ref[...]
@copy_out.def_end
def copy_out_end(_, x_ref, o_ref):
del x_ref
# dma_end creates a read_effect to o_ref
_ = o_ref[...]
pipeline = schedule_api.schedule_pipeline(
stages=(copy_in, kernel_body, copy_out),
grid=(4,),
args=(
MemoryRef(shape=(128, 128), dtype=jnp.dtype(jnp.float32),
memory_space="VMEM"),
MemoryRef(shape=(128, 128), dtype=jnp.dtype(jnp.float32),
memory_space="VMEM"),
),
eval_fn=test_util.print_stage,
)
ref = jnp.ones((128, 128), jnp.float32)
ref = jax.new_ref(ref)
with jtu.capture_stdout() as stdout:
pipeline(ref, ref)
output = stdout().strip().split("\n")
expected = [
# step
"[itr=0] copy_in_start",
"[itr=1] copy_in_start",
# step
"[itr=0] copy_in_end",
"[itr=0] kernel_body",
"[itr=0] copy_out_start",
"[itr=2] copy_in_start",
# step
"[itr=1] copy_in_end",
"[itr=1] kernel_body",
"[itr=1] copy_out_start",
"[itr=3] copy_in_start",
# step
test_util.AnyOrder([
"[itr=0] copy_out_end",
"[itr=2] copy_in_end"]),
"[itr=2] kernel_body",
"[itr=2] copy_out_start",
# step
test_util.AnyOrder([
"[itr=1] copy_out_end",
"[itr=3] copy_in_end"]),
"[itr=3] kernel_body",
"[itr=3] copy_out_start",
# step
"[itr=2] copy_out_end",
"[itr=3] copy_out_end",
]
self.assertTrue(test_util.compare_lists(output, expected))
if __name__ == "__main__":
absltest.main()
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/pallas/pipelining/schedule_api_test.py",
"license": "Apache License 2.0",
"lines": 116,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/pallas/pipelining/schedulers_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from absl.testing import absltest
from absl.testing import parameterized
import jax
from jax._src import test_util as jtu
from jax._src.pallas.pipelining import internal
from jax._src.pallas.pipelining import pipeline_test_util as test_util
from jax._src.pallas.pipelining import schedulers
jax.config.parse_flags_with_absl()
def empty_jaxpr():
def noop():
pass
return jax.make_jaxpr(noop)
class SchedulersGoldenTest(parameterized.TestCase):
def setUp(self):
super().setUp()
if not jtu.test_device_matches(["cpu"]):
self.skipTest("Only works on CPU")
def test_2_async_stages(self):
# This test uses 2 stages that are both async.
# 1
# |
# 2
token1 = internal.make_token("a")
token2 = internal.make_token("b")
stage1_start = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.WriteEffect(token1),),
properties=internal.SchedulingProperties(
max_in_flight=3, is_async_start=True, is_async_done=False),
name="stage1_start"
)
stage1_done = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.ReadEffect(token1), internal.WriteEffect(0)),
properties=internal.SchedulingProperties(
max_in_flight=3, is_async_start=False, is_async_done=True),
name="stage1_end"
)
stage2_start = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.WriteEffect(token2),
# We need to insert this token so that stage1_start
# does not clobber input 0.
internal.ReadEffect(token1),
internal.ReadEffect(0)),
properties=internal.SchedulingProperties(
max_in_flight=3, is_async_start=True, is_async_done=False),
name="stage2_start"
)
stage2_done = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.ReadEffect(token2),),
properties=internal.SchedulingProperties(
max_in_flight=3, is_async_start=False, is_async_done=True),
name="stage2_end"
)
loop_struct = internal.NDLoopStruct(
stages=(stage1_start, stage1_done, stage2_start, stage2_done),
grid=(4,)
)
with jtu.capture_stdout() as stdout:
schedulers.static_nd_loop_scheduler(
loop_struct,
args=(None,),
eval_fn=test_util.print_stage)
output = stdout().strip().split("\n")
expected = [
"[itr=0] stage1_start",
"[itr=1] stage1_start",
"[itr=2] stage1_start",
"[itr=0] stage1_end",
"[itr=0] stage2_start",
"[itr=3] stage1_start",
"[itr=1] stage1_end",
"[itr=1] stage2_start",
"[itr=2] stage1_end",
"[itr=2] stage2_start",
"[itr=3] stage1_end",
"[itr=0] stage2_end",
"[itr=3] stage2_start",
"[itr=1] stage2_end",
"[itr=2] stage2_end",
"[itr=3] stage2_end",
]
self.assertEqual(output, expected)
def test_async_inputs_with_different_buffering(self):
# This test uses 2 input stages (1a, 1b) that feed into a synchronous stage.
# 1a 1b
# \ /
# 2
token1a = internal.make_token("1a")
token1b = internal.make_token("1b")
stage1a_start = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.WriteEffect(token1a),),
properties=internal.SchedulingProperties(
max_in_flight=2, is_async_start=True, is_async_done=False),
name="stage1a_start"
)
stage1a_done = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.ReadEffect(token1a), internal.WriteEffect(0)),
properties=internal.SchedulingProperties(
max_in_flight=2, is_async_start=False, is_async_done=True),
name="stage1a_end"
)
stage1b_start = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.WriteEffect(token1b),),
properties=internal.SchedulingProperties(
max_in_flight=4, is_async_start=True, is_async_done=False),
name="stage1b_start"
)
stage1b_done = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.ReadEffect(token1b), internal.WriteEffect(1)),
properties=internal.SchedulingProperties(
max_in_flight=4, is_async_start=False, is_async_done=True),
name="stage1b_end"
)
stage2 = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.ReadEffect(token1a),
internal.ReadEffect(token1b),
internal.ReadEffect(0),
internal.ReadEffect(1)),
properties=internal.SchedulingProperties(
max_in_flight=2, is_async_start=False, is_async_done=False),
name="stage2"
)
loop_struct = internal.NDLoopStruct(
stages=(stage1a_start, stage1a_done,
stage1b_start, stage1b_done,
stage2,),
grid=(6,)
)
with jtu.capture_stdout() as stdout:
schedulers.static_nd_loop_scheduler(
loop_struct,
args=(None, None),
eval_fn=test_util.print_stage)
output = stdout().strip().split("\n")
expected = [
"[itr=0] stage1a_start",
"[itr=0] stage1b_start",
"[itr=1] stage1b_start",
"[itr=2] stage1b_start",
"[itr=1] stage1a_start",
"[itr=3] stage1b_start",
"[itr=0] stage1a_end",
"[itr=0] stage1b_end",
"[itr=0] stage2",
"[itr=2] stage1a_start",
"[itr=4] stage1b_start",
"[itr=1] stage1a_end",
"[itr=1] stage1b_end",
"[itr=1] stage2",
"[itr=3] stage1a_start",
"[itr=5] stage1b_start",
"[itr=2] stage1a_end",
"[itr=2] stage1b_end",
"[itr=2] stage2",
"[itr=4] stage1a_start",
"[itr=3] stage1b_end",
"[itr=3] stage1a_end",
"[itr=3] stage2",
"[itr=5] stage1a_start",
"[itr=4] stage1b_end",
"[itr=4] stage1a_end",
"[itr=4] stage2",
"[itr=5] stage1a_end",
"[itr=5] stage1b_end",
"[itr=5] stage2",
]
self.assertEqual(output, expected)
def test_synchronous_3_stage(self):
# This test models a 3-stage pipeline where all stages are synchronous.
# 1
# |
# 2
# |
# 3
stage1 = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.WriteEffect(0),),
properties=internal.SchedulingProperties(
max_in_flight=3, is_async_start=False, is_async_done=False),
name="stage1"
)
stage2 = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.ReadEffect(0), internal.WriteEffect(1),),
properties=internal.SchedulingProperties(
max_in_flight=3, is_async_start=False, is_async_done=False),
name="stage2"
)
stage3 = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.ReadEffect(1),),
properties=internal.SchedulingProperties(
max_in_flight=3, is_async_start=False, is_async_done=False),
name="stage3"
)
loop_struct = internal.NDLoopStruct(
stages=(stage1, stage2, stage3),
grid=(4,)
)
with jtu.capture_stdout() as stdout:
schedulers.static_nd_loop_scheduler(
loop_struct,
args=(None, None),
eval_fn=test_util.print_stage)
output = stdout().strip().split("\n")
expected = [
# step
"[itr=0] stage1",
# step
"[itr=1] stage1",
"[itr=0] stage2",
# step
"[itr=2] stage1",
"[itr=1] stage2",
"[itr=0] stage3",
# step
"[itr=3] stage1",
"[itr=2] stage2",
"[itr=1] stage3",
# step
"[itr=3] stage2",
"[itr=2] stage3",
# step
"[itr=3] stage3",
]
self.assertEqual(output, expected)
def test_standard_emit_pipeline(self):
# This test uses 3 stages where copy_in and copy_out are async.
# copy_in
# |
# body
# |
# copy_out
token1 = internal.make_token("a")
token2 = internal.make_token("b")
copy_in_start = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.WriteEffect(token1),),
properties=internal.SchedulingProperties(
max_in_flight=2, is_async_start=True, is_async_done=False),
name="copy_in_start"
)
copy_in_done = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.ReadEffect(token1), internal.WriteEffect(0)),
properties=internal.SchedulingProperties(
max_in_flight=2, is_async_start=False, is_async_done=True),
name="copy_in_done"
)
body_stage = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.ReadEffect(token1), internal.ReadEffect(0),
internal.WriteEffect(1)),
properties=internal.SchedulingProperties(
max_in_flight=2, is_async_start=False, is_async_done=False),
name="body"
)
copy_out_start = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.WriteEffect(token2),
internal.ReadEffect(1)),
properties=internal.SchedulingProperties(
max_in_flight=2, is_async_start=True, is_async_done=False),
name="copy_out_start"
)
copy_out_done = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.ReadEffect(token2),),
properties=internal.SchedulingProperties(
max_in_flight=2, is_async_start=False, is_async_done=True),
name="copy_out_done"
)
loop_struct = internal.NDLoopStruct(
stages=(copy_in_start, copy_in_done, body_stage,
copy_out_start, copy_out_done),
grid=(4, 4)
)
with jtu.capture_stdout() as stdout:
schedulers.static_nd_loop_scheduler(
loop_struct,
args=(None,),
eval_fn=test_util.print_stage)
output = stdout().strip().split("\n")
prologue = [
"[itr=0] copy_in_start",
"[itr=1] copy_in_start",
"[itr=0] copy_in_done",
"[itr=0] body",
"[itr=0] copy_out_start",
"[itr=2] copy_in_start",
"[itr=1] copy_in_done",
"[itr=1] body",
"[itr=1] copy_out_start",
]
steady_state = []
for itr in range(3, 16):
steady_state.extend([
f"[itr={itr}] copy_in_start",
test_util.AnyOrder([
f"[itr={itr-3}] copy_out_done",
f"[itr={itr-1}] copy_in_done",]),
f"[itr={itr-1}] body",
f"[itr={itr-1}] copy_out_start",
])
epilogue = [
"[itr=15] copy_in_done",
"[itr=13] copy_out_done",
"[itr=15] body",
"[itr=15] copy_out_start",
"[itr=14] copy_out_done",
"[itr=15] copy_out_done",
]
expected = prologue + steady_state + epilogue
list_equal = test_util.compare_lists(output, expected)
self.assertTrue(list_equal)
def test_pipelined_prefetch(self):
# This test uses 4 stages where prefetch, copy_in and copy_out are async.
# prefetch
# |
# copy_in
# |
# body
# |
# copy_out
token1 = internal.make_token("a")
token2 = internal.make_token("b")
token_prefetch = internal.make_token("c")
prefetch_start = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.WriteEffect(token_prefetch),),
properties=internal.SchedulingProperties(
max_in_flight=2, is_async_start=True, is_async_done=False),
name="prefetch_start"
)
prefetch_done = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.ReadEffect(token_prefetch), internal.WriteEffect(0)),
properties=internal.SchedulingProperties(
max_in_flight=2, is_async_start=False, is_async_done=True),
name="prefetch_done"
)
copy_in_start = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.ReadEffect(token_prefetch),
internal.ReadEffect(0),
internal.WriteEffect(token1),),
properties=internal.SchedulingProperties(
max_in_flight=2, is_async_start=True, is_async_done=False),
name="copy_in_start"
)
copy_in_done = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.ReadEffect(token1), internal.WriteEffect(1)),
properties=internal.SchedulingProperties(
max_in_flight=2, is_async_start=False, is_async_done=True),
name="copy_in_done"
)
body_stage = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.ReadEffect(token1), internal.ReadEffect(1),
internal.WriteEffect(2)),
properties=internal.SchedulingProperties(
max_in_flight=2, is_async_start=False, is_async_done=False),
name="body"
)
copy_out_start = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.WriteEffect(token2),
internal.ReadEffect(2)),
properties=internal.SchedulingProperties(
max_in_flight=2, is_async_start=True, is_async_done=False),
name="copy_out_start"
)
copy_out_done = internal.PipelineStage(
jaxpr=empty_jaxpr(),
effects=(internal.ReadEffect(token2),),
properties=internal.SchedulingProperties(
max_in_flight=2, is_async_start=False, is_async_done=True),
name="copy_out_done"
)
loop_struct = internal.NDLoopStruct(
stages=(prefetch_start, prefetch_done,
copy_in_start, copy_in_done,
body_stage,
copy_out_start, copy_out_done),
grid=(4, 4)
)
with jtu.capture_stdout() as stdout:
schedulers.static_nd_loop_scheduler(
loop_struct,
args=(None,),
eval_fn=test_util.print_stage)
output = stdout().strip().split("\n")
# The schedule is slightly suboptimal here, noted in the comments.
prologue = [
"[itr=0] prefetch_start",
"[itr=1] prefetch_start",
"[itr=0] prefetch_done",
"[itr=0] copy_in_start",
"[itr=2] prefetch_start",
"[itr=1] prefetch_done",
"[itr=1] copy_in_start",
"[itr=3] prefetch_start",
"[itr=0] copy_in_done",
# This can be pushed after body, before [itr=2] copy_in_start
"[itr=2] prefetch_done",
"[itr=0] body",
"[itr=0] copy_out_start",
"[itr=2] copy_in_start",
"[itr=4] prefetch_start",
"[itr=1] copy_in_done",
# This can be pushed after body, before [itr=2] copy_in_start
"[itr=3] prefetch_done",
"[itr=1] body",
"[itr=1] copy_out_start",
"[itr=3] copy_in_start",
# This can be pushed after [itr=5] prefetch_start
"[itr=0] copy_out_done",
"[itr=5] prefetch_start",
"[itr=2] copy_in_done",
"[itr=4] prefetch_done",
"[itr=2] body",
"[itr=2] copy_out_start",
]
steady_state = []
for i in range(6, 16):
steady_state.extend([
f"[itr={i-2}] copy_in_start",
f"[itr={i-5}] copy_out_done",
f"[itr={i}] prefetch_start",
f"[itr={i-3}] copy_in_done",
f"[itr={i-1}] prefetch_done",
f"[itr={i-3}] body",
f"[itr={i-3}] copy_out_start",
])
epilogue = [
"[itr=14] copy_in_start",
"[itr=11] copy_out_done",
"[itr=15] prefetch_done",
"[itr=13] copy_in_done",
"[itr=13] body",
"[itr=13] copy_out_start",
"[itr=15] copy_in_start",
"[itr=12] copy_out_done",
"[itr=14] copy_in_done",
"[itr=14] body",
"[itr=14] copy_out_start",
"[itr=15] copy_in_done",
"[itr=13] copy_out_done",
"[itr=15] body",
"[itr=15] copy_out_start",
"[itr=14] copy_out_done",
"[itr=15] copy_out_done",
]
expected = prologue + steady_state + epilogue
self.assertEqual(output, expected)
if __name__ == "__main__":
absltest.main()
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/pallas/pipelining/schedulers_test.py",
"license": "Apache License 2.0",
"lines": 479,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/pallas/tpu_info_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from absl.testing import absltest
import jax
from jax._src import test_util as jtu
from jax.experimental.pallas import tpu as pltpu
class TpuInfoTest(jtu.JaxTestCase):
def setUp(self):
super().setUp()
if not jtu.is_device_tpu():
self.assertFalse(pltpu.is_tpu_device())
self.skipTest("Skipping test because device is not a TPU.")
else:
self.assertTrue(pltpu.is_tpu_device())
def test_get_tpu_info(self):
device = jax.devices()[0]
info = pltpu.get_tpu_info()
self.assertIsInstance(info, pltpu.TpuInfo)
match device.device_kind:
case "TPU v2":
self.assertEqual(info.chip_version, pltpu.ChipVersion.TPU_V2)
case "TPU v3":
self.assertEqual(info.chip_version, pltpu.ChipVersion.TPU_V3)
case "TPU v4 lite":
self.assertEqual(info.chip_version, pltpu.ChipVersion.TPU_V4I)
case "TPU v4":
self.assertEqual(info.chip_version, pltpu.ChipVersion.TPU_V4)
case "TPU v5 lite":
self.assertEqual(info.chip_version, pltpu.ChipVersion.TPU_V5E)
case "TPU v5":
self.assertEqual(info.chip_version, pltpu.ChipVersion.TPU_V5P)
case "TPU v6 lite":
self.assertEqual(info.chip_version, pltpu.ChipVersion.TPU_V6E)
case "TPU7":
self.assertEqual(info.chip_version, pltpu.ChipVersion.TPU_7)
case "TPU7x":
self.assertEqual(info.chip_version, pltpu.ChipVersion.TPU_7X)
case _:
self.fail(f"Unexpected device kind: {device.device_kind}")
def test_is_matmul_supported_input_formats(self):
info = pltpu.get_tpu_info()
with self.subTest("str"):
self.assertTrue(info.is_matmul_supported("float32", "float32"))
with self.subTest("dtype"):
self.assertTrue(
info.is_matmul_supported(
jax.numpy.float32, jax.numpy.dtype("float32")
)
)
with self.subTest("array.dtype"):
a = jax.numpy.array([1.0], dtype=jax.numpy.float32)
b = jax.numpy.array([2.0], dtype="float32")
self.assertTrue(info.is_matmul_supported(a.dtype, b.dtype))
def test_is_lite(self):
info = pltpu.get_tpu_info()
if info.chip_version in {
pltpu.ChipVersion.TPU_V4I,
pltpu.ChipVersion.TPU_V5E,
pltpu.ChipVersion.TPU_V6E,
}:
self.assertTrue(info.is_lite)
else:
self.assertFalse(info.is_lite)
def test_is_split_chip(self):
info = pltpu.get_tpu_info()
if info.chip_version in {
pltpu.ChipVersion.TPU_V2,
pltpu.ChipVersion.TPU_V3,
pltpu.ChipVersion.TPU_7,
pltpu.ChipVersion.TPU_7X,
}:
self.assertTrue(info.is_split_chip)
else:
self.assertFalse(info.is_split_chip)
def test_is_megacore(self):
info = pltpu.get_tpu_info()
if info.chip_version in {
pltpu.ChipVersion.TPU_V4,
pltpu.ChipVersion.TPU_V5P,
}:
self.assertTrue(info.is_megacore)
else:
self.assertFalse(info.is_megacore)
def test_num_cores(self):
info = pltpu.get_tpu_info()
if info.chip_version in {
pltpu.ChipVersion.TPU_V4,
pltpu.ChipVersion.TPU_V5P,
}:
self.assertEqual(info.num_cores, 2)
else:
self.assertEqual(info.num_cores, 1)
def test_get_tpu_info_given_chip_version(self):
info = pltpu.get_tpu_info()
num_cores = (
2
if info.chip_version
in {
pltpu.ChipVersion.TPU_V4,
pltpu.ChipVersion.TPU_V5P,
}
else 1
)
info_for_chip = pltpu.get_tpu_info_for_chip(info.chip_version, num_cores)
self.assertEqual(info, info_for_chip)
class TpuInfoStaticTest(jtu.JaxTestCase):
def test_all_chip_versions_properties(self):
for version in pltpu.ChipVersion:
match version:
case pltpu.ChipVersion.TPU_V4 | pltpu.ChipVersion.TPU_V5P:
# Megacore support
# 1. Split mode
info_split = pltpu.get_tpu_info_for_chip(version, 1)
self.assertFalse(info_split.is_megacore)
self.assertTrue(info_split.is_split_chip)
self.assertEqual(version.num_physical_tensor_cores_per_chip, 2)
# 2. Megacore mode
info_mega = pltpu.get_tpu_info_for_chip(version, 2)
self.assertTrue(info_mega.is_megacore)
self.assertFalse(info_mega.is_megacore and info_mega.is_split_chip)
self.assertTrue(version.supports_megacore)
case (
pltpu.ChipVersion.TPU_V2
| pltpu.ChipVersion.TPU_V3
| pltpu.ChipVersion.TPU_7
| pltpu.ChipVersion.TPU_7X
):
# Dual core, no megacore
info = pltpu.get_tpu_info_for_chip(version, 1)
self.assertFalse(info.is_megacore)
self.assertTrue(info.is_split_chip)
self.assertFalse(version.supports_megacore)
with self.assertRaisesRegex(
ValueError, "Lite chips and dual-core chips that do not support"
):
pltpu.get_tpu_info_for_chip(version, 2)
case (
pltpu.ChipVersion.TPU_V4I
| pltpu.ChipVersion.TPU_V5E
| pltpu.ChipVersion.TPU_V6E
):
# Single core
info = pltpu.get_tpu_info_for_chip(version, 1)
self.assertFalse(info.is_megacore)
self.assertFalse(info.is_split_chip)
self.assertTrue(info.is_lite)
self.assertFalse(version.supports_megacore)
with self.assertRaisesRegex(
ValueError, "Lite chips and dual-core chips that do not support"
):
pltpu.get_tpu_info_for_chip(version, 2)
case _:
raise ValueError(f"Unexpected chip version: {version}")
def test_is_matmul_supported_all_gens(self):
for version in pltpu.ChipVersion:
info = pltpu.get_tpu_info_for_chip(version, 1)
# F32/BF16 always supported on all TPUs
self.assertTrue(
info.is_matmul_supported("float32", "float32"), msg=f"{version} f32"
)
if info.generation >= 4:
self.assertTrue(
info.is_matmul_supported("bfloat16", "bfloat16"),
msg=f"{version} bf16",
)
if __name__ == "__main__":
jax.config.parse_flags_with_absl()
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/pallas/tpu_info_test.py",
"license": "Apache License 2.0",
"lines": 179,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/pallas/tpu_pallas_call_print_test.py | # Copyright 2023 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test TPU-specific extensions to pallas print call."""
import functools
import re
from absl.testing import absltest
from absl.testing import parameterized
import jax
from jax._src import test_util as jtu
from jax._src.pallas import pallas_test_util as ptu
from jax.experimental import pallas as pl
from jax.experimental.pallas import tpu as pltpu
import jax.numpy as jnp
import numpy as np
jax.config.parse_flags_with_absl()
P = jax.sharding.PartitionSpec
partial = functools.partial
@jtu.thread_unsafe_test_class() # debug print test is not thread safe
class PallasCallPrintTest(ptu.PallasTPUTest):
def test_debug_print(self):
@functools.partial(
self.pallas_call,
out_shape=jax.ShapeDtypeStruct((8, 128), jnp.float32),
)
def kernel(x_ref, o_ref):
pl.debug_print('It works!')
x = jnp.arange(8 * 128, dtype=jnp.float32).reshape((8, 128))
compiled_kernel = (
jax.jit(kernel)
.lower(x)
.compile({'xla_tpu_enable_log_recorder': 'true'})
)
with jtu.capture_stderr() as get_output:
jax.block_until_ready(compiled_kernel(x))
self.assertIn('It works!', get_output())
def test_debug_print_in_index_map(self):
def index_map(i):
pl.debug_print('It works!')
return (i, 0)
@functools.partial(
self.pallas_call,
grid=(1,),
in_specs=(pl.BlockSpec(index_map=index_map),),
out_shape=jax.ShapeDtypeStruct((8, 128), jnp.float32),
)
def kernel(x_ref, o_ref):
o_ref[...] = x_ref[...]
x = jnp.arange(8 * 128, dtype=jnp.float32).reshape((8, 128))
compiled_kernel = (
jax.jit(kernel)
.lower(x)
.compile({'xla_tpu_enable_log_recorder': 'true'})
)
with jtu.capture_stderr() as get_output:
jax.block_until_ready(compiled_kernel(x))
self.assertIn('It works!', get_output())
@parameterized.product(dtype=[jnp.int32, jnp.float32])
def test_debug_print_with_values(self, dtype):
@functools.partial(
self.pallas_call,
in_specs=(pl.BlockSpec(memory_space=pltpu.SMEM),),
out_shape=jax.ShapeDtypeStruct((8, 128), jnp.float32),
)
def kernel(x_ref, o_ref):
if dtype == jnp.int32:
pl.debug_print('BEGIN1 x[0] == {}', x_ref[0])
pl.debug_print(
'BEGIN2 x[0] == {} ; x[1] == {} ; END', x_ref[0], x_ref[1]
)
else:
pl.debug_print('BEGIN1 x[0] == ', x_ref[0])
x = jnp.array([42, 24], dtype=dtype)
compiled_kernel = (
jax.jit(kernel)
.lower(x)
.compile({'xla_tpu_enable_log_recorder': 'true'})
)
with jtu.capture_stderr() as get_output:
jax.block_until_ready(compiled_kernel(x))
output = get_output()
if dtype == jnp.int32:
self.assertIn('BEGIN1 x[0] == 42', output)
self.assertIn('BEGIN2 x[0] == 42 ; x[1] == 24 ; END', output)
else:
self.assertIn('BEGIN1 x[0] == f32[] 42', output)
@parameterized.named_parameters(
(f"{'_'.join(map(str, shape))}_{dtype.__name__}", shape, dtype)
for shape in (
(2, 8, 128),
# test unaligned shapes
(3,),
(3, 4),
(2, 3, 4),
(2, 9, 129),
)
for dtype in (jnp.int32, jnp.uint32, jnp.float32)
)
def test_debug_print_vector(self, shape, dtype):
@functools.partial(
self.pallas_call,
out_shape=jax.ShapeDtypeStruct(shape, dtype),
)
def kernel(x_ref, o_ref):
pl.debug_print("{}", x_ref[...])
o_ref[...] = x_ref[...]
n = np.prod(shape)
x = jnp.arange(n, dtype=dtype).reshape(shape)
compiled_kernel = (
jax.jit(kernel)
.lower(x)
.compile({"xla_tpu_enable_log_recorder": "true"})
)
with jtu.capture_stderr() as get_output:
jax.block_until_ready(compiled_kernel(x))
output = get_output()
numbers = [
int(num)
for line in output.splitlines()
if (match := re.search(r"\{(.*)", line)) # extract contents after `{`
for num in re.findall(r"\d+", match.group(1))
]
# Check if the numbers in the output match the values generated by `arange`.
self.assertLen(numbers, n)
self.assertTrue(all(num == i for i, num in enumerate(numbers)))
if __name__ == '__main__':
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/pallas/tpu_pallas_call_print_test.py",
"license": "Apache License 2.0",
"lines": 137,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/pallas/tpu_pallas_interpret_thread_map_test.py | # Copyright 2024 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Thread map test for TPU-specific interpret mode."""
import threading
from absl.testing import absltest
import jax
from jax._src import test_util as jtu
from jax._src.pallas.mosaic.interpret.thread_map import thread_map
jax.config.parse_flags_with_absl()
jax.config.update('jax_threefry_partitionable', True)
# TODO(jburnim): Figure out how to safely run different instance of TPU
# interpret mode in parallel, and then remove this decorator.
@jtu.thread_unsafe_test_class()
class InterpretThreadMapTest(jtu.JaxTestCase):
def setUp(self):
super().setUp()
if not jtu.test_device_matches(['cpu']):
self.skipTest('CPU-only test')
self.num_devices = jax.device_count()
if self.num_devices > 1:
# Workaround for https://github.com/jax-ml/jax/issues/25671
self.skipTest(f'requires 1 device, found {self.num_devices}')
def test_thread_map(self):
barrier = threading.Barrier(8)
lock = threading.Lock()
concurrent_calls = [0]
max_concurrent_calls = [0]
def _barrier():
with lock:
concurrent_calls[0] += 1
max_concurrent_calls[0] = max(
max_concurrent_calls[0], concurrent_calls[0])
barrier.wait()
with lock:
concurrent_calls[0] -= 1
def f(core_index):
del core_index
jax.experimental.io_callback(_barrier, (), ordered=True)
thread_map(f, 8)
self.assertEqual(max_concurrent_calls[0], 8)
# `thread_map` returns only after all threads have completed, so the final
# value of `concurrent_calls` should be zero.
self.assertEqual(concurrent_calls[0], 0)
if __name__ == '__main__':
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/pallas/tpu_pallas_interpret_thread_map_test.py",
"license": "Apache License 2.0",
"lines": 56,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/pallas/tpu_pallas_memory_space_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test TPU-specific uses of Pallas memory space APIs."""
import functools
from absl.testing import absltest
from absl.testing import parameterized
import jax
from jax._src import test_util as jtu
from jax.experimental import pallas as pl
from jax.experimental.pallas import tpu as pltpu
import jax.numpy as jnp
import numpy as np
jax.config.parse_flags_with_absl()
P = jax.sharding.PartitionSpec
partial = functools.partial
class TPUPallasCallMemorySpaceTest(jtu.JaxTestCase):
def setUp(self):
super().setUp()
if not jtu.is_device_tpu_at_least(5):
self.skipTest('Needs a newer TPU')
@parameterized.parameters(
(pltpu.VMEM, 1),
(pltpu.SMEM, 4),
(pltpu.HBM, 0),
(pl.ANY, None),
)
def test_basic_input_memory_space_constraint(self, memory_space, color):
def kernel(x_ref, y_ref):
pltpu.sync_copy(x_ref, y_ref)
def g(x):
return pl.pallas_call(
kernel,
out_shape=x,
in_specs=[pl.BlockSpec(memory_space=memory_space)],
out_specs=pl.BlockSpec(memory_space=pl.ANY),
)(x)
@jax.jit
def f(x):
x = pltpu.with_memory_space_constraint(x, memory_space=memory_space)
if color is not None:
self.assertEqual(jax.typeof(x).memory_space, memory_space)
x = g(x)
return x
x = jnp.ones((8, 128), dtype=jnp.float32)
y = f(x)
np.testing.assert_array_equal(y, x)
hlo = jax.jit(f).lower(x).compile().as_text()
if color is None or memory_space == pltpu.SMEM:
self.assertIn('"input_memory_space_colors":[]', hlo)
else:
self.assertIn(
f'"input_memory_space_colors":[{{"operand_index":"0","color":"{color}","shape_index":[]}}]',
hlo,
)
@parameterized.parameters(
(pltpu.VMEM, 1),
(pltpu.SMEM, 4),
(pltpu.HBM, 0),
(pl.ANY, None),
(pltpu.HOST, 5),
)
def test_basic_output_memory_space_constraint(self, memory_space, color):
out_shape_ctor = memory_space
if color is None:
out_shape_ctor = jax.ShapeDtypeStruct
def kernel(x_ref, y_ref):
pltpu.sync_copy(x_ref, y_ref)
def g(x):
return pl.pallas_call(
kernel,
out_shape=out_shape_ctor(x.shape, x.dtype),
in_specs=[pl.BlockSpec(memory_space=pl.ANY)],
out_specs=pl.BlockSpec(memory_space=memory_space),
)(x)
if memory_space == pltpu.HOST:
if jax.device_count() > 1:
self.skipTest('Test only works with a single device.')
out_sharding = jax.sharding.NamedSharding(
jax.sharding.Mesh(jax.devices(), 'x'),
jax.sharding.PartitionSpec(),
memory_kind='pinned_host',
)
else:
out_sharding = None
@functools.partial(jax.jit, out_shardings=out_sharding)
def f(x):
x = g(x)
return x
x = jnp.ones((8, 128), dtype=jnp.float32)
y = f(x)
np.testing.assert_array_equal(y, x)
hlo = jax.jit(f, out_shardings=out_sharding).lower(x).compile().as_text()
if color is None:
self.assertIn('"output_memory_space_colors":[]', hlo)
else:
self.assertIn(
f'"output_memory_space_colors":[{{"color":"{color}","shape_index":[]}}]',
hlo,
)
class TPUCoreMapMemorySpaceTest(jtu.JaxTestCase):
def setUp(self):
super().setUp()
if not jtu.is_device_tpu_at_least(5):
self.skipTest('Needs a newer TPU')
@parameterized.parameters(
(pltpu.VMEM, 1),
(pltpu.SMEM, 4),
(pltpu.HBM, 0),
(pl.ANY, None),
)
def test_basic_ref_memory_space_constraint(self, memory_space, color):
@jax.jit
def f(x):
x_ref = jax.new_ref(x, memory_space=memory_space)
y_ref = jax.new_ref(pl.empty_like(x), memory_space=memory_space)
self.assertEqual(jax.typeof(x_ref).memory_space, memory_space)
self.assertEqual(jax.typeof(y_ref).memory_space, memory_space)
@pl.core_map(mesh=pltpu.create_tensorcore_mesh('core'))
def _():
if jax.typeof(x_ref).memory_space is pltpu.VMEM:
y_ref[...] = x_ref[...]
else:
pltpu.sync_copy(x_ref, y_ref)
return y_ref[...]
x = jnp.arange(1024, dtype=jnp.float32).reshape((8, 128))
num_cores = jax.devices()[0].num_cores
if num_cores > 1 and memory_space == pltpu.VMEM:
with self.assertRaisesRegex(
NotImplementedError,
'TensorCoreMesh does not support VMEM inputs/outputs when there are'
' >1 cores. Use HBM or ANY instead.',
):
f.lower(x).compile()
return
lowered = f.lower(x)
compiled = lowered.compile()
hlo = compiled.as_text()
if color is None or memory_space == pltpu.SMEM:
self.assertIn('"input_memory_space_colors":[]', hlo)
else:
self.assertIn(
f'"input_memory_space_colors":[{{"operand_index":"0","color":"{color}","shape_index":[]}},{{"operand_index":"1","color":"{color}","shape_index":[]}}]',
hlo,
)
y = compiled(x)
np.testing.assert_array_equal(y, x)
def test_smem_copy(self):
mesh = pltpu.create_tensorcore_mesh('core')
if len(mesh.devices) > 1:
self.skipTest('Only one core is supported for this test.')
kernel = pl.core_map(mesh=mesh)
@jax.jit
def f():
y_ref = pl.empty_ref_like(pltpu.SMEM((8,), jnp.int32))
@kernel
def _():
for i in range(y_ref.shape[0]):
y_ref[i] = i
@kernel
def _():
for i in range(y_ref.shape[0]):
y_ref[i] = y_ref[i] + 1
return y_ref[...]
np.testing.assert_array_equal(f(), np.arange(8) + 1)
def test_smem_async_copy(self):
mesh = pltpu.create_tensorcore_mesh('core')
if len(mesh.devices) > 1:
self.skipTest('Only one core is supported for this test.')
kernel = pl.core_map(mesh=mesh)
@jax.jit
def f():
y_ref = pl.empty_ref_like(pltpu.SMEM((8,), jnp.int32))
@kernel
def _():
for i in range(y_ref.shape[0]):
y_ref[i] = i
@kernel
def _():
for i in range(y_ref.shape[0]):
y_ref[i] = y_ref[i] + 1
y_out_ref = pl.empty_ref_like(pltpu.HBM((8,), jnp.int32))
sem = pl.empty_ref_like(pltpu.SemaphoreType.DMA(()))
@kernel
def _():
pltpu.make_async_copy(y_ref, y_out_ref, sem).start()
@kernel
def _():
pltpu.make_async_copy(y_ref, y_out_ref, sem).wait()
return y_out_ref[...]
np.testing.assert_array_equal(f(), np.arange(8) + 1)
def test_smem_async_copy_megacore(self):
mesh = pltpu.create_tensorcore_mesh('core')
num_cores = len(mesh.devices)
if num_cores == 1:
self.skipTest('Only megacore is supported for this test.')
kernel = pl.core_map(mesh=mesh)
n = 256
@jax.jit
def f():
y_ref = pl.empty_ref_like(pltpu.SMEM((1, n), jnp.int32))
@kernel
def _():
core_i = jax.lax.axis_index('core')
for i in range(n):
y_ref[0, i] = i + core_i * n
@kernel
def _():
for i in range(n):
y_ref[0, i] = y_ref[0, i] + 1
y_out_ref = pl.empty_ref_like(pltpu.HBM((num_cores, 1, n), jnp.int32))
sem = pl.empty_ref_like(pltpu.SemaphoreType.DMA(()))
@kernel
def _():
core_i = jax.lax.axis_index('core')
pltpu.make_async_copy(y_ref, y_out_ref.at[core_i, ...], sem).start()
@kernel
def _():
core_i = jax.lax.axis_index('core')
pltpu.make_async_copy(y_ref, y_out_ref.at[core_i, ...], sem).wait()
return y_out_ref[...]
np.testing.assert_array_equal(
f(), np.arange(num_cores * n).reshape((num_cores, 1, n)) + 1
)
if __name__ == '__main__':
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/pallas/tpu_pallas_memory_space_test.py",
"license": "Apache License 2.0",
"lines": 236,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/pallas/tpu_side_effects_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from absl.testing import absltest
from absl.testing import parameterized
import jax
from jax._src import test_util as jtu
from jax.experimental import pallas as pl
from jax.experimental.pallas import tpu as pltpu
import jax.numpy as jnp
import numpy as np
jax.config.parse_flags_with_absl()
class SideEffectsTest(jtu.JaxTestCase):
def setUp(self):
super().setUp()
if not jtu.is_device_tpu():
self.skipTest("TPU required")
@parameterized.named_parameters(
("pure", pltpu.SideEffectType.PURE),
("side_effecting", pltpu.SideEffectType.SIDE_EFFECTING),
("dataflow_side_effecting", pltpu.SideEffectType.DATAFLOW_SIDE_EFFECTING),
("legacy_true", True),
("legacy_false", False),
)
def test_side_effects_enum(self, side_effect_type):
def kernel(x_ref, o_ref):
pltpu.sync_copy(x_ref, o_ref)
@jax.jit
def f(x):
return pl.pallas_call(
kernel,
out_shape=jax.ShapeDtypeStruct(x.shape, x.dtype),
compiler_params=pltpu.CompilerParams(
has_side_effects=side_effect_type
),
)(x)
x = jnp.ones((8, 128), dtype=jnp.float32)
y = f(x)
np.testing.assert_array_equal(y, x)
def test_invalid_side_effect_type(self):
def kernel(x_ref, o_ref):
o_ref[...] = x_ref[...]
@jax.jit
def f(x):
return pl.pallas_call(
kernel,
out_shape=jax.ShapeDtypeStruct(x.shape, x.dtype),
compiler_params=pltpu.CompilerParams(has_side_effects="invalid"),
)(x)
with self.assertRaisesRegex(ValueError, "Invalid side effect type"):
f(jnp.ones((8, 8), dtype=jnp.float32))
def test_side_effecting_dce(self):
def kernel(x_ref, o_ref):
pltpu.sync_copy(x_ref, o_ref)
def get_compiled_hlo(side_effect_type):
@jax.jit
def f(x):
# We use dce_sink to consume the output but allow DCE if the op is pure/dce-able.
out = pl.pallas_call(
kernel,
out_shape=jax.ShapeDtypeStruct(x.shape, x.dtype),
compiler_params=pltpu.CompilerParams(
has_side_effects=side_effect_type
),
)(x)
jax.lax.dce_sink(out)
return x
lowered = f.lower(jnp.ones((8, 8), dtype=jnp.float32))
shlo = lowered.as_text()
hlo = lowered.compile().as_text()
return shlo, hlo
# PURE kernels should be DCE'd.
shlo_pure, hlo_pure = get_compiled_hlo(pltpu.SideEffectType.PURE)
self.assertIn("custom_call", shlo_pure)
self.assertNotIn("custom-call", hlo_pure)
# SIDE_EFFECTING kernels should NOT be DCE'd.
shlo_side_effecting, hlo_side_effecting = get_compiled_hlo(
pltpu.SideEffectType.SIDE_EFFECTING
)
self.assertIn("custom_call", shlo_side_effecting)
self.assertIn("has_side_effect = true", shlo_side_effecting)
self.assertIn("custom-call", hlo_side_effecting)
self.assertIn("custom_call_has_side_effect=true", hlo_side_effecting)
# DATAFLOW_SIDE_EFFECTING kernels SHOULD be DCE'd if outputs are unused.
shlo_dataflow, hlo_dataflow = get_compiled_hlo(
pltpu.SideEffectType.DATAFLOW_SIDE_EFFECTING
)
self.assertIn("custom_call", shlo_dataflow)
self.assertIn("has_side_effect = true", shlo_dataflow)
self.assertNotIn("custom-call", hlo_dataflow)
if __name__ == "__main__":
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/pallas/tpu_side_effects_test.py",
"license": "Apache License 2.0",
"lines": 102,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/pallas/tpu_sparsecore_pallas_debug_check_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""SparseCore Pallas tests with runtime assertions.
Runtime assertions halt TPU execution, which can cause subsequent tests to get
stuck. Therefore, each test with a failing assertion should run in a separate
process. By separating these tests from the rest, we can set the shard count
such that each test runs in its own shard.
The test class in this file makes an attempt to detect the simple scenario where
there are more test methods in the module than shards.
"""
import functools
import os
import sys
import unittest
from absl.testing import absltest
from absl import flags
import jax
from jax._src import test_util as jtu
from jax.experimental import pallas as pl
from jax.experimental.pallas import tpu as pltpu
from jax.experimental.pallas import tpu_sc as plsc
import jax.numpy as jnp
jax.config.parse_flags_with_absl()
class DebugCheckTest(jtu.JaxTestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
total_shards = int(os.environ.get("TEST_TOTAL_SHARDS", -1))
if total_shards == -1:
raise unittest.SkipTest("Tests can only be run with Bazel.")
loader = unittest.TestLoader()
test_cases = loader.loadTestsFromModule(
sys.modules['__main__']
).countTestCases()
if test_cases > total_shards:
raise RuntimeError(
"Each test with a failing assertion should be in a separate test"
" shard because they put the hardware in a halt state, causing"
" subsequent tests to fail. Make sure sharding is enabled and the"
f" shard count is at least {test_cases}."
)
def setUp(self):
if not jtu.is_device_tpu(5, "p") and not jtu.is_device_tpu_at_least(6):
self.skipTest("SparseCore only supported on TPU v5p+")
super().setUp()
def test_scalar_debug_check(self):
if not jtu.is_device_tpu_at_least(8):
# TODO: b/469486032 - Figure out why the test gets stuck on v5p, v6e, v7.
self.skipTest("Fails on v5p, v6e, and v7.")
x = jnp.arange(8)
@pl.kernel(
out_shape=x,
mesh=plsc.ScalarSubcoreMesh(axis_name="core", num_cores=1),
)
def kernel(o_hbm_ref):
@functools.partial(
pl.run_scoped,
sem=pltpu.SemaphoreType.DMA,
)
def _(sem):
pltpu.async_copy(o_hbm_ref, o_hbm_ref, sem).wait()
pl.debug_check(True, "Check success!")
pl.debug_check(False, "Check failure!")
with pl.enable_debug_checks(), self.assertRaises(
jax.errors.JaxRuntimeError
) as error:
jax.block_until_ready(kernel())
self.assertNotIn("Check success!", str(error.exception))
self.assertIn("Check failure!", str(error.exception))
self.assertIn(
"check at DebugCheckTest.test_scalar_debug_check", str(error.exception)
)
def test_vector_debug_check(self):
x = jnp.arange(8)
@functools.partial(
pl.pallas_call,
out_shape=x,
compiler_params=pltpu.CompilerParams(
kernel_type=pltpu.CoreType.SC_VECTOR_SUBCORE
),
)
def kernel(_):
pl.debug_check(True, "Check success!")
pl.debug_check(False, "Check failure!")
with pl.enable_debug_checks(), self.assertRaises(
jax.errors.JaxRuntimeError
) as error:
jax.block_until_ready(kernel())
# TODO(b/479427406): Remove this once the bug is fixed.
if not (jtu.is_cloud_tpu() and jtu.is_device_tpu_at_least(7)):
self.assertNotIn("Check success!", str(error.exception))
self.assertIn("Check failure!", str(error.exception))
self.assertIn(
"check at DebugCheckTest.test_vector_debug_check",
str(error.exception),
)
def test_trigger_bounds_checker(self):
if "xla_sc_assert_level" in flags.FLAGS:
# The test crashes the process anyway, so no need to be clean.
flags.FLAGS.xla_sc_assert_level = "all-loads-stores"
else:
self.skipTest("TODO: Find another way to enable bounds checking.")
if jtu.is_device_tpu(7, "x"):
self.skipTest("TODO(b/478798643): Fails on v7x")
x = jnp.arange(8, dtype=jnp.int32)
# Index 8 is out-of-bounds.
indices = jnp.array([0, 1, 2, 3, 4, 5, 6, 8], dtype=jnp.int32)
@functools.partial(
pl.pallas_call,
out_shape=x,
compiler_params=pltpu.CompilerParams(
kernel_type=pltpu.CoreType.SC_VECTOR_SUBCORE
),
)
def kernel(x_ref, indices_ref, o_ref):
o_ref[...] = plsc.load_gather(x_ref, [indices_ref[...]])
# We expect this to fail with a runtime error from the bounds checker.
with self.assertRaisesRegex(
jax.errors.JaxRuntimeError,
"Trying to perform an indexed vector load from out of bounds address.",
):
jax.block_until_ready(kernel(x, indices))
if __name__ == "__main__":
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/pallas/tpu_sparsecore_pallas_debug_check_test.py",
"license": "Apache License 2.0",
"lines": 135,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/pallas/tpu_sparsecore_pallas_distributed_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for Pallas on SparseCore with multiple devices."""
import math
from absl.testing import absltest
from absl.testing import parameterized
import jax
from jax import lax
from jax._src import test_util as jtu
from jax.experimental import mesh_utils
from jax.experimental import pallas as pl
from jax.experimental.pallas import tpu as pltpu
from jax.experimental.pallas import tpu_sc as plsc
import jax.numpy as jnp
import numpy as np
jax.config.parse_flags_with_absl()
class PallasCallRemoteDMATest(parameterized.TestCase):
def setUp(self):
super().setUp()
if jax.device_count() < 2:
self.skipTest('Only >=2 devices are supported.')
if not jtu.is_device_tpu_at_least(5):
self.skipTest('SparseCore only supported on TPU v5+')
@parameterized.product(direction=['left', 'right'], num_devices=[2, None])
def test_collective_permute_1d(self, direction, num_devices):
if not jtu.is_cloud_tpu_at_least(2026, 2, 24):
self.skipTest("Requires a newer libTPU")
shape = (8, 128)
# Implements a very simple collective permute.
@pl.kernel(
out_shape=jax.ShapeDtypeStruct(shape, jnp.int32),
mesh=plsc.ScalarSubcoreMesh(axis_name='core', num_cores=1),
scratch_shapes=(
pltpu.SemaphoreType.REGULAR,
pltpu.SemaphoreType.DMA,
pltpu.SemaphoreType.DMA,
),
)
def kernel(x_ref, y_ref, ready_sem, send_sem, recv_sem):
my_id = lax.axis_index('x')
axis_size = lax.axis_size('x')
if direction == 'right':
neighbor = lax.rem(my_id + 1, axis_size)
else:
neighbor = lax.rem(my_id + axis_size - 1, axis_size)
pltpu.semaphore_signal(ready_sem, device_id=neighbor)
pltpu.semaphore_wait(ready_sem)
pltpu.async_remote_copy(
x_ref, y_ref, send_sem, recv_sem, device_id=neighbor
).wait()
num_devices = num_devices or jax.device_count()
x = jnp.arange(num_devices * math.prod(shape), dtype=jnp.int32).reshape(
(-1, shape[-1])
)
device_mesh = mesh_utils.create_device_mesh(
(num_devices,), jax.devices()[:num_devices]
)
mesh = jax.sharding.Mesh(device_mesh, ['x'])
f = jax.jit(
jax.shard_map(
kernel,
mesh=mesh,
in_specs=jax.P('x'),
out_specs=jax.P('x'),
check_vma=False,
)
)
if direction == 'right':
expected = jnp.concatenate([x[-8:], x[:-8]])
else:
expected = jnp.concatenate([x[8:], x[:8]])
np.testing.assert_allclose(f(x), expected)
@parameterized.product(direction=['left', 'right'])
def test_collective_permute_2d(self, direction):
if not jtu.is_cloud_tpu_at_least(2026, 2, 24):
self.skipTest("Requires a newer libTPU")
shape = (8, 128)
@pl.kernel(
out_shape=jax.ShapeDtypeStruct(shape, jnp.int32),
mesh=plsc.ScalarSubcoreMesh(axis_name='core', num_cores=1),
scratch_shapes=(
pltpu.SemaphoreType.REGULAR,
pltpu.SemaphoreType.DMA,
pltpu.SemaphoreType.DMA,
),
)
def kernel(x_ref, y_ref, ready_sem, send_sem, recv_sem):
my_id = lax.axis_index('x')
my_other_id = lax.axis_index('y')
axis_size = lax.axis_size('x')
if direction == 'right':
neighbor = lax.rem(my_id + 1, axis_size)
else:
neighbor = lax.rem(my_id + axis_size - 1, axis_size)
pltpu.semaphore_signal(ready_sem, device_id=(my_other_id, neighbor))
pltpu.semaphore_wait(ready_sem)
pltpu.async_remote_copy(
x_ref, y_ref, send_sem, recv_sem, device_id=(my_other_id, neighbor)
).wait()
axis_size = jax.device_count() // 2
x = jnp.arange(axis_size * 8 * 128).reshape((axis_size * 8, 128))
device_mesh = mesh_utils.create_device_mesh((2, axis_size), jax.devices())
mesh = jax.sharding.Mesh(device_mesh, ['y', 'x'])
y = jax.jit(
jax.shard_map(
kernel,
mesh=mesh,
in_specs=jax.P('x', None),
out_specs=jax.P('x', None),
check_vma=False,
)
)(x)
if direction == 'right':
expected = jnp.concatenate([x[-8:], x[:-8]])
else:
expected = jnp.concatenate([x[8:], x[:8]])
np.testing.assert_allclose(y, expected)
if __name__ == '__main__':
absltest.main()
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/pallas/tpu_sparsecore_pallas_distributed_test.py",
"license": "Apache License 2.0",
"lines": 130,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/pallas/tpu_sparsecore_pallas_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for Pallas on SparseCore."""
import collections
import functools
import itertools
import math
from absl.testing import absltest
from absl.testing import parameterized
import hypothesis as hp
import hypothesis.strategies as hps
import jax
from jax import lax
from jax._src import test_util as jtu
from jax._src.pallas import mpmd
from jax._src.pallas.mosaic import sc_core
from jax._src.state import discharge as state_discharge
from jax.experimental import pallas as pl
from jax.experimental.pallas import tpu as pltpu
from jax.experimental.pallas import tpu_sc as plsc
import jax.numpy as jnp
import numpy as np
jtu.setup_hypothesis()
jax.config.parse_flags_with_absl()
class PallasSCMeshTest(jtu.JaxTestCase):
def setUp(self):
if not jtu.is_device_tpu(5, "p") and not jtu.is_device_tpu_at_least(6):
self.skipTest("SparseCore only supported on TPU v5p+")
super().setUp()
def test_scalar_subcore_mesh(self):
sc_info = plsc.get_sparse_core_info()
mesh = sc_core.ScalarSubcoreMesh(axis_name="x", num_cores=sc_info.num_cores)
self.assertEqual(
mesh.shape, collections.OrderedDict({"x": sc_info.num_cores})
)
self.assertEqual(mesh.dimension_semantics, ["core_parallel"])
self.assertEqual(mesh.default_memory_space, pltpu.MemorySpace.HBM)
def test_vector_subcore_mesh(self):
sc_info = plsc.get_sparse_core_info()
num_cores = sc_info.num_cores
num_subcores = sc_info.num_subcores
mesh = sc_core.VectorSubcoreMesh(
core_axis_name="x", num_cores=num_cores, subcore_axis_name="y"
)
self.assertEqual(
mesh.shape,
collections.OrderedDict({"x": num_cores, "y": num_subcores}),
)
self.assertEqual(
mesh.dimension_semantics, ["core_parallel", "subcore_parallel"]
)
self.assertEqual(mesh.default_memory_space, pltpu.MemorySpace.HBM)
class PallasSCTest(jtu.JaxTestCase):
USE_TC_TILING = False
@property
def num_lanes(self) -> int:
return self.sc_info.num_lanes
def setUp(self):
if not jtu.is_device_tpu(5, "p") and not jtu.is_device_tpu_at_least(6):
self.skipTest("SparseCore only supported on TPU v5p+")
if self.USE_TC_TILING and jtu.is_cloud_tpu():
# TODO(apaszke,slebedev): Fix those.
self.skipTest("Many tests are failing on Cloud TPUs")
super().setUp()
@property
def sc_info(self):
return plsc.get_sparse_core_info()
def vector_subcore_kernel(self, **kwargs):
assert "compiler_params" not in kwargs
return functools.partial(
pl.pallas_call,
**kwargs,
compiler_params=pltpu.CompilerParams(
kernel_type=pltpu.CoreType.SC_VECTOR_SUBCORE,
use_tc_tiling_on_sc=self.USE_TC_TILING,
),
)
def kernel(self, **kwargs):
assert "compiler_params" not in kwargs
return functools.partial(
pl.kernel,
compiler_params=pltpu.CompilerParams(
use_tc_tiling_on_sc=self.USE_TC_TILING
),
**kwargs,
)
def skip_if_tc_tiling(self, reason: str = ""):
if self.USE_TC_TILING:
self.skipTest(f"TC tiling is not supported. {reason}")
class DebugPrintTest(PallasSCTest):
def setUp(self):
if jtu.is_cloud_tpu():
# TODO(slebedev): Investigate this and remove the skip.
self.skipTest("Fails on Cloud TPUs")
super().setUp()
@parameterized.product(dtype=[jnp.int32, jnp.float32])
def test_vector_subcore(self, dtype):
x = jnp.arange(self.num_lanes, dtype=dtype)
debug_int = 1234552
debug_float = 12344.625
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_hbm_ref, _):
pl.debug_print("Memref", x_hbm_ref)
x = x_hbm_ref[...] + 100
pl.debug_print("Vector value", x)
masks = x < 103
pl.debug_print("Masks", masks)
pl.debug_print("Single int", debug_int)
pl.debug_print("Single float", debug_float)
pl.debug_print("No values")
compiled_kernel = jax.jit(
kernel,
compiler_options={
"xla_tpu_enable_sc_log_recorder": "true",
"xla_tpu_enable_tile_log_recorder": "true",
},
)
with jtu.capture_stderr() as get_output:
jax.block_until_ready(compiled_kernel(x))
self.assertIn("Memref", get_output())
self.assertIn(", ".join(map(str, range(self.num_lanes))), get_output())
self.assertIn("Vector value", get_output())
self.assertIn(
", ".join(map(str, range(100, 100 + self.num_lanes))), get_output()
)
self.assertIn("Masks", get_output())
masks = [1] * 3 + [0] * (self.num_lanes - 3)
self.assertIn(", ".join(map(str, masks)), get_output())
self.assertIn("Single int, data: s32[1]", get_output())
self.assertIn(str(debug_int), get_output())
self.assertIn("Single float, data: f32[1]", get_output())
self.assertIn(str(debug_float), get_output())
self.assertIn("No values", get_output())
def test_scalar_subcore(self):
nl = self.num_lanes
int32s = jnp.arange(512, dtype=jnp.int32).reshape(-1, nl)
int16s = jnp.arange(512, dtype=jnp.int16).reshape(-1, 2 * nl)
int8s = jnp.arange(512, dtype=jnp.int8).reshape(-1, 4 * nl)
debug_int = 1234552
debug_float = 12344.625
@self.kernel(
out_shape=int32s,
mesh=plsc.ScalarSubcoreMesh(
axis_name="x", num_cores=self.sc_info.num_cores
),
)
def kernel(int32s_hbm_ref, int16s_hbm_ref, int8s_hbm_ref, o_hbm_ref):
@functools.partial(
pl.run_scoped,
tmp_ref=pltpu.VMEM_SHARED(int32s.shape, int32s.dtype),
sem=pltpu.SemaphoreType.DMA,
)
def _(tmp_ref, sem):
@pl.when(lax.axis_index("x") == 0)
def _():
pltpu.async_copy(int32s_hbm_ref, tmp_ref, sem).wait()
pltpu.async_copy(tmp_ref, o_hbm_ref, sem).wait()
pl.debug_print("s32 array", tmp_ref)
pl.debug_print("s16 array", int16s_hbm_ref)
pl.debug_print("s8 array", int8s_hbm_ref)
pl.debug_print("Single int", debug_int)
pl.debug_print("Single float", debug_float)
pl.debug_print("No values")
compiled_kernel = jax.jit(
kernel,
compiler_options={
"xla_tpu_enable_sc_log_recorder": "true",
# TODO(slebedev): This should not be necessary.
"xla_sc_force_aligned_buffers": "false",
},
)
with jtu.capture_stderr() as get_output:
jax.block_until_ready(compiled_kernel(int32s, int16s, int8s))
self.assertIn("s32 array, data: s32", get_output())
self.assertIn(
"{ " + ", ".join(map(str, range(nl, 2 * nl))) + " }", get_output()
)
self.assertIn("s16 array, data: s16", get_output())
self.assertIn(
"{ " + ", ".join(map(str, range(2 * nl, 4 * nl))) + " }", get_output()
)
self.assertIn("s8 array, data: s8", get_output())
self.assertIn(
"{ " + ", ".join(map(str, range(4 * nl, 8 * nl))) + " }", get_output()
)
self.assertIn("Single int", get_output())
self.assertIn(str(debug_int), get_output())
self.assertIn("Single float", get_output())
self.assertIn(str(debug_float), get_output())
self.assertIn("No values", get_output())
class VectorSubcoreTest(PallasSCTest):
# Used for testing masked loads and stores below
MASK_FNS = [lambda x: x < 4, lambda x: x >= 4, lambda x: x % 2 == 0]
@parameterized.product(
dtype=[jnp.int32, jnp.float32], op=[jnp.add, jnp.subtract]
)
def test_add_sub_one(self, dtype, op):
x = jnp.arange(self.num_lanes, dtype=dtype)
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, o_ref):
x = x_ref[...]
o_ref[...] = op(x, 1)
np.testing.assert_array_equal(kernel(x), op(x, 1))
def test_add_one_block_specs(self):
# TODO(b/488280666): Remove this once the bug is fixed.
self.skip_if_tc_tiling("The test is flaky with TC tiling")
num_steps = 4
x = jnp.arange(num_steps * self.num_lanes, dtype=jnp.int32)
@self.vector_subcore_kernel(
out_shape=x,
grid=(num_steps,),
out_specs=pl.BlockSpec([self.num_lanes], lambda i: i),
in_specs=[pl.BlockSpec([self.num_lanes], lambda i: i)],
)
def kernel(x_ref, o_ref):
o_ref[...] = x_ref[...] + 1
np.testing.assert_array_equal(kernel(x), x + 1)
@parameterized.product(
dtype=[
# fmt: off
"int32", "uint32", "float32", "int16", "uint16", "float16",
"bfloat16", "int8", "uint8"
# fmt: on
]
)
@jtu.thread_unsafe_test(condition=not jtu.hypothesis_is_thread_safe())
@hp.given(hps.data())
# TODO(b/478865387): Remove the skip once the bug is fixed.
@absltest.skip("Needs vector unrolling pass")
def test_slicing(self, dtype, data):
self.skip_if_tc_tiling()
if dtype == "float16":
# TODO(b/433704850): Remove this once the bug is fixed.
self.skipTest("Crashes in the backend")
out_shape = data.draw(
hps.sampled_from(sc_core.supported_shapes(dtype)), label="out_shape"
)
minor_scale = data.draw(hps.sampled_from([1, 2, 4]), label="minor_scale")
out_minor = out_shape[-1]
in_minor = out_minor * minor_scale
in_shape = (*out_shape[:-1], in_minor)
indices = [
slice(i * out_minor, (i + 1) * out_minor) for i in range(minor_scale)
]
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct(shape=out_shape, dtype=dtype),
)
def kernel(x_ref, o_ref):
o_ref[...] = sum(x_ref[..., idx] for idx in indices)
x = jnp.arange(math.prod(in_shape), dtype=dtype).reshape(in_shape)
np.testing.assert_array_equal(
kernel(x), sum(x[..., idx] for idx in indices)
)
@parameterized.product(major_dim=[2, 3, 4])
def test_get_index(self, major_dim):
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct(shape=(self.num_lanes,), dtype=jnp.int32),
)
def kernel(x_ref, o_ref):
o_ref[...] = lax.fori_loop(
1, major_dim, lambda i, acc: acc + x_ref[i], x_ref[0]
)
x = jnp.arange(self.num_lanes * major_dim).reshape(major_dim, self.num_lanes)
np.testing.assert_array_equal(kernel(x), x.sum(axis=0))
def test_get_multi_index(self):
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct(shape=(self.num_lanes,), dtype=jnp.int32)
)
def kernel(x_ref, o_ref):
o_ref[...] = jnp.zeros_like(o_ref)
for i, j in itertools.product(*map(range, x_ref.shape[:-1])):
o_ref[...] += x_ref.at[i][j]
x = jnp.arange(3 * 4 * self.num_lanes).reshape(3, 4, self.num_lanes)
np.testing.assert_array_equal(kernel(x), x.sum(axis=(0, 1)))
@jtu.thread_unsafe_test(condition=not jtu.hypothesis_is_thread_safe())
@hp.given(hps.data())
def test_block_spec_untiled_slicing(self, data):
self.skipTest(
"Test uncovers a bug: @reproduce_failure('6.80.0', b'AAEBAQAAAAA=')"
)
slice_shape = data.draw(
hps.lists(
hps.integers(1, 3), min_size=(1 + self.USE_TC_TILING), max_size=4
)
)
if self.USE_TC_TILING:
slice_shape[-2] *= self.num_lanes
slice_shape[-1] *= 128
else:
slice_shape[-1] *= self.num_lanes
max_elems = 12000 if jtu.is_device_tpu(6, "e") else 25000
hp.assume(math.prod(slice_shape) <= max_elems) # Avoid OOMs.
rank = len(slice_shape)
offsets = data.draw(
hps.lists(hps.integers(0, 4), min_size=rank, max_size=rank)
)
full_shape = tuple(s * (o + 2) for s, o in zip(slice_shape, offsets))
def nd_loop(bounds, body, *, _idxs = ()):
if not bounds:
body(*_idxs)
return
bound, *other_bounds = bounds
def _loop_body(i, _):
nd_loop(other_bounds, body, _idxs=(*_idxs, i))
jax.lax.fori_loop(0, bound, _loop_body, None)
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct(shape=slice_shape, dtype=jnp.int32),
in_specs=[pl.BlockSpec(slice_shape, lambda: offsets)],
)
def kernel(x_ref, o_ref):
slice_vec_shape = (
*slice_shape[:-1],
slice_shape[-1] // self.num_lanes,
)
def copy(*idxs):
idxs = (*idxs[:-1], pl.ds(idxs[-1] * self.num_lanes, self.num_lanes))
o_ref[idxs] = x_ref[idxs]
nd_loop(slice_vec_shape, copy)
x = jnp.arange(math.prod(full_shape)).reshape(full_shape)
np_slc = tuple(slice(o * s, (o + 1) * s) for o, s in zip(offsets, slice_shape))
np.testing.assert_array_equal(kernel(x), x[np_slc])
@parameterized.product(major_dim=[2, 3, 4])
def test_swap_index(self, major_dim):
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct(
shape=(major_dim, self.num_lanes), dtype=jnp.int32
),
)
def kernel(x_ref, o_ref):
@pl.loop(0, major_dim)
def _(i):
o_ref[major_dim - 1 - i] = x_ref[i]
x = jnp.arange(major_dim * self.num_lanes).reshape(major_dim, self.num_lanes)
np.testing.assert_array_equal(kernel(x), x[::-1])
@parameterized.product(
shape_type=["vector", "2vector", "matrix", "2matrix", "3d"]
)
def test_scatter_major(self, shape_type):
nl = self.num_lanes
shape = {
"vector": (nl,),
"2vector": (2 * nl,),
"matrix": (nl, nl),
"2matrix": (2 * nl, nl),
"3d": (nl, 2 * nl, nl),
}[shape_type]
self.skip_if_tc_tiling()
x = jnp.arange(math.prod(shape)).reshape(shape)
major_dim, *_ = shape
indices = jax.random.permutation(jax.random.key(42), jnp.arange(major_dim))
@self.vector_subcore_kernel(
out_shape=x, out_specs=pl.BlockSpec(memory_space=pltpu.HBM)
)
def kernel(x_ref, indices_ref, o_hbm_ref):
@functools.partial(pl.run_scoped, sem=pltpu.SemaphoreType.DMA)
def _(sem):
pltpu.async_copy(x_ref, o_hbm_ref.at[indices_ref], sem).wait()
np.testing.assert_array_equal(
kernel(x, indices), jnp.empty_like(x).at[indices].set(x)
)
def test_scatter_1d_array(self):
x = jnp.arange(self.num_lanes)
indices = jax.random.permutation(jax.random.key(42), jnp.arange(self.num_lanes))
@self.vector_subcore_kernel(
out_shape=x, out_specs=pl.BlockSpec(memory_space=pltpu.HBM)
)
def kernel(x_ref, indices_ref, o_hbm_ref):
pltpu.sync_copy(x_ref, o_hbm_ref.at[indices_ref[...]])
np.testing.assert_array_equal(
kernel(x, indices), jnp.empty_like(x).at[indices].set(x)
)
def test_scatter_1d_array_from_transformed_src(self):
self.skip_if_tc_tiling()
x = jnp.arange(2 * self.num_lanes).reshape(2, -1)
indices = jax.random.permutation(jax.random.key(42), jnp.arange(self.num_lanes))
@self.vector_subcore_kernel(
out_shape=x[0], out_specs=pl.BlockSpec(memory_space=pltpu.HBM),
)
def kernel(x_ref, indices_ref, o_hbm_ref):
pltpu.sync_copy(x_ref.at[0], o_hbm_ref.at[indices_ref[...]])
np.testing.assert_array_equal(
kernel(x, indices), jnp.empty_like(x[0]).at[indices].set(x[0])
)
@parameterized.product(kind=["ref", "array"])
def test_gather_1d(self, kind):
x = jnp.arange(self.num_lanes)
indices = jax.random.permutation(jax.random.key(42), x)
@self.vector_subcore_kernel(
out_shape=x,
in_specs=(
pl.BlockSpec(memory_space=pltpu.HBM),
pl.BlockSpec(memory_space=pltpu.VMEM),
),
)
def kernel(x_hbm_ref, indices_ref, o_ref):
indices = indices_ref if kind == "ref" else indices_ref[...]
pltpu.sync_copy(x_hbm_ref.at[indices], o_ref)
np.testing.assert_array_equal(kernel(x, indices), x[indices])
@parameterized.product(kind=["ref", "array"])
def test_gather_1d_to_transformed_dst(self, kind):
self.skip_if_tc_tiling()
x = jnp.arange(self.num_lanes)
indices = jax.random.permutation(jax.random.key(42), x)
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct(
shape=(2, self.num_lanes), dtype=jnp.int32
),
in_specs=(
pl.BlockSpec(memory_space=pltpu.HBM),
pl.BlockSpec(memory_space=pltpu.VMEM),
),
)
def kernel(x_hbm_ref, indices_ref, o_ref):
indices = indices_ref if kind == "ref" else indices_ref[...]
pltpu.sync_copy(x_hbm_ref.at[indices], o_ref.at[0])
np.testing.assert_array_equal(kernel(x, indices)[0], x[indices])
def test_large_gather_1d(self):
x = jnp.arange(1024)
indices = jax.random.permutation(jax.random.key(42), x)
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct(shape=[1, *x.shape], dtype=x.dtype),
in_specs=(
pl.BlockSpec(memory_space=pltpu.HBM),
pl.BlockSpec(memory_space=pltpu.VMEM),
),
)
def kernel(x_hbm_ref, indices_ref, o_ref):
pltpu.sync_copy(x_hbm_ref.at[indices_ref], o_ref)
# We have to expand the arrays to 2D to ensure that the pipeline stage
# dimension does not get tiled when using TC tiling.
# TODO(b/488280660): Remove this once the bug is fixed.
result = jnp.squeeze(
kernel(jnp.expand_dims(x, 0), jnp.expand_dims(indices, 0))
)
np.testing.assert_array_equal(result, x[indices])
def test_gather_1d_with_indexing(self):
self.skip_if_tc_tiling("Small 1d gather does not work on TC tiling.")
x = jnp.arange(4 * 4 * self.num_lanes).reshape(4, 4, self.num_lanes)
indices = jax.random.permutation(
jax.random.key(42), jnp.arange(self.num_lanes)
)
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct(shape=(self.num_lanes,), dtype=jnp.int32),
in_specs=(
pl.BlockSpec(memory_space=pltpu.HBM),
pl.BlockSpec(memory_space=pltpu.VMEM),
),
)
def kernel(x_hbm_ref, indices_ref, o_ref):
pltpu.sync_copy(x_hbm_ref.at[1, 2].at[indices_ref], o_ref)
np.testing.assert_array_equal(kernel(x, indices), x[1, 2, indices])
def test_gather_2d_with_indexing(self):
x = jnp.arange(4 * 16 * 128).reshape(4, 16, 128)
indices = jax.random.permutation(jax.random.key(42), jnp.arange(8))
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct(shape=(8, 128,), dtype=jnp.int32),
in_specs=(
pl.BlockSpec(memory_space=pltpu.HBM),
pl.BlockSpec(memory_space=pltpu.VMEM),
),
)
def kernel(x_hbm_ref, indices_ref, o_ref):
pltpu.sync_copy(x_hbm_ref.at[1, pl.ds(8, 8), :].at[indices_ref], o_ref)
np.testing.assert_array_equal(kernel(x, indices), x[1, 8:][indices])
def test_gather_1d_with_indexed_ref(self):
x = jnp.arange(16)
indices = jax.random.permutation(jax.random.key(42), jnp.arange(16))
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct(shape=(8,), dtype=jnp.int32),
in_specs=(
pl.BlockSpec(memory_space=pltpu.HBM),
pl.BlockSpec(memory_space=pltpu.VMEM),
),
)
def kernel(x_hbm_ref, indices_ref, o_ref):
pltpu.sync_copy(x_hbm_ref.at[indices_ref.at[:indices.size // 2]], o_ref)
np.testing.assert_array_equal(
kernel(x, indices), x[indices[:indices.size // 2]]
)
def test_gather_1d_with_dynamically_sized_ref(self):
self.skip_if_tc_tiling()
x = jnp.arange(16)
indices = jax.random.permutation(jax.random.key(42), jnp.arange(16))
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct(shape=(8,), dtype=jnp.int32),
grid=(1,),
in_specs=(
pl.BlockSpec(memory_space=pltpu.HBM),
pl.BlockSpec(memory_space=pltpu.VMEM),
),
)
def kernel(x_hbm_ref, indices_ref, o_ref):
pid = pl.program_id(0) # Always zero.
num_indices = pid + indices_ref.size // 2
pltpu.sync_copy(
x_hbm_ref.at[indices_ref.at[pl.ds(0, num_indices)]],
o_ref.at[pl.ds(0, num_indices)],
)
np.testing.assert_array_equal(
kernel(x, indices), x[indices[: indices.size // 2]]
)
def test_gather_1d_with_dynamically_sized_2d_ref(self):
if not jtu.is_cloud_tpu_at_least(2026, 3, 1):
self.skipTest("Requires a newer libtpu")
self.skip_if_tc_tiling()
x = jnp.arange(16)
indices = jax.random.permutation(
jax.random.key(42), jnp.arange(2 * 16).reshape(2, -1), axis=1
)
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct(
shape=(indices.size // 4,), dtype=jnp.int32
),
grid=(1,),
in_specs=(
pl.BlockSpec(memory_space=pltpu.HBM),
pl.BlockSpec(memory_space=pltpu.VMEM),
),
)
def kernel(x_hbm_ref, indices_ref, o_ref):
pid = pl.program_id(0) # Always zero.
num_indices = pid + indices_ref.size // 4
pltpu.sync_copy(
x_hbm_ref.at[indices_ref.at[pid, pl.ds(0, num_indices)]],
o_ref.at[pl.ds(0, num_indices)],
)
np.testing.assert_array_equal(
kernel(x, indices), x[indices[0, : indices.size // 4]]
)
def test_invalid_gather_1d_with_extra_transforms(self):
x = jnp.arange(8)
indices = jax.random.permutation(jax.random.key(42), x)
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct(shape=x.shape, dtype=jnp.int32),
in_specs=(
pl.BlockSpec(memory_space=pltpu.HBM),
pl.BlockSpec(memory_space=pltpu.VMEM),
),
)
def kernel(x_hbm_ref, indices_ref, o_ref):
pltpu.sync_copy(x_hbm_ref.at[indices_ref].reshape(o_ref.size), o_ref)
with self.assertRaisesRegex(
NotImplementedError, "cannot have any transforms following the indexer"
):
kernel(x, indices)
def test_invalid_gather_1d_with_indexed_destination(self):
x = jnp.arange(8)
indices = jax.random.permutation(jax.random.key(42), x)
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct(shape=x.shape, dtype=jnp.int32),
in_specs=(
pl.BlockSpec(memory_space=pltpu.HBM),
pl.BlockSpec(memory_space=pltpu.VMEM),
),
)
def kernel(x_hbm_ref, indices_ref, o_ref):
pltpu.sync_copy(x_hbm_ref.at[indices_ref], o_ref.at[indices_ref])
with self.assertRaisesRegex(ValueError, "source ref can be indexed"):
kernel(x, indices)
def test_invalid_gather_1d_memory_space(self):
x = jnp.arange(8)
indices = jax.random.permutation(jax.random.key(42), x)
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct(shape=x.shape, dtype=jnp.int32),
in_specs=(
pl.BlockSpec(memory_space=pltpu.HBM),
pl.BlockSpec(memory_space=pltpu.VMEM),
),
out_specs=pl.BlockSpec(memory_space=pltpu.HBM),
)
def kernel(x_hbm_ref, indices_ref, o_ref):
pltpu.sync_copy(x_hbm_ref.at[indices_ref], o_ref)
with self.assertRaisesRegex(
NotImplementedError, "from HBM to HBM is not supported"
):
kernel(x, indices)
def test_invalid_gather_1d_offsets_memory_space(self):
x = jnp.arange(8)
indices = jax.random.permutation(jax.random.key(42), x)
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct(shape=x.shape, dtype=jnp.int32),
in_specs=(
pl.BlockSpec(memory_space=pltpu.HBM),
pl.BlockSpec(memory_space=pltpu.HBM),
),
)
def kernel(x_hbm_ref, indices_ref, o_ref):
pltpu.sync_copy(x_hbm_ref.at[indices_ref], o_ref)
with self.assertRaisesRegex(NotImplementedError, "must be in VMEM, got HBM"):
kernel(x, indices)
def test_implicit_gather_1d(self):
self.skip_if_tc_tiling()
num_steps = 4
x = jnp.arange(num_steps * self.num_lanes).reshape(num_steps, self.num_lanes)
indices = jax.random.permutation(jax.random.key(42), jnp.arange(num_steps))
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct(
shape=(num_steps, self.num_lanes), dtype=jnp.int32
),
grid=(num_steps,),
in_specs=(
plsc.BlockSpec(
(pl.Squeezed(), self.num_lanes), indexed_by=1, indexed_dim=0
),
pl.BlockSpec((1,), lambda i: i),
),
out_specs=pl.BlockSpec(
(pl.Squeezed(), self.num_lanes), lambda i: (0, i)
),
)
def kernel(x_ref, indices_ref, o_ref):
del indices_ref # Unused.
o_ref[...] = x_ref[...]
np.testing.assert_array_equal(
kernel(x, indices), jnp.take(x, indices, axis=0)
)
def test_load_gather_1d(self):
x = jnp.arange(self.num_lanes)
indices = jax.random.permutation(
jax.random.key(42), jnp.arange(self.num_lanes)
)
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, indices_ref, o_ref):
o_ref[...] = plsc.load_gather(x_ref, [indices_ref[...]])
np.testing.assert_array_equal(kernel(x, indices), x[indices])
def test_load_gather_2d(self):
x = jnp.arange(self.num_lanes * self.num_lanes).reshape(self.num_lanes, -1)
indices0 = indices1 = jax.random.permutation(
jax.random.key(42), jnp.arange(self.num_lanes)
)
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct((self.num_lanes,), x.dtype)
)
def kernel(x_ref, indices0_ref, indices1_ref, o_ref):
o_ref[...] = plsc.load_gather(
x_ref, [indices0_ref[...], indices1_ref[...]]
)
np.testing.assert_array_equal(
kernel(x, indices0, indices1), x[indices0, indices1]
)
def test_load_gather_with_indexing(self):
self.skip_if_tc_tiling()
num_steps = 4
x = jnp.arange(num_steps * self.num_lanes).reshape(num_steps, self.num_lanes)
indices = jax.random.permutation(
jax.random.key(42), jnp.arange(self.num_lanes)
)
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, indices_ref, o_ref):
indices = indices_ref[...]
for i in range(num_steps):
o_ref[i] = plsc.load_gather(x_ref.at[i], [indices])
out = kernel(x, indices)
for i in range(num_steps):
np.testing.assert_array_equal(out[i], x[i][indices])
@parameterized.parameters(*MASK_FNS)
def test_load_gather_masked(self, mask_fn):
x = jnp.arange(self.num_lanes)
indices = jax.random.permutation(
jax.random.key(42), jnp.arange(self.num_lanes)
)
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, indices_ref, o_ref):
o_ref[...] = plsc.load_gather(
x_ref, [indices_ref[...]], mask=mask_fn(x_ref[...])
)
mask = mask_fn(x)
np.testing.assert_array_equal(kernel(x, indices)[mask], x[indices][mask])
def test_store_scatter(self):
self.skip_if_tc_tiling()
x = jnp.arange(self.num_lanes)
indices = jax.random.permutation(
jax.random.key(42), jnp.arange(self.num_lanes)
)
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, indices_ref, o_ref):
plsc.store_scatter(o_ref, [indices_ref[...]], x_ref[...])
np.testing.assert_array_equal(
kernel(x, indices), jnp.zeros_like(x).at[indices].set(x)
)
@parameterized.parameters(*MASK_FNS)
def test_store_scatter_masked(self, mask_fn):
x = jnp.arange(self.num_lanes)
indices = jax.random.permutation(
jax.random.key(42), jnp.arange(self.num_lanes)
)
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, indices_ref, o_ref):
x = x_ref[...]
o_ref[...] = jnp.zeros_like(o_ref)
plsc.store_scatter(o_ref, [indices_ref[...]], x, mask=mask_fn(x))
mask = mask_fn(x)
np.testing.assert_array_equal(
kernel(x, indices),
jnp.zeros_like(x).at[indices[mask]].set(x[mask]),
)
def test_store_scatter_2d(self):
num_steps = 4
x = jnp.arange(num_steps * self.num_lanes).reshape(num_steps, self.num_lanes)
indices = jax.random.permutation(
jax.random.key(42), jnp.arange(self.num_lanes)
)
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, indices_ref, o_ref):
indices = indices_ref[...]
for i in range(num_steps):
plsc.store_scatter(
o_ref, [jnp.full(indices.shape, i), indices], x_ref[i])
out = kernel(x, indices)
for i in range(num_steps):
np.testing.assert_array_equal(
out[i], jnp.zeros_like(x[i]).at[indices].set(x[i])
)
@parameterized.parameters(*MASK_FNS)
def test_addupdate_scatter(self, mask_fn):
self.skip_if_tc_tiling()
x = jnp.arange(self.num_lanes)
indices = jax.random.permutation(
jax.random.key(42), jnp.arange(self.num_lanes)
)
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, indices_ref, o_ref):
x = x_ref[...]
o_ref[...] = jnp.ones_like(o_ref)
plsc.addupdate_scatter(o_ref, [indices_ref[...]], x, mask=mask_fn(x))
mask = mask_fn(x)
np.testing.assert_array_equal(
kernel(x, indices),
jnp.ones_like(x).at[indices[mask]].add(x[mask]),
)
@parameterized.parameters(*MASK_FNS)
def test_load_expanded(self, mask_fn):
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct(shape=(self.num_lanes,), dtype=jnp.int32)
)
def kernel(x_ref, o_ref):
o_ref[...] = plsc.load_expanded(x_ref.at[...], mask=mask_fn(x_ref[...]))
x = jnp.arange(self.num_lanes)
mask = mask_fn(x)
expected = jnp.zeros_like(x).at[mask].set(x[: mask.sum()])
np.testing.assert_array_equal(kernel(x)[mask], expected[mask])
@parameterized.parameters(*MASK_FNS)
def test_store_compressed(self, mask_fn):
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct(shape=(self.num_lanes,), dtype=jnp.int32)
)
def kernel(x_ref, o_ref):
x = x_ref[...]
plsc.store_compressed(o_ref.at[...], x, mask=mask_fn(x))
x = jnp.arange(self.num_lanes)
mask = mask_fn(x)
np.testing.assert_array_equal(kernel(x)[: mask.sum()], x[mask])
def test_addupdate(self):
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct(
shape=(self.num_lanes,), dtype=jnp.int32
)
)
def kernel(o_ref):
o_ref[...] = jnp.zeros_like(o_ref)
for i in range(self.num_lanes):
plsc.addupdate(o_ref.at[...], lax.broadcast(i, o_ref.shape))
np.testing.assert_array_equal(
kernel(),
jnp.full(self.num_lanes, jnp.arange(self.num_lanes).sum()),
)
@parameterized.parameters(*MASK_FNS)
def test_addupdate_compressed(self, mask_fn):
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct(
shape=(self.num_lanes,), dtype=jnp.int32
)
)
def kernel(x_ref, o_ref):
o_ref[...] = jnp.zeros_like(o_ref)
for i in range(self.num_lanes):
plsc.addupdate_compressed(
o_ref.at[...],
lax.broadcast(i, o_ref.shape),
mask=mask_fn(x_ref[...]),
)
x = jnp.arange(self.num_lanes)
mask = mask_fn(x)
np.testing.assert_array_equal(
kernel(x)[: mask.sum()],
jnp.full(mask.sum(), jnp.arange(self.num_lanes).sum()),
)
@parameterized.product(
dtype=[jnp.int32], new_dtype=[jnp.int8, jnp.int16, jnp.float32]
)
def test_bitcast(self, dtype, new_dtype):
self.skip_if_tc_tiling()
new_shape = (
self.num_lanes * jnp.dtype(dtype).itemsize // jnp.dtype(new_dtype).itemsize,
)
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct(shape=new_shape, dtype=new_dtype)
)
def kernel(x_ref, o_ref):
o_ref[...] = plsc.bitcast(x_ref[...], o_ref.dtype)
x = jnp.arange(self.num_lanes, dtype=dtype)
np.testing.assert_array_equal(kernel(x), x.view(new_dtype))
def test_lax_bitcast(self):
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct((self.num_lanes,), jnp.uint32),
)
def kernel(x_ref, o_ref):
o_ref[...] = x_ref[...].view(o_ref.dtype)
x = jnp.arange(self.num_lanes, dtype=jnp.float32)
np.testing.assert_array_equal(kernel(x), x.view(np.uint32))
def test_ref_bitcast(self):
# TODO: b/443906446 - Remove the skip once we can lower such bitcasts.
self.skipTest("Ref bitcast is not supported yet")
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct((self.num_lanes,), jnp.uint32),
)
def kernel(x_ref, o_ref):
o_ref[...] = x_ref.bitcast(o_ref.dtype)[...]
x = jnp.arange(self.num_lanes, dtype=jnp.float32)
np.testing.assert_array_equal(kernel(x), x.view(np.uint32))
@parameterized.product(
pack_format=[*plsc.PackFormat],
dtype=[jnp.float32, jnp.int32],
)
def test_pack_unpack(self, pack_format, dtype):
shape = (self.num_lanes,)
@self.vector_subcore_kernel(
out_shape=(jax.ShapeDtypeStruct((self.num_lanes,), dtype),) * 2
)
def kernel(a_ref, b_ref, oa_ref, ob_ref):
ab = plsc.pack(a_ref[...], b_ref[...], format=pack_format)
oa_ref[...], ob_ref[...] = plsc.unpack(ab, format=pack_format)
a = jnp.arange(math.prod(shape), dtype=dtype).reshape(shape)
b = -a
out_a, out_b = kernel(a, b)
np.testing.assert_array_equal(out_a, a)
np.testing.assert_array_equal(out_b, b)
@parameterized.parameters(jnp.int32, jnp.float32)
def test_scan_count(self, dtype):
shape = [self.num_lanes]
@self.vector_subcore_kernel(
out_shape=(
jax.ShapeDtypeStruct(shape, jnp.int32),
jax.ShapeDtypeStruct(shape, jnp.int32),
),
)
def kernel(x_ref, counts_ref, mask_ref):
counts_ref[...], mask = plsc.scan_count(x_ref[...])
mask_ref[...] = mask.astype(jnp.int32)
key = jax.random.key(42)
x = jax.random.randint(key, shape, 0, 10, dtype=jnp.int32).astype(dtype)
counts, mask = kernel(x)
expected_counts = []
expected_mask = []
c = collections.Counter()
for item in x:
item = int(item)
c[item] += 1
expected_counts.append(c[item])
for item in x:
item = int(item)
c[item] -= 1
expected_mask.append(c[item] == 0)
np.testing.assert_array_equal(counts, expected_counts)
np.testing.assert_array_equal(mask, expected_mask)
def test_population_count(self):
key = jax.random.key(42)
x = jax.random.randint(key, [self.num_lanes], 0, 100)
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, o_ref):
mask = x_ref[...] < 50
# TODO: b/434208146 - Test with reduce!=1 when we support v6e packed masks
o_ref[...] = plsc.all_reduce_population_count(mask)
np.testing.assert_array_equal(
kernel(x), np.broadcast_to(np.count_nonzero(x < 50), x.shape)
)
def test_iota(self):
key = jax.random.key(42)
x = jax.random.randint(key, [self.num_lanes], 0, 100)
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, o_ref):
o_ref[...] = jnp.arange(self.num_lanes) + x_ref[...]
np.testing.assert_array_equal(kernel(x), x + np.arange(self.num_lanes))
def test_write_to_transformed_ref(self):
if not jtu.is_cloud_tpu_at_least(2026, 3, 1):
self.skipTest("Requires a newer libTPU")
x = jnp.arange(2 * self.num_lanes)
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, o_ref):
plsc.store_compressed(
o_ref.at[pl.ds(5, self.num_lanes)],
x_ref[pl.ds(2, self.num_lanes)],
mask=jnp.ones(self.num_lanes, jnp.bool),
)
np.testing.assert_array_equal(
kernel(x)[5 : 5 + self.num_lanes], x[2 : 2 + self.num_lanes]
)
def test_load_transformed_ref(self):
x = jnp.arange(2 * self.num_lanes)
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, o_ref):
o_ref[pl.ds(5, self.num_lanes)] = plsc.load_expanded(
x_ref.at[pl.ds(2, self.num_lanes)],
mask=jnp.arange(self.num_lanes) % 2 == 0,
)
np.testing.assert_array_equal(
kernel(x)[5 : 5 + self.num_lanes : 2], x[2 : 2 + self.num_lanes // 2]
)
def test_scalar_load_store(self):
@self.vector_subcore_kernel(
in_specs=(pl.BlockSpec(memory_space=pltpu.HBM),),
out_specs=pl.BlockSpec(memory_space=pltpu.VMEM),
out_shape=jax.ShapeDtypeStruct((self.num_lanes,), jnp.int32),
scratch_shapes=(pltpu.VMEM((1,), jnp.int32),),
)
def kernel(x_ref, o_ref, tmp_ref):
pltpu.sync_copy(x_ref, tmp_ref)
o_ref[...] = lax.broadcast(tmp_ref[0], o_ref.shape)
np.testing.assert_array_equal(
kernel(jnp.ones((1,), jnp.int32)), jnp.ones((self.num_lanes,), jnp.int32)
)
def test_scalar_load_hbm(self):
@self.vector_subcore_kernel(
in_specs=(pl.BlockSpec(memory_space=pltpu.HBM),),
out_specs=pl.BlockSpec(memory_space=pltpu.VMEM),
out_shape=jax.ShapeDtypeStruct((self.num_lanes,), jnp.int32),
)
def kernel(x_ref, o_ref):
o_ref[...] = lax.broadcast(x_ref[0], o_ref.shape)
with self.assertRaisesRegex(
NotImplementedError, "Get does not support loading from HBM"
):
_ = kernel(jnp.ones((1,), jnp.int32))
@parameterized.parameters("mixed", "all_zero", "all_one")
def test_ffs(self, case):
nl = self.num_lanes
if case == "mixed":
data = [0, 0, 1] + [0] * (nl - 3)
expected = 2
elif case == "all_zero":
data = [0] * nl
expected = nl
elif case == "all_one":
data = [1] * nl
expected = 0
else:
raise NotImplementedError("Unsupported case")
x = jnp.array(data)
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, o_ref):
mask = x_ref[...] == 1
# TODO: b/434208146 - Test with reduce!=1 when we support v6e packed masks
o_ref[...] = plsc.all_reduce_ffs(mask)
np.testing.assert_array_equal(kernel(x), np.broadcast_to(expected, x.shape))
def test_fetch_and_add(self):
if not jtu.is_cloud_tpu_at_least(2026, 2, 24):
self.skipTest("Requires a newer libTPU")
n = self.sc_info.num_subcores
dim = self.num_lanes
@functools.partial(
pl.pallas_call,
compiler_params=pltpu.CompilerParams(
kernel_type=pltpu.CoreType.SC_VECTOR_SUBCORE,
dimension_semantics=["subcore_parallel"],
),
out_shape=(
jax.ShapeDtypeStruct((n * dim,), jnp.int32),
jax.ShapeDtypeStruct((n * dim,), jnp.int32),
),
grid=(n,),
out_specs=(
pl.BlockSpec([dim], lambda i: (i,)),
pl.BlockSpec([dim], lambda i: (i,)),
),
scratch_shapes=(pltpu.SMEM([1], jnp.int32),),
)
def kernel(old_val_ref, new_val_ref, smem_ref):
my_id = pl.program_id(0)
smem_ref[0] = my_id
plsc.subcore_barrier()
neighbor_id = (my_id + 1) % n
old_val = plsc.fetch_and_add(
smem_ref.at[0], 10, subcore_id=neighbor_id
)
plsc.subcore_barrier()
new_val = smem_ref[0]
old_val_ref[...] = jax.lax.broadcast(old_val, old_val_ref.shape)
new_val_ref[...] = jax.lax.broadcast(new_val, new_val_ref.shape)
old, new = kernel()
old = old.reshape(n, dim)
new = new.reshape(n, dim)
# old_val comes from the neighbor, which is (my_id + 1) % n.
expected_old = (np.arange(n) + 1) % n
# new_val is my_id + 10, since the neighbor added 10 to me.
expected_new = np.arange(n) + 10
np.testing.assert_array_equal(old[:, 0], expected_old)
np.testing.assert_array_equal(new[:, 1], expected_new)
def test_run_scoped(self):
x = jnp.arange(self.num_lanes)
@self.vector_subcore_kernel(
out_shape=x, out_specs=pl.BlockSpec(memory_space=pltpu.HBM)
)
def kernel(x_ref, o_hbm_ref):
pltpu.sync_copy(x_ref, o_hbm_ref)
np.testing.assert_array_equal(kernel(x), x)
def test_run_scoped_with_tiling(self):
x = jnp.arange(self.num_lanes)
@self.vector_subcore_kernel(out_shape=x)
@pl.with_scoped(
plsc.MemoryRef(x.shape, x.dtype, memory_space=pltpu.VMEM, tiling=[(8,)])
)
def kernel(x_ref, o_ref, scratch_ref):
scratch_ref[...] = x_ref[...]
o_ref[...] = scratch_ref[...]
# Just make sure it compiles. The unrolling logic in the SC compiler
# does not yet handle tiled layouts properly, so the result is wrong.
_ = kernel(x)
@parameterized.parameters(pltpu.VMEM, pltpu.SMEM)
def test_empty_ref(self, memory_space):
@self.vector_subcore_kernel(
out_shape=jax.ShapeDtypeStruct((self.num_lanes,), jnp.float32),
)
def kernel(y_ref):
x_ref = jax.empty_ref(
jax.ShapeDtypeStruct(y_ref.shape, y_ref.dtype),
memory_space=memory_space,
)
s = ... if memory_space == pltpu.VMEM else 0
x_ref[s] = jnp.ones_like(x_ref) if memory_space == pltpu.VMEM else 1.
y_ref[...] = jnp.broadcast_to(4 * x_ref[s], y_ref.shape)
o = kernel()
np.testing.assert_allclose(o, 4 * np.ones_like(o))
@parameterized.product(sizes=[[1, 1], [2, 2], [1, 1, 1, 1]])
# TODO(b/478865387): Remove the skip once the bug is fixed.
@absltest.skip("Needs vector unrolling pass")
def test_split_concatenate(self, sizes):
shape = (sum(sizes), self.num_lanes)
x = jnp.arange(math.prod(shape)).reshape(-1, self.num_lanes)
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, o_ref):
chunks = lax.split(x_ref[...], sizes, 0)
o_ref[...] = lax.concatenate(chunks, 0)
np.testing.assert_array_equal(kernel(x), x)
def test_scratch(self):
x = jnp.arange(self.num_lanes)
@self.vector_subcore_kernel(
out_shape=x,
scratch_shapes=(pltpu.VMEM([self.num_lanes], jnp.float32),),
)
def kernel(x_ref, o_ref, scratch_ref):
scratch_ref[...] = x_ref[...].astype(jnp.float32)
o_ref[...] = scratch_ref[...].astype(x.dtype)
np.testing.assert_array_equal(kernel(x), x)
def test_subcore_parallel(self):
self.skip_if_tc_tiling()
num_subcores = self.sc_info.num_subcores
@self.kernel(
out_shape=jax.ShapeDtypeStruct(
shape=(num_subcores, self.num_lanes), dtype=jnp.int32
),
mesh=plsc.VectorSubcoreMesh(
core_axis_name="core", subcore_axis_name="subcore", num_cores=1
),
)
def kernel(x_ref, o_ref):
# This is a smoke test, since it does not in fact check that the kernel
# is executed in parallel over the subcores.
subcore_id = lax.axis_index("subcore")
pltpu.sync_copy(x_ref.at[subcore_id], o_ref.at[subcore_id])
x = jnp.arange(num_subcores * self.num_lanes, dtype=jnp.int32).reshape(
-1, self.num_lanes
)
np.testing.assert_array_equal(kernel(x), x)
def test_smem_vmem_store_literals(self):
self.skip_if_tc_tiling()
num_subcores = self.sc_info.num_subcores
@self.kernel(
out_shape=jax.ShapeDtypeStruct(
shape=(num_subcores, self.num_lanes), dtype=jnp.float32
),
mesh=plsc.VectorSubcoreMesh(
core_axis_name="core", subcore_axis_name="subcore", num_cores=1
),
scratch_shapes=(
pltpu.SMEM([1], jnp.float32),
pltpu.VMEM([self.num_lanes], jnp.float32),
),
)
def kernel(x_ref, o_ref, scratch_scalar_ref, scratch_vec_ref):
subcore_id = lax.axis_index("subcore")
scratch_scalar_ref[0] = 7.0
pltpu.sync_copy(x_ref.at[subcore_id], scratch_vec_ref)
scratch_vec_ref[...] = jnp.where(
subcore_id < 3, scratch_scalar_ref[0], scratch_vec_ref[...]
)
pltpu.sync_copy(scratch_vec_ref, o_ref.at[subcore_id])
x = jnp.arange(num_subcores * self.num_lanes, dtype=jnp.float32).reshape(
-1, self.num_lanes
)
expected = jnp.where(
jnp.arange(num_subcores)[:, jnp.newaxis] < 3,
jnp.full((num_subcores, self.num_lanes), 7.0),
x,
)
np.testing.assert_array_equal(kernel(x), expected)
@parameterized.named_parameters(
("barrier", lambda _: plsc.subcore_barrier()),
("debug_print", lambda vec: pl.debug_print("test", vec)),
)
def test_effect_discharge(self, effectful_op):
x = jnp.arange(self.sc_info.num_lanes)
mesh = plsc.VectorSubcoreMesh(
core_axis_name="core", subcore_axis_name="subcore", num_cores=1
)
def stateful(refs):
def body(x_ref, o_ref):
def with_scratch(scratch_ref):
pltpu.sync_copy(x_ref, scratch_ref)
scratch_ref[...] = scratch_ref[...] + 1
effectful_op(scratch_ref[...])
pltpu.sync_copy(scratch_ref, o_ref)
pl.run_scoped(with_scratch, pltpu.VMEM(x.shape, x.dtype))
pl.core_map(mesh)(lambda: body(*refs))
_, out = jax.jit(state_discharge.run_state(stateful))(
(x, jnp.empty_like(x)))
np.testing.assert_array_equal(out, x + 1)
def test_parallel_loop_effects(self):
chunk_size = self.num_lanes
@self.kernel(
out_shape=(),
mesh=plsc.VectorSubcoreMesh(
core_axis_name="core", subcore_axis_name="subcore", num_cores=1
),
scratch_shapes=(pltpu.VMEM((chunk_size,), jnp.uint32),) * 3,
)
def _kernel(a_ref, b_ref, c_ref):
@pl.loop(0, 4)
def outer(i):
const = jnp.array(0, jnp.uint32)
@plsc.parallel_loop(0, chunk_size)
def body(_):
x = a_ref[...] >> i.astype(jnp.uint32)
plsc.store_compressed(c_ref.at[...], b_ref[...], mask=x > const)
_kernel()
def test_reshape(self):
shape = (self.num_lanes,)
dtype = jnp.int32
@self.vector_subcore_kernel(out_shape=jax.ShapeDtypeStruct(shape, dtype))
def kernel(x_ref, o_ref):
o_ref[...] = (
x_ref[...].reshape(2, self.num_lanes // 2).reshape(self.num_lanes)
)
x = jnp.arange(math.prod(shape), dtype=dtype).reshape(shape)
np.testing.assert_array_equal(kernel(x), x)
@parameterized.product(dtype=[jnp.int32, jnp.float32])
def test_cumsum(self, dtype):
x = jnp.arange(self.sc_info.num_lanes, dtype=dtype)
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, o_ref):
o_ref[...] = jnp.cumsum(x_ref[...])
np.testing.assert_array_equal(kernel(x), np.cumsum(x))
@parameterized.product(dtype=[jnp.uint32, jnp.int32, jnp.float32],
op=[jnp.sum, jnp.max, jnp.min])
def test_reductions(self, dtype, op):
x = jnp.arange(self.sc_info.num_lanes, dtype=dtype)
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, o_ref):
o_ref[...] = jnp.full(o_ref.shape, op(x_ref[...]))
np.testing.assert_array_equal(kernel(x)[0], op(x))
np.testing.assert_array_equal(kernel(x[::-1])[0], op(x[::-1]))
if dtype != jnp.uint32:
np.testing.assert_array_equal(kernel(-x)[0], op(-x))
np.testing.assert_array_equal(kernel(-x[::-1])[0], op(-x[::-1]))
@parameterized.product(dtype=[jnp.bool], op=[jnp.all, jnp.any])
def test_binary_reductions(self, dtype, op):
x = jnp.ones(self.sc_info.num_lanes, dtype=dtype)
@self.vector_subcore_kernel(out_shape=x.astype(jnp.int32))
def kernel(x_ref, o_ref):
o_ref[...] = jnp.full(o_ref.shape, op(x_ref[...] != 0)).astype(jnp.int32)
np.testing.assert_array_equal(
kernel(x.astype(jnp.int32))[0].astype(dtype), op(x))
@parameterized.product(dtype=[jnp.int32, jnp.float32])
def test_cumsum_2d_not_supported(self, dtype):
x = jnp.arange(self.sc_info.num_lanes, dtype=dtype)
with self.assertRaisesRegex(NotImplementedError, r"must be rank 1"):
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, o_ref):
o_ref[...] = (
jnp.cumsum(x_ref[...].reshape(4, self.num_lanes // 4), axis=0)
.reshape(-1)
)
kernel(x)
@parameterized.product(dtype=[jnp.int32, jnp.float32])
def test_masked_cumsum(self, dtype):
x = jnp.arange(self.sc_info.num_lanes, dtype=dtype)
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, o_ref):
o_ref[...] = plsc.cumsum(x_ref[...], mask=(x_ref[...] % 2) == 1)
np.testing.assert_array_equal(kernel(x), np.cumsum(x * (x % 2)))
@parameterized.product(dtype=[jnp.int32, jnp.float32])
def test_masked_cummax(self, dtype):
x = np.arange(self.sc_info.num_lanes, dtype=dtype)
np.random.shuffle(x)
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, o_ref):
o_ref[...] = plsc.cummax(x_ref[...], mask=(x_ref[...] % 2) == 1)
row = np.arange(self.sc_info.num_lanes)[:, np.newaxis]
col = np.arange(self.sc_info.num_lanes)[np.newaxis, :]
mask = x % 2
expected = (x * mask * (col <= row)).max(axis=1)
has_valid_value_so_far = np.cumsum(mask) > 0
expected = np.where(has_valid_value_so_far, expected, x)
np.testing.assert_array_equal(kernel(x), expected)
def test_parallel_loop_with_carry(self):
# TODO(b/488280666): Remove this skip once the bug is fixed.
self.skip_if_tc_tiling("The test is flaky with TC tiling")
chunk_size = self.num_lanes
nchunks = 4
per_step_increment = 10
sentinel_multiplier = 1000
nsubcores = self.sc_info.num_subcores
x = jnp.arange(nsubcores * chunk_size * nchunks, dtype=np.int32)
@self.vector_subcore_kernel(
out_shape=x,
grid=(nsubcores,),
in_specs=[pl.BlockSpec([chunk_size * nchunks], lambda i: (i,))],
out_specs=pl.BlockSpec([chunk_size * nchunks], lambda i: (i,)),
)
def kernel(x_ref, o_ref):
@pl.when(pl.program_id(0) < nsubcores)
def _():
init = (
jnp.zeros([], x_ref.dtype), # scalar
jnp.zeros([chunk_size], x_ref.dtype), # vector
)
def for_each_chunk(i, carry):
incr, running_sum = carry
incr += per_step_increment
o_ref[pl.ds(i, chunk_size)] = x_ref[pl.ds(i, chunk_size)] + incr
return incr, running_sum + x_ref[pl.ds(i, chunk_size)]
result = plsc.parallel_loop(0, x_ref.shape[0], chunk_size, carry=init)(
for_each_chunk)
o_ref[pl.ds(0, chunk_size)] = jnp.where(
jnp.arange(chunk_size) == 0,
result[0] * sentinel_multiplier,
result[1])
output = kernel(x)
expected = np.array(x).reshape(nsubcores, nchunks, chunk_size)
# Check that the increment was properly applied.
expected += 10 * np.arange(1, 5)[:, None]
# Check the final carry values:
# - Scalar in 0th position.
expected[:, 0, 0] = sentinel_multiplier * per_step_increment * nchunks
# - Vector in 1:chunk_size-1 positions.
expected[:, 0, 1:] = x.reshape(nsubcores, nchunks, chunk_size).sum(1)[
:, 1:
]
np.testing.assert_array_equal(output, expected.reshape(-1))
@parameterized.parameters(
(lambda x_ref: x_ref, r"may not be.*Ref\{"),
(lambda x_ref: x_ref.at[pl.ds(0, 8)], r"TransformedRefs are not allowed"),
)
def test_parallel_loop_disallows_ref_carries(self, carry_fn, expected_regex):
x = jnp.arange(2 * self.num_lanes, dtype=jnp.int32)
with self.assertRaisesRegex(TypeError, expected_regex):
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, o_ref):
@plsc.parallel_loop(0, 1, carry=carry_fn(x_ref))
def _(i, carry):
del i # Unused.
x_ref[...] = o_ref[...]
return carry
kernel(x)
def test_parallel_loop_wrong_carry_return(self):
x = jnp.arange(2 * self.num_lanes, dtype=jnp.int32)
with self.assertRaisesRegex(ValueError, "should have same structure"):
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, o_ref):
init = dict(x=jnp.zeros([]), y=jnp.ones([self.num_lanes]))
@plsc.parallel_loop(0, 1, carry=init)
def _(i, carry):
del i # Unused.
x_ref[...] = o_ref[...]
return carry["x"]
kernel(x)
def test_multiple_of(self):
x = jnp.arange(2 * self.num_lanes)
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, o_ref):
@pl.loop(0, 2 * self.num_lanes, step=self.num_lanes)
def _(i):
i = pl.multiple_of(i, self.num_lanes)
o_ref[pl.ds(i, self.num_lanes)] = x_ref[pl.ds(i, self.num_lanes)] + 1
np.testing.assert_array_equal(kernel(x), x + 1)
def test_barrier_via_mesh(self):
self.skip_if_tc_tiling()
mesh = plsc.VectorSubcoreMesh(
core_axis_name="core", subcore_axis_name="subcore", num_cores=1
)
vec_dim = self.sc_info.num_lanes
@self.kernel(
out_shape=jax.ShapeDtypeStruct(
shape=(mesh.num_subcores, vec_dim), dtype=jnp.uint32
),
mesh=mesh,
scratch_shapes=[pltpu.VMEM((mesh.num_subcores, vec_dim), jnp.uint32)],
)
def kernel(o_ref, vmem_ref):
subcore_id = lax.axis_index("subcore")
@pl.loop(0, 2 * subcore_id + 1)
def _(i):
vmem_ref[subcore_id] = jnp.full(vec_dim, i, dtype=jnp.uint32)
pltpu.sync_copy(vmem_ref.at[subcore_id], o_ref.at[subcore_id])
plsc.subcore_barrier()
pltpu.sync_copy(o_ref.at[(subcore_id + 1) % mesh.num_subcores],
vmem_ref.at[subcore_id])
pltpu.sync_copy(vmem_ref.at[subcore_id], o_ref.at[subcore_id])
expected = 2 * jnp.roll(jnp.arange(mesh.num_subcores), -1)
expected = jnp.broadcast_to(expected[:, None], (mesh.num_subcores, vec_dim))
np.testing.assert_array_equal(kernel(), expected)
def test_barrier_via_pallas_call(self):
self.skip_if_tc_tiling()
mesh = plsc.VectorSubcoreMesh(
core_axis_name="core", subcore_axis_name="subcore", num_cores=1
)
vec_dim = self.num_lanes
nsubcores = self.sc_info.num_subcores
@functools.partial(
pl.pallas_call,
grid=nsubcores,
compiler_params=pltpu.CompilerParams(
kernel_type=pltpu.CoreType.SC_VECTOR_SUBCORE,
dimension_semantics=["subcore_parallel"],
use_tc_tiling_on_sc=self.USE_TC_TILING,
),
out_shape=jax.ShapeDtypeStruct(
shape=(mesh.num_subcores, vec_dim), dtype=jnp.uint32
),
out_specs=pl.BlockSpec((1, vec_dim), lambda i: (i, 0)),
scratch_shapes=(
pltpu.VMEM_SHARED((mesh.num_subcores, vec_dim), jnp.uint32),
pltpu.VMEM((vec_dim,), jnp.uint32),
),
)
def kernel(o_ref, shared_ref, vmem_ref):
subcore_id = pl.program_id(0)
@pl.loop(0, 10 * subcore_id + 1)
def _(i):
vmem_ref[:] = jnp.full(vec_dim, i, dtype=jnp.uint32)
pltpu.sync_copy(vmem_ref, shared_ref.at[subcore_id])
plsc.subcore_barrier()
pltpu.sync_copy(
shared_ref.at[(subcore_id + 1) % mesh.num_subcores], o_ref.at[0]
)
expected = 10 * jnp.roll(jnp.arange(mesh.num_subcores), -1)
expected = jnp.broadcast_to(expected[:, None], (mesh.num_subcores, vec_dim))
np.testing.assert_array_equal(kernel(), expected)
@parameterized.parameters(jnp.int32, jnp.float32)
def test_gather_add(self, dtype):
self.skip_if_tc_tiling()
shape = (self.sc_info.num_subcores, 64, 32)
x = jnp.arange(math.prod(shape), dtype=dtype).reshape(*shape)
# TODO(b/478819791): Fix and enable on v7x
if jtu.is_device_tpu(7, "x"):
self.skipTest("Mysteriously fails in MLIR verifier (no error message) on v7x")
@self.kernel(
out_shape=x[:, : self.num_lanes],
mesh=plsc.VectorSubcoreMesh(
core_axis_name="core", subcore_axis_name="subcore", num_cores=1
),
scratch_shapes=dict(
indices_vmem=pltpu.VMEM([8], jnp.int32),
scratch_ref=pltpu.VMEM([8, 32], dtype),
),
)
def kernel(x_ref, indices_ref, o_ref, indices_vmem, scratch_ref):
subcore_id = lax.axis_index("subcore")
pltpu.sync_copy(indices_ref, indices_vmem)
# Initialize scratch space.
pltpu.sync_copy(x_ref.at[subcore_id, pl.ds(0, 8)], scratch_ref)
# Gather-add selected indices to scratch.
# TODO(selebedev): Allow mixing array and ref indexers in ``.at``.
pltpu.sync_copy(
x_ref.at[subcore_id].at[indices_vmem], scratch_ref, add=True
)
pltpu.sync_copy(scratch_ref, o_ref.at[subcore_id])
indices = jnp.arange(8) * 8
np.testing.assert_array_equal(kernel(x, indices), x[:, :8] + x[:, indices])
@parameterized.parameters(jnp.int32, jnp.float32)
def test_scatter_add(self, dtype):
self.skip_if_tc_tiling()
shape = (self.sc_info.num_subcores, 32)
x = jnp.arange(math.prod(shape), dtype=dtype).reshape(*shape)
mesh = plsc.VectorSubcoreMesh(
core_axis_name="core", subcore_axis_name="subcore", num_cores=1
)
@functools.partial(
pl.pallas_call,
grid=mesh.num_subcores,
compiler_params=pltpu.CompilerParams(
kernel_type=pltpu.CoreType.SC_VECTOR_SUBCORE,
dimension_semantics=["subcore_parallel"],
use_tc_tiling_on_sc=self.USE_TC_TILING,
),
out_shape=jax.ShapeDtypeStruct(shape[1:], dtype),
out_specs=pl.BlockSpec(
shape[1:], lambda i: (0,), memory_space=pltpu.HBM
),
in_specs=[
pl.BlockSpec(shape, lambda *_: (0, 0), memory_space=pltpu.HBM),
pl.BlockSpec(shape[1:], lambda _: (0,)),
],
scratch_shapes=[
pltpu.VMEM_SHARED(shape[1:], dtype),
pltpu.VMEM(shape[1:], dtype),
],
)
def kernel(x_ref, indices_ref, o_ref, shared_scratch_ref, scratch_ref):
subcore_id = pl.program_id(0)
pltpu.sync_copy(x_ref.at[subcore_id], scratch_ref)
# Subcore 0 to init shared scratch.
@pl.when(subcore_id == 0)
def _():
pltpu.sync_copy(scratch_ref, shared_scratch_ref)
plsc.subcore_barrier()
# All cores to add their slice to shared scratch.
pltpu.sync_copy(scratch_ref, shared_scratch_ref.at[indices_ref], add=True)
plsc.subcore_barrier()
# Subcore 0 to copy shared scratch to output.
@pl.when(subcore_id == 0)
def _():
pltpu.sync_copy(shared_scratch_ref, scratch_ref)
pltpu.sync_copy(scratch_ref, o_ref)
indices = 31 - jnp.arange(32)
np.testing.assert_array_equal(kernel(x, indices), x[0] + x.sum(0)[::-1])
def test_shared_scratch(self):
if not jtu.is_cloud_tpu_at_least(2026, 3, 1):
self.skip_if_tc_tiling()
mesh = plsc.VectorSubcoreMesh(
core_axis_name="core", subcore_axis_name="subcore", num_cores=1
)
shape = (mesh.num_subcores, 8, self.num_lanes)
x = jnp.arange(math.prod(shape), dtype=jnp.int32).reshape(*shape)
@self.kernel(
out_shape=x,
mesh=mesh,
scratch_shapes=(
pltpu.VMEM_SHARED(shape[1:], jnp.int32),
pltpu.VMEM_SHARED(shape, jnp.int32),
),
)
def kernel(x_ref, o_ref, shared_scratch_ref, shared_scratch_ref2):
subcore_id = lax.axis_index("subcore")
@pl.when(subcore_id == 0)
def _():
pltpu.sync_copy(
x_ref.at[subcore_id], shared_scratch_ref2.at[subcore_id])
pltpu.sync_copy(x_ref.at[subcore_id], shared_scratch_ref)
pltpu.sync_copy(shared_scratch_ref, o_ref.at[subcore_id])
np.testing.assert_array_equal(kernel(x)[0], x[0])
def test_copy_in_shard_map(self):
self.skip_if_tc_tiling()
num_devices = len(jax.devices())
mesh = jtu.create_mesh((num_devices,), ("x",))
rng = np.random.default_rng(0)
x = rng.integers(512, size=(num_devices * 1024, 16), dtype=np.int32)
# The test ensures that JAX-level memory space for ``x`` is not propagated
# into Pallas, since Pallas cannot use it.
x = jax.device_put(x, jax.sharding.NamedSharding(mesh, jax.P("x", None)))
self.assertEqual(jax.typeof(x).memory_space, jax.memory.Space.Device)
@functools.partial(
jax.shard_map,
in_specs=(jax.P("x", None),),
out_specs=jax.P("x", None),
mesh=mesh,
check_vma=True,
)
def f(x):
@self.kernel(
out_shape=jax.ShapeDtypeStruct(x.shape, x.dtype, vma={"x"}),
mesh=plsc.VectorSubcoreMesh(
core_axis_name="core", subcore_axis_name="subcore", num_cores=1
),
scratch_shapes=(pltpu.VMEM(x.shape, x.dtype),),
)
def kernel(in_ref, o_ref, scratch_ref):
pltpu.sync_copy(in_ref, scratch_ref)
pltpu.sync_copy(scratch_ref, o_ref)
return kernel(x)
np.testing.assert_array_equal(f(x), x)
@parameterized.named_parameters(
("exp", jnp.exp), ("neg", lambda x: -x), ("abs", jnp.abs)
)
def test_unary_ops(self, op):
x = jnp.arange(self.num_lanes, dtype=jnp.float32)
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, o_ref):
o_ref[...] = op(x_ref[...])
np.testing.assert_array_equal(kernel(x), op(x))
@parameterized.product(dtype=[np.int32, np.float32])
def test_vector_gather(self, dtype):
vec_dim = self.sc_info.num_lanes
x = np.arange(vec_dim, dtype=dtype)
indices = np.random.randint(0, vec_dim, size=vec_dim, dtype=np.int32)
indices[[0, -2]] = 2 # Verify non-unique works.
indices[1] = -2 # Verify negative indices work.
@self.vector_subcore_kernel(out_shape=x)
def kernel(x_ref, indices_ref, out_ref):
out_ref[...] = x_ref[...][indices_ref[...]]
np.testing.assert_array_equal(kernel(x, indices), x[indices])
@parameterized.product(
keys_dtype=[np.int32, np.float32],
values_dtype=[np.int32, np.float32],
use_mask=[False, True],
descending=[False, True],
)
def test_sort_key_val(self, keys_dtype, values_dtype, use_mask, descending):
vec_dim = self.sc_info.num_lanes
keys = np.arange(vec_dim, dtype=keys_dtype)
np.random.shuffle(keys)
keys[3] = keys[1] # Verify sort stability.
values = np.arange(vec_dim, dtype=values_dtype)
np.random.shuffle(values)
mask = np.random.choice([True, False], size=vec_dim) if use_mask else None
maybe_mask_arg = (mask.astype(jnp.int32),) if use_mask else ()
@self.vector_subcore_kernel(out_shape=(keys, values, *maybe_mask_arg))
def kernel(*args):
if use_mask:
mask_ref, *args, o_mask_ref = args
mask = mask_ref[...].astype(jnp.bool)
else:
mask, o_mask_ref = None, None
keys_ref, values_ref, o_keys_ref, o_vals_ref = args
o_keys_ref[...], o_vals_ref[...], *maybe_out_mask = plsc.sort_key_val(
keys_ref[...], values_ref[...], mask=mask, descending=descending)
if use_mask:
[out_mask] = maybe_out_mask
o_mask_ref[...] = out_mask.astype(jnp.int32)
out_keys, out_values, *maybe_out_mask = kernel(
*maybe_mask_arg, keys, values)
keys_arg = keys
if descending:
keys_arg = -keys_arg
if use_mask:
keys_arg = jnp.where(mask, keys_arg, 100)
_, gt_keys = jax.lax.sort_key_val(keys_arg, keys)
_, gt_values = jax.lax.sort_key_val(keys_arg, values)
if use_mask:
[out_mask] = maybe_out_mask
gt_out_mask = jnp.arange(vec_dim) < mask.sum()
np.testing.assert_array_equal(out_mask, gt_out_mask.astype(jnp.int32))
np.testing.assert_array_equal(out_keys, gt_keys)
np.testing.assert_array_equal(out_values, gt_values)
@parameterized.product(dtype=[np.int32, np.float32])
def test_rev_and_sort_desc(self, dtype):
vec_dim = self.sc_info.num_lanes
keys = np.arange(vec_dim, dtype=dtype)
np.random.shuffle(keys)
@self.vector_subcore_kernel(out_shape=(keys, keys))
def kernel(x_ref, o1_ref, o2_ref):
o1_ref[...] = jnp.sort(x_ref[...], descending=True)
o2_ref[...] = jnp.flip(x_ref[...], axis=-1)
sorted_desc, reversed_keys = kernel(keys) # pylint: disable=unpacking-non-sequence
np.testing.assert_array_equal(
sorted_desc, jnp.arange(vec_dim, dtype=dtype)[::-1])
np.testing.assert_array_equal(reversed_keys, keys[::-1])
@parameterized.product(
keys_dtype=[np.int32, np.float32],
values_dtypes=[(), (np.int32,), (np.float32, np.int32)],
)
def test_sort(self, keys_dtype, values_dtypes):
vec_dim = self.sc_info.num_lanes
keys = np.arange(vec_dim, dtype=keys_dtype)
np.random.shuffle(keys)
values = [np.arange(vec_dim, dtype=dtype) for dtype in values_dtypes]
_ = [np.random.shuffle(v) for v in values]
@self.vector_subcore_kernel(out_shape=(keys, *values))
def kernel(*args):
keys_ref, *values_refs = args[: len(args) // 2]
keys_out, *all_values_out = jax.lax.sort(
(keys_ref[...], *(ref[...] for ref in values_refs))
)
keys_out_ref, *values_out_refs = args[len(args) // 2 :]
keys_out_ref[...] = keys_out
for values_out_ref, values_out in zip(
values_out_refs, all_values_out, strict=True
):
values_out_ref[...] = values_out
perm = np.argsort(keys)
keys_result, *values_results = kernel(keys, *values)
np.testing.assert_array_equal(keys_result, keys[perm])
for values_result, values_in in zip(values_results, values, strict=True):
np.testing.assert_array_equal(values_result, values_in[perm])
class VectorSubcoreTestWithTCTiling(VectorSubcoreTest):
USE_TC_TILING = True
class ScalarSubcoreTest(PallasSCTest):
def test_pallas_call(self):
if not jtu.is_cloud_tpu_at_least(2026, 2, 22):
self.skipTest("Requires a newer libtpu")
@functools.partial(
pl.pallas_call,
out_shape=jax.ShapeDtypeStruct((self.num_lanes,), jnp.int32),
compiler_params=pltpu.CompilerParams(
kernel_type=pltpu.CoreType.SC_SCALAR_SUBCORE,
use_tc_tiling_on_sc=self.USE_TC_TILING,
),
)
def kernel(x, out):
@pl.loop(0, x.size)
def _(i):
out[i] = x[i] + 1
x = jnp.arange(self.num_lanes)
np.testing.assert_array_equal(kernel(x), x + 1)
def test_copy(self):
x = jnp.arange(self.num_lanes)
@self.kernel(
out_shape=x,
mesh=plsc.ScalarSubcoreMesh(
axis_name="x", num_cores=self.sc_info.num_cores
),
)
def kernel(x_ref, o_ref):
lax.cond(
lax.axis_index("x") == lax.axis_size("x") - 1,
lambda: pltpu.sync_copy(x_ref, o_ref),
lambda: None,
)
np.testing.assert_array_equal(kernel(x), x)
def test_sliced_copy(self):
self.skip_if_tc_tiling()
x = jnp.arange(self.sc_info.num_cores * self.num_lanes).reshape(
self.sc_info.num_cores, -1
)
@self.kernel(
out_shape=x,
mesh=plsc.ScalarSubcoreMesh(
axis_name="x", num_cores=self.sc_info.num_cores
),
)
def kernel(x_ref, o_ref):
@functools.partial(pl.run_scoped, sems=pltpu.SemaphoreType.DMA(4))
def _(sems):
core_id = lax.axis_index("x")
pltpu.async_copy(
x_ref.at[core_id], o_ref.at[core_id], sems.at[core_id]
).wait()
np.testing.assert_array_equal(kernel(x), x)
def test_scalar_load_store(self):
x = jnp.arange(self.num_lanes)
@self.kernel(
out_shape=x, mesh=plsc.ScalarSubcoreMesh(axis_name="core", num_cores=1)
)
def kernel(x_ref, o_ref):
@functools.partial(
pl.run_scoped,
tmp_ref=pltpu.SMEM(x.shape, x.dtype),
sem=pltpu.SemaphoreType.DMA,
)
def _(tmp_ref, sem):
pltpu.async_copy(x_ref, tmp_ref, sem).wait()
@pl.loop(1, *x.shape)
def _(i):
tmp_ref[i] += tmp_ref[i - 1]
pltpu.async_copy(tmp_ref, o_ref, sem).wait()
np.testing.assert_array_equal(kernel(x), jnp.cumsum(x))
@parameterized.product(
first_parallel=[False, True], second_parallel=[False, True]
)
def test_parallel_loop(self, first_parallel, second_parallel):
if not jtu.is_cloud_tpu_at_least(2026, 2, 13):
self.skipTest("Requires a newer libtpu")
if not jtu.is_cloud_tpu_at_least(2026, 3, 1):
self.skip_if_tc_tiling()
x = jnp.arange(self.num_lanes * self.num_lanes).reshape(
self.num_lanes, self.num_lanes
)
loop = lambda start, end, parallel, **kwargs: (
plsc.parallel_loop(start, end, **kwargs)
if parallel
else pl.loop(start, end, **kwargs)
)
@self.kernel(
out_shape=x,
mesh=plsc.ScalarSubcoreMesh(axis_name="core", num_cores=1),
scratch_shapes=(
pltpu.SMEM(x.shape, x.dtype),
pltpu.SemaphoreType.DMA,
),
)
def kernel(x_ref, o_ref, tmp_ref, sem):
pltpu.async_copy(x_ref, tmp_ref, sem).wait()
@loop(0, tmp_ref.shape[0], first_parallel)
def _(i):
@loop(0, tmp_ref.shape[1], second_parallel, unroll=tmp_ref.shape[1])
def _(j):
tmp_ref[i, j] += 1
pltpu.async_copy(tmp_ref, o_ref, sem).wait()
np.testing.assert_array_equal(kernel(x), x + 1)
def test_parallel_loop_with_carry(self):
if not jtu.is_cloud_tpu_at_least(2026, 2, 13):
self.skipTest("Requires a newer libtpu")
if not jtu.is_cloud_tpu_at_least(2026, 3, 1):
self.skip_if_tc_tiling()
x = jnp.arange(self.num_lanes * self.num_lanes).reshape(
self.num_lanes, self.num_lanes
)
@self.kernel(
out_shape=x,
mesh=plsc.ScalarSubcoreMesh(axis_name="core", num_cores=1),
scratch_shapes=(
pltpu.SMEM(x.shape, x.dtype),
pltpu.SemaphoreType.DMA,
),
)
def kernel(x_ref, o_ref, tmp_ref, sem):
pltpu.async_copy(x_ref, tmp_ref, sem).wait()
@plsc.parallel_loop(0, tmp_ref.shape[0], carry=jnp.zeros([], x.dtype))
def _(i, carry):
carry += 1
@plsc.parallel_loop(0, tmp_ref.shape[1], unroll=2)
def _(j):
tmp_ref[i, j] += carry
return carry
pltpu.async_copy(tmp_ref, o_ref, sem).wait()
np.testing.assert_array_equal(
kernel(x), x + jnp.arange(1, self.num_lanes + 1)[:, None]
)
def test_dma_memory_space(self):
if not jtu.is_cloud_tpu_at_least(2026, 2, 13):
self.skipTest("Requires a newer libtpu")
x = jnp.arange(self.num_lanes)
@functools.partial(
pl.pallas_call,
compiler_params=pltpu.CompilerParams(
kernel_type=pltpu.CoreType.SC_SCALAR_SUBCORE,
),
grid=(1,),
in_specs=[pl.BlockSpec(memory_space=pltpu.HBM)],
out_shape=x,
out_specs=pl.BlockSpec(memory_space=pltpu.HBM),
scratch_shapes=(pltpu.SemaphoreType.DMA,),
)
def kernel(x_ref, o_hbm_ref, sem):
pltpu.async_copy(x_ref, o_hbm_ref, sem).wait()
np.testing.assert_array_equal(kernel(x), x)
class ScalarSubcoreTestWithTCTiling(ScalarSubcoreTest):
USE_TC_TILING = True
class MpmdMapTest(PallasSCTest):
def setUp(self):
if not jtu.is_cloud_tpu_at_least(2026, 2, 21):
self.skipTest("Requires a newer libtpu")
super().setUp()
def test_parallel_subkernels(self):
if not jtu.is_cloud_tpu_at_least(2026, 3, 1):
self.skipTest("Need a newer libtpu")
v_mesh = plsc.VectorSubcoreMesh(
core_axis_name="core",
subcore_axis_name="subcore",
num_cores=self.sc_info.num_cores,
)
s_mesh = plsc.ScalarSubcoreMesh(
axis_name="scs_core", num_cores=self.sc_info.num_cores
)
x = jnp.arange(self.num_lanes, dtype=jnp.int32)
def vector_subcore_fn(x_hbm_ref, out_hbm_ref):
scratch_ref = jax.empty_ref(jax.typeof(x), memory_space=pltpu.VMEM)
pltpu.sync_copy(x_hbm_ref, scratch_ref)
scratch_ref[...] += 2 * scratch_ref[...]
pltpu.sync_copy(scratch_ref, out_hbm_ref.at[:x.size])
def scalar_subcore_fn(x_hbm_ref, out_hbm_ref):
scratch_ref = jax.empty_ref(jax.typeof(x), memory_space=pltpu.SMEM)
pltpu.sync_copy(x_hbm_ref, scratch_ref)
@pl.loop(0, x.size)
def _(i):
scratch_ref[i] += 3 * scratch_ref[i]
pltpu.sync_copy(scratch_ref, out_hbm_ref.at[x.size:])
out = mpmd.mpmd_map(
[(v_mesh, vector_subcore_fn), (s_mesh, scalar_subcore_fn)],
out_shapes=jax.ShapeDtypeStruct([x.size * 2], x.dtype),
)(x)
np.testing.assert_array_equal(out[:x.size], x + 2 * x)
np.testing.assert_array_equal(out[x.size:], x + 3 * x)
class PipelineTest(PallasSCTest):
def test_basic(self):
self.skip_if_tc_tiling()
if self.num_lanes != 8:
# TODO(b/478865387): Remove the skip once the bug is fixed.
self.skipTest(
f"This test requires SC to have 8 lanes, but got {self.num_lanes}"
)
num_steps = 16
x = jnp.arange(num_steps * self.num_lanes).reshape(-1, 8)
@self.vector_subcore_kernel(
out_shape=x,
in_specs=(pl.BlockSpec(memory_space=pltpu.HBM),),
out_specs=pl.BlockSpec(memory_space=pltpu.HBM),
)
def kernel(x_hbm_ref, o_hbm_ref):
@functools.partial(
pltpu.emit_pipeline,
tiling=pltpu.Tiling.SPARSE_CORE,
grid=(num_steps,),
in_specs=pl.BlockSpec(
(pl.Squeezed(), self.num_lanes), lambda i: (i, 0)
),
out_specs=pl.BlockSpec(
(pl.Squeezed(), self.num_lanes), lambda i: (i, 0)
),
)
def pipeline(x_ref, o_ref):
o_ref[...] = x_ref[...] + 1
pipeline(x_hbm_ref, o_hbm_ref)
np.testing.assert_array_equal(kernel(x), x + 1)
def test_explicit_sc_tiling_1d(self):
self.skip_if_tc_tiling("The test uses SC tiling.")
num_steps = 4
x = jnp.arange(num_steps * self.num_lanes)
@self.vector_subcore_kernel(
out_shape=x,
in_specs=(pl.BlockSpec(memory_space=pltpu.HBM),),
out_specs=pl.BlockSpec(memory_space=pltpu.HBM),
)
def kernel(x_hbm_ref, o_hbm_ref):
spec = plsc.BlockSpec((self.num_lanes,), lambda i: (i,))
@functools.partial(
pltpu.emit_pipeline,
grid=(num_steps,),
in_specs=spec,
out_specs=spec,
tiling=pltpu.Tiling.SPARSE_CORE,
)
def pipeline(x_ref, o_ref):
o_ref[...] = x_ref[...] + 1
pipeline(x_hbm_ref, o_hbm_ref)
np.testing.assert_array_equal(kernel(x), x + 1)
def test_explicit_sc_tiling_2d(self):
self.skip_if_tc_tiling("The test uses SC tiling.")
num_steps = 16
x = jnp.arange(num_steps * 8 * 128).reshape(-1, 8, 128)
@self.vector_subcore_kernel(
out_shape=x,
in_specs=(pl.BlockSpec(memory_space=pltpu.HBM),),
out_specs=pl.BlockSpec(memory_space=pltpu.HBM),
)
def kernel(x_hbm_ref, o_hbm_ref):
spec = plsc.BlockSpec((pl.Squeezed(), 8, 128), lambda i: (i, 0, 0))
@functools.partial(
pltpu.emit_pipeline,
grid=(num_steps,),
in_specs=[spec],
out_specs=[spec],
tiling=pltpu.Tiling.SPARSE_CORE,
)
def pipeline(x_ref, o_ref):
@pl.loop(0, 8)
def _(i):
@pl.loop(0, 128, step=self.num_lanes)
def _(j):
js = pl.ds(j, self.num_lanes)
o_ref[i, js] = x_ref[i, js] + 1
pipeline(x_hbm_ref, o_hbm_ref)
np.testing.assert_array_equal(kernel(x), x + 1)
class PipelineTestWithTCTiling(PipelineTest):
USE_TC_TILING = True
class PallasSparsecoreAsyncTest(PallasSCTest):
@parameterized.product(
shape=[
(8, 128),
(8, 256),
(8, 512),
(8, 1024),
(16, 128),
(16, 256),
(16, 512),
(16, 1024),
# TODO(sharadmv): These shapes fail right now.
# (64, 8),
],
dtype=[jnp.int32, jnp.float32, jnp.bfloat16],
)
def test_basic_async_kernel(self, shape, dtype):
x = jnp.arange(shape[0] * shape[1], dtype=dtype).reshape(shape)
@jax.jit
def foo(x):
sc_mesh = plsc.ScalarSubcoreMesh(axis_name="core", num_cores=1)
sem = pl.pallas_call(
lambda _: None,
out_shape=pltpu.SemaphoreType.DMA(()),
out_specs=pl.BlockSpec(memory_space=pltpu.SEMAPHORE),
grid=(1,),
compiler_params=pltpu.CompilerParams(
dimension_semantics=["core_parallel"],
kernel_type=pltpu.CoreType.SC_SCALAR_SUBCORE,
use_tc_tiling_on_sc=self.USE_TC_TILING,
),
)()
sem_ref = jax.new_ref(sem, memory_space=pltpu.SEMAPHORE)
y_ref = pl.empty_ref_like(pltpu.HBM(x.shape, x.dtype))
x_ref = jax.new_ref(x)
run_kernel = pl.core_map(mesh=sc_mesh)
@run_kernel
def _():
pltpu.make_async_copy(x_ref, y_ref, sem_ref).start()
@run_kernel
def _():
pltpu.make_async_copy(x_ref, y_ref, sem_ref).wait()
return y_ref[...]
o = jax.block_until_ready(foo(x))
np.testing.assert_array_equal(o, x)
def test_memory_space_annotations_aliased_input_core_map(self):
@jax.jit
def f(x, y):
mesh = plsc.ScalarSubcoreMesh(axis_name='core', num_cores=1)
x_ref = jax.new_ref(x, memory_space=pltpu.HBM)
y_ref = jax.new_ref(y, memory_space=pltpu.HBM)
index_ref = jax.new_ref(
jnp.zeros([8], jnp.int32), memory_space=pltpu.SMEM
)
sem = pl.kernel(
lambda *_: None,
out_shape=pltpu.SemaphoreType.DMA(()),
mesh=mesh,
name="sem_alloc",
)()
sem_ref = jax.new_ref(sem, memory_space=pltpu.SEMAPHORE)
@pl.core_map(mesh)
def dma1():
pltpu.async_copy(x_ref.at[index_ref[0]], y_ref, sem_ref).wait()
index_ref[0] += 1 # TODO(b/487587946): unable to put this inside dma1
y1 = jax.freeze(y_ref)
y_ref = jax.new_ref(y1)
@pl.core_map(mesh)
def dma2():
pltpu.async_copy(x_ref.at[index_ref[0]], y_ref, sem_ref).wait()
y2 = jax.freeze(y_ref)
# Transpose tests jnp op on result of core_map, verifying we don't leak
# ShapedArrayWithMemorySpace.
return y1.T, y2.T
x = jnp.arange(2 * 8 * 128.0).reshape(2, 8, 128)
y = -x[0]
y1, y2 = f(x, y)
np.testing.assert_array_equal(y1, x[0].T)
np.testing.assert_array_equal(y2, x[1].T)
class PallasSparsecoreAsyncTestWithTCTiling(PallasSparsecoreAsyncTest):
USE_TC_TILING = True
if __name__ == "__main__":
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/pallas/tpu_sparsecore_pallas_test.py",
"license": "Apache License 2.0",
"lines": 1958,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/pallas/triton_pallas_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import functools
import sys
import unittest
from absl.testing import absltest
from absl.testing import parameterized
import jax
from jax import lax
from jax._src import config
from jax._src import dtypes
from jax._src import test_util as jtu
from jax.experimental import pallas as pl
import jax.numpy as jnp
import numpy as np
if sys.platform != "win32":
from jax.experimental.pallas import triton as plgpu
else:
plgpu = None
config.parse_flags_with_absl()
intx = dtypes.default_int_dtype()
floatx = dtypes.default_float_dtype()
@jtu.with_config(jax_traceback_filtering="off")
class PallasBaseTest(jtu.JaxTestCase):
INTERPRET = False
def setUp(self):
if jtu.test_device_matches(["cpu"]):
if not self.INTERPRET:
self.skipTest("On CPU the test works only in interpret mode")
elif jtu.test_device_matches(["gpu"]):
if jtu.test_device_matches(["cuda"]) and \
not jtu.is_cuda_compute_capability_at_least("9.0"):
self.skipTest("Only works on GPU with capability >= sm90")
if plgpu is None:
self.skipTest("plgpu not available on this platform")
else:
self.skipTest("Test only works on CPU and GPU")
super().setUp()
def pallas_call(self, *args, **kwargs):
# Force the use of the Triton backend.
kwargs.setdefault("compiler_params", plgpu.CompilerParams())
return pl.pallas_call(*args, **kwargs, interpret=self.INTERPRET)
DTYPE_LIST = [jnp.float32, jnp.float16, jnp.bfloat16,
jnp.float8_e4m3fn, jnp.float8_e5m2]
class TritonPallasTest(PallasBaseTest):
INTERPRET = False
@parameterized.product(src_dtype=DTYPE_LIST, dst_dtype=DTYPE_LIST)
def test_fp_dtype_cast(self, src_dtype, dst_dtype):
if src_dtype == dst_dtype:
self.skipTest("No need to test the same dtype")
if dtypes.itemsize_bits(src_dtype) == 8 and dtypes.itemsize_bits(dst_dtype) == 8:
self.skipTest("Not casting between 8-bit types")
def body(x_ref, y_ref):
y_ref[...] = x_ref[...].astype(dst_dtype)
x = 10 * jax.random.normal(jax.random.key(0), (64, 64), dtype=src_dtype)
y = self.pallas_call(body,
in_specs=[pl.BlockSpec((64, 64), lambda i: (0, 0))],
out_specs=pl.BlockSpec((64, 64), lambda i: (0, 0)),
out_shape=jax.ShapeDtypeStruct((64, 64), dst_dtype),
grid=(1,),
)(x)
self.assertEqual(y.dtype, dst_dtype)
self.assertArraysEqual(y, x.astype(dst_dtype))
@parameterized.named_parameters(
("add_i32", "atomic_add", np.array([1, 2, 3, 4], np.int32), np.sum),
("max_i32", "atomic_max", np.array([1, 2, 3, 4], np.int32), np.max),
("min_i32", "atomic_min", np.array([1, 2, 3, 4], np.int32), np.min),
("add_f16", "atomic_add", np.array([1, 2, 3, 4], np.float16), np.sum),
("add_f32", "atomic_add", np.array([1, 2, 3, 4], np.float32), np.sum),
("max_f32", "atomic_max", np.array([1, 2, 3, 4], np.float32), np.max),
("min_f32", "atomic_min", np.array([1, 2, 3, 4], np.float32), np.min),
)
def test_scalar_atomic(self, op, value, numpy_op):
op = getattr(plgpu, op)
@functools.partial(
self.pallas_call,
out_shape=jax.ShapeDtypeStruct((), value.dtype),
grid=value.shape[0],
input_output_aliases={1: 0},
)
def atomic_kernel(x_ref, _, o_ref):
pid = pl.program_id(axis=0)
op(o_ref, (), x_ref[pid])
if op == plgpu.atomic_add:
neutral = np.array(0, dtype=value.dtype)
elif op == plgpu.atomic_max:
if np.issubdtype(value.dtype, np.integer):
neutral = np.array(np.iinfo(value.dtype).min, value.dtype)
else:
# JAX on ROCm does not currently handle atomic fmin/fmax correctly
if jtu.test_device_matches(["rocm"]):
self.skipTest("Atomic fmin/fmax not currently supported on ROCm.")
neutral = np.array(-float("inf"), value.dtype)
elif op == plgpu.atomic_min:
if np.issubdtype(value.dtype, np.integer):
neutral = np.array(np.iinfo(value.dtype).max, value.dtype)
else:
# JAX on ROCm does not currently handle atomic fmin/fmax correctly
if jtu.test_device_matches(["rocm"]):
self.skipTest("Atomic fmin/fmax not currently supported on ROCm.")
neutral = np.array(float("inf"), value.dtype)
elif op == plgpu.atomic_or:
neutral = np.array(False, value.dtype)
else:
raise NotImplementedError()
out = atomic_kernel(value, neutral)
np.testing.assert_allclose(out, numpy_op(value))
@parameterized.parameters((0,), (1,))
def test_array_atomic_add(self, axis):
m, n = 32, 8
if axis == 0:
grid = m
else:
grid = n
out_shape = jax.ShapeDtypeStruct((n if axis == 0 else m,), floatx)
@functools.partial(
self.pallas_call,
out_shape=out_shape,
grid=grid,
input_output_aliases={1: 0},
)
def reduce(x_ref, _, y_ref):
i = pl.program_id(axis=0)
if axis == 0:
idx = (i, jnp.arange(n))
else:
idx = (jnp.arange(m), i)
x = x_ref[idx]
plgpu.atomic_add(y_ref, (jnp.arange(y.shape[0]),), x)
x = jax.random.normal(jax.random.key(0), (m, n))
y = jnp.zeros(out_shape.shape, out_shape.dtype)
y = reduce(x, y)
y_ref = np.sum(x, axis=axis)
np.testing.assert_allclose(y, y_ref, atol=1e-2, rtol=1e-2)
@parameterized.parameters(
(0, 0, 1),
(0, 1, 1),
(1, 0, 1),
(1, 1, 1),
(2, 1, 1),
(2, 1, 1),
)
def test_atomic_cas(self, init_value, cmp, new_value):
if jax.config.x64_enabled:
self.skipTest("Not supported in 64-bit mode")
@functools.partial(
self.pallas_call,
out_shape=(
jax.ShapeDtypeStruct((), intx),
jax.ShapeDtypeStruct((), intx),
),
input_output_aliases={0: 0},
)
def swap(_, lock_ref, out_ref):
out_ref[()] = plgpu.atomic_cas(lock_ref, cmp, new_value)
lock, out = swap(init_value)
np.testing.assert_allclose(
lock, new_value if cmp == init_value else init_value
)
np.testing.assert_allclose(out, init_value)
@parameterized.parameters(1, 2, 3, 4, 8)
def test_atomic_counter(self, num_threads):
if self.INTERPRET:
self.skipTest("While loop not supported in interpret mode.")
if jax.config.x64_enabled:
self.skipTest("Not supported in 64-bit mode")
@functools.partial(
self.pallas_call,
out_shape=(
jax.ShapeDtypeStruct((), intx),
jax.ShapeDtypeStruct((), intx),
),
input_output_aliases={0: 0, 1: 1},
grid=(num_threads,),
)
def increment(_, __, lock_ref, counter_ref):
def _cond(_):
return plgpu.atomic_cas(lock_ref, 0, 1) == 1
lax.while_loop(_cond, lambda a: a, 0)
counter_ref[...] += 1
plgpu.atomic_xchg(lock_ref, (), 0)
lock, count = increment(0, 0)
np.testing.assert_allclose(lock, 0)
np.testing.assert_allclose(count, num_threads)
@parameterized.product(
size=[1, 2, 64, 129, 1021],
block_size=[1, 2, 32, 64, 128],
)
def test_masked_load_store(self, size, block_size):
@functools.partial(
self.pallas_call,
out_shape=(jax.ShapeDtypeStruct((size,), floatx)),
grid=pl.cdiv(size, block_size),
)
def kernel(x_ref, o_ref):
idx = pl.program_id(0) * block_size + jnp.arange(
block_size, dtype=jnp.int32
)
mask = idx < x_ref.shape[0]
x = plgpu.load(x_ref.at[idx], mask=mask)
plgpu.store(o_ref.at[idx], x + 1.0, mask=mask)
key = jax.random.key(0)
x = jax.random.normal(key, (size,))
np.testing.assert_allclose(kernel(x), x + 1.0, atol=1e-5, rtol=1e-5)
def test_masked_oob_load_store_slice(self):
n = 16
@functools.partial(
self.pallas_call,
out_shape=(jax.ShapeDtypeStruct((n,), floatx)),
)
def masked_oob_load_store_slice(x_ref, mask_ref, start_idx_ref, o_ref):
x = plgpu.load(
x_ref.at[pl.ds(start_idx_ref[()], n)], mask=mask_ref[:], other=-1.0
)
o_ref[...] = x
x = jax.random.normal(jax.random.key(0), (n,))
slice_start = jax.random.randint(jax.random.key(2), (), 1, n)
indices = jnp.arange(n) + slice_start
mask = indices < n
out = masked_oob_load_store_slice(x, mask, slice_start)
o_new = jnp.where(mask, x[indices], jnp.full_like(x, -1.0))
np.testing.assert_array_equal(out, o_new)
@parameterized.parameters(
((16, 32), (16,)),
((16, 32), (16, 16)),
)
def test_invalid_broadcasted_load(self, x_shape, mask_shape):
if self.INTERPRET:
self.skipTest("No broadcasting checks in pl.load in interpret mode")
@functools.partial(
self.pallas_call, out_shape=jax.ShapeDtypeStruct((), jnp.float32)
)
def kernel(x_ref, mask_ref, o_ref):
del o_ref # Unused.
plgpu.load(x_ref, mask=mask_ref[:])
x = jnp.ones(x_shape, dtype=jnp.float32)
mask = jnp.ones(mask_shape, dtype=jnp.bool_)
with self.assertRaisesRegex(ValueError, "Cannot broadcast"):
kernel(x, mask)
@parameterized.parameters("float16", "bfloat16", "float32")
def test_approx_tanh(self, dtype):
if self.INTERPRET:
self.skipTest("approx_tanh is not supported in interpret mode")
if (dtype == "bfloat16" and
not jtu.is_cuda_compute_capability_at_least("9.0")):
self.skipTest("tanh.approx.bf16 requires a GPU with capability >= sm90")
@functools.partial(
self.pallas_call, out_shape=jax.ShapeDtypeStruct((4,), dtype),
)
def kernel(x_ref, o_ref):
o_ref[...] = plgpu.approx_tanh(x_ref[...])
x = jnp.asarray([-1, 0.42, 0.24, 1]).astype(dtype)
# We upcast to float32 because NumPy <2.0 does not handle custom dtypes
# properly. See https://github.com/jax-ml/jax/issues/11014.
np.testing.assert_allclose(
kernel(x).astype(jnp.float32),
jnp.tanh(x).astype(jnp.float32),
atol=5e-3,
rtol=5e-3,
)
def test_elementwise_inline_asm(self):
if self.INTERPRET:
self.skipTest(
"elementwise_inline_asm is not supported in interpret mode"
)
if jtu.is_device_rocm():
self.skipTest("elementwise_inline_asm is not currently "
"supported on ROCm")
@functools.partial(
self.pallas_call,
out_shape=jax.ShapeDtypeStruct((256,), jnp.float16),
)
def kernel(x_ref, o_ref):
[o_ref[...]] = plgpu.elementwise_inline_asm(
"tanh.approx.f16x2 $0, $1;",
args=[x_ref[...]],
constraints="=r,r",
pack=2,
result_shape_dtypes=[jax.ShapeDtypeStruct(x_ref.shape, x_ref.dtype)],
)
x = jnp.arange(256).astype(jnp.float16)
np.testing.assert_allclose(kernel(x), jnp.tanh(x), atol=5e-3, rtol=5e-3)
def test_debug_barrier(self):
if self.INTERPRET:
self.skipTest("debug_barrier is not supported in interpret mode")
@functools.partial(
self.pallas_call,
out_shape=jax.ShapeDtypeStruct((2,), jnp.float32),
)
def kernel(x_ref, o_ref):
o_ref[...] = x_ref[...]
plgpu.debug_barrier()
x = jnp.array([4.2, 2.4]).astype(jnp.float32)
np.testing.assert_array_equal(kernel(x), x)
def test_debug_print(self):
if jtu.test_device_matches(["gpu"]):
self.skipTest("This test flakes on gpu")
@functools.partial(
self.pallas_call,
out_shape=jax.ShapeDtypeStruct((2,), jnp.float32),
compiler_params=plgpu.CompilerParams(num_warps=1, num_stages=1),
)
def kernel(x_ref, o_ref):
pl.debug_print("It works!")
x = jnp.array([4.2, 2.4]).astype(jnp.float32)
with jtu.capture_stdout() as output:
jax.block_until_ready(kernel(x))
jax.effects_barrier()
self.assertIn("It works!", output())
@unittest.skipIf(
sys.platform == "win32",
"plgpu.CompilerParams unavailable on Windows",
)
def test_debug_print_with_values(self):
if jtu.test_device_matches(["gpu"]):
self.skipTest("This test flakes on gpu")
@functools.partial(
self.pallas_call,
out_shape=jax.ShapeDtypeStruct((2,), jnp.float32),
compiler_params=plgpu.CompilerParams(
num_warps=1, num_stages=1
),
)
def kernel(x_ref, o_ref):
pl.debug_print("x[0] =", x_ref[0])
x = jnp.array([4.2, 2.4]).astype(jnp.float32)
with jtu.capture_stdout() as output:
jax.block_until_ready(kernel(x))
jax.effects_barrier()
self.assertIn("x[0] = 4.2", output())
@parameterized.named_parameters(*[
(f"m_{m}_n_{n}_k_{k}_dtype_{dtype}_bm_{block_size_m}_"
f"bn_{block_size_n}_bk_{block_size_k}_gm_{group_size_m}", m, n, k, dtype,
block_size_m, block_size_n, block_size_k, group_size_m)
for m in [512, 1024]
for k in [512]
for n in [512, 1024]
for dtype in ["float32", "float16"]
for block_size_m in [64, 128]
for block_size_n in [64, 128]
for block_size_k in [32]
for group_size_m in [8]
if block_size_m <= m and block_size_n <= n and block_size_k <= k
])
def test_matmul(self, m, n, k, dtype, bm, bn, bk, gm):
if jtu.test_device_matches(["tpu"]) and not self.INTERPRET:
self.skipTest("On TPU the test works only in interpret mode")
k1, k2 = jax.random.split(jax.random.key(0))
x = jax.random.normal(k1, (m, k), dtype=dtype)
y = jax.random.normal(k2, (k, n), dtype=dtype)
out = matmul(x, y, bm=bm, bn=bn, bk=bk, gm=gm,
interpret=self.INTERPRET)
expected = jnp.matmul(
x, y, preferred_element_type=jnp.float32).astype(dtype)
np.testing.assert_allclose(out, expected, atol=0.05, rtol=0.05)
@parameterized.named_parameters(*(
dict(
testcase_name=f"{batch_size}_{size}_{block_size}_{dtype}",
batch_size=batch_size,
size=size,
block_size=block_size,
dtype=dtype,
)
for batch_size in [1, 2, 4, 23]
for size in [1, 2, 129, 255, 256]
for block_size in [1, 2, 32, 64, 128, 256]
for dtype in ["float32"]
if size < block_size
))
def test_softmax(self, batch_size, size, block_size, dtype):
@functools.partial(
self.pallas_call,
out_shape=jax.ShapeDtypeStruct((batch_size, size), dtype),
grid=batch_size,
)
def softmax(x_ref, o_ref):
row_idx = pl.program_id(0)
x_idx = jnp.arange(block_size)
row_idxs = (row_idx, x_idx)
mask = x_idx < x_ref.shape[1]
row = plgpu.load(x_ref.at[row_idxs], mask=mask, other=-float("inf"))
row_minus_max = row - jnp.max(row, axis=0)
numerator = jnp.exp(row_minus_max)
denominator = jnp.sum(numerator, axis=0)
softmax_output = numerator / denominator
plgpu.store(o_ref.at[row_idxs], softmax_output, mask=mask)
key = jax.random.key(0)
x = jax.random.normal(key, [batch_size, size], dtype=dtype)
np.testing.assert_allclose(
softmax(x), jax.nn.softmax(x, axis=-1), atol=1e-5, rtol=1e-5
)
@functools.partial(
jax.jit, static_argnames=["bm", "bn", "gm", "bk", "interpret", "debug"]
)
def matmul(x, y, *, bm, bn, gm, bk, interpret, debug=False):
m, n, k = x.shape[0], y.shape[1], x.shape[1]
@functools.partial(
pl.pallas_call,
out_shape=jax.ShapeDtypeStruct((m, n), jnp.float32),
grid=pl.cdiv(m, bm) * pl.cdiv(n, bn),
interpret=interpret,
debug=debug,
compiler_params=plgpu.CompilerParams(),
)
def matmul_kernel(x_ref, y_ref, o_ref):
pid = pl.program_id(axis=0).astype(intx)
num_pid_m = m // bm
num_pid_n = n // bn
num_pid_in_group = gm * num_pid_n
group_id = lax.div(pid, num_pid_in_group)
first_pid_m = group_id * gm
group_size_m = jnp.minimum(num_pid_m - first_pid_m, gm)
pid_m = first_pid_m + lax.rem(pid, group_size_m)
pid_n = lax.div(lax.rem(pid, num_pid_in_group), group_size_m)
idx_m = pid_m * bm + jnp.arange(bm)
idx_n = pid_n * bn + jnp.arange(bn)
idx_m = plgpu.max_contiguous(pl.multiple_of(idx_m, bm), bm)
idx_n = plgpu.max_contiguous(pl.multiple_of(idx_n, bn), bn)
acc = jnp.zeros((bm, bn), dtype=jnp.float32)
def body(i, acc):
idx_k = i * bk + jnp.arange(bk)
x_idx = (
lax.broadcast_in_dim(idx_m, (bm, bk), (0,)),
lax.broadcast_in_dim(idx_k, (bm, bk), (1,)),
)
y_idx = (
lax.broadcast_in_dim(idx_k, (bk, bn), (0,)),
lax.broadcast_in_dim(idx_n, (bk, bn), (1,)),
)
x_block, y_block = x_ref[x_idx], y_ref[y_idx]
out = pl.dot(x_block, y_block)
return acc + out
acc = lax.fori_loop(0, k // bk, body, acc).astype(o_ref.dtype)
o_idx = (
lax.broadcast_in_dim(idx_m, (bm, bn), (0,)),
lax.broadcast_in_dim(idx_n, (bm, bn), (1,)),
)
o_ref[o_idx] = acc
return matmul_kernel(x, y)
if __name__ == "__main__":
absltest.main()
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/pallas/triton_pallas_test.py",
"license": "Apache License 2.0",
"lines": 452,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/scheduling_groups_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from absl.testing import absltest
import jax
import jax.numpy as jnp
from jax._src import test_util as jtu
from jax.experimental.scheduling_groups import (
scheduling_group, xla_metadata_call)
jax.config.parse_flags_with_absl()
class SchedulingGroupsTest(jtu.JaxTestCase):
def test_basic(self):
a = 1.
b = 2.
x = 3.
y = 4.
@scheduling_group(name="grp0:sub_grp0")
def fn0(a, b):
c = jnp.add(a, b)
return c
@scheduling_group(name="grp0:sub_grp1")
def fn1(x, y):
z = jnp.multiply(x, y)
return z
@scheduling_group(name="grp0")
def fn(a, b, x, y):
c = fn0(a, b)
z = fn1(x, y)
return c, z
lowered = jax.jit(fn).lower(a, b, x, y)
self.assertIn('scheduling_group = "grp0"', lowered.as_text())
def test_transforms(self):
@scheduling_group(name='yash')
def f(x):
return 2 * x
ans = jax.vmap(f)(jnp.arange(3.))
self.assertAllClose(ans, 2. * jnp.arange(3.))
ans = jax.grad(f)(3.)
self.assertAllClose(ans, 2., check_dtypes=False)
# TODO(yashkatariya): Enable this on TPU once XLA:TPU knows about inlineable
@jtu.run_on_devices('cpu')
def test_xla_metadata_call_inlineable(self):
inp = jnp.arange(8.)
@xla_metadata_call(inlineable="false")
def g(x):
return x * 2
@jax.jit
def f(x):
y = g(x)
return jnp.sin(y).sum()
f(inp) # doesn't crash
lowered = jax.jit(jax.grad(f)).lower(inp)
self.assertIn('inlineable = "false"', lowered.as_text())
compiled = lowered.compile()
self.assertIn('inlineable="false"', compiled.as_text())
compiled(inp) # doesn't crash
@jtu.run_on_devices('cpu')
def test_xla_metadata_call_inlineable_remat_in_scan(self):
@xla_metadata_call(inlineable="false")
def f(x, y):
return x + y, (x + y).sum()
def g(x, use_remat=True):
maybe_rematted_f = jax.remat(f) if use_remat else f
_, b = maybe_rematted_f(x, x)
return b
grad_f = jax.jit(jax.grad(g), static_argnums=(1,))
grads = grad_f(jnp.array(5.0), use_remat=False)
self.assertIsNotNone(grads)
grads = grad_f(jnp.array(5.0), use_remat=True)
self.assertIsNotNone(grads)
@jtu.run_on_devices('cpu')
def test_xla_metadata_call_deduplication(self):
inp = jnp.arange(8.)
@xla_metadata_call(inlineable='false')
@jax.jit
def g(x):
return x * 2
def f(x):
y = g(x)
z = g(y)
return z.sum()
f(inp) # doesn't crash
lowered = jax.jit(f).lower(inp)
self.assertEqual(
lowered.as_text().count('func.func private @xla_metadata_call'), 1)
compiled = lowered.compile()
compiled(inp) # doesn't crash
jax.jit(jax.grad(f))(inp) # doesn't crash
lowered = jax.jit(jax.grad(f)).lower(inp)
self.assertEqual(
lowered.as_text().count('func.func private @xla_metadata_call'), 1)
compiled = lowered.compile()
compiled(inp) # doesn't crash
@jtu.run_on_devices('cpu')
def test_xla_metadata_call_deduplication_remat(self):
inp = jnp.arange(8.)
@jax.remat
@xla_metadata_call(inlineable='false')
@jax.jit
def g(x):
return x * 2
def f(x):
y = g(x)
z = g(y)
return z.sum()
f(inp) # doesn't crash
lowered = jax.jit(f).lower(inp)
self.assertEqual(
lowered.as_text().count('func.func private @xla_metadata_call'), 1)
compiled = lowered.compile()
compiled(inp) # doesn't crash
jax.jit(jax.value_and_grad(f))(inp) # doesn't crash
lowered = jax.jit(jax.value_and_grad(f)).lower(inp)
self.assertEqual(
lowered.as_text().count('func.func private @xla_metadata_call'), 2)
compiled = lowered.compile()
compiled(inp) # doesn't crash
@jtu.run_on_devices('cpu')
def test_xla_metadata_call_deduplication_kwargs(self):
inp = jnp.arange(8.)
@xla_metadata_call(inlineable='false')
@jax.jit
def g(x):
return x * 2
def f(x):
y = g(x=x)
z = g(x=y)
return z.sum()
f(inp) # doesn't crash
if __name__ == '__main__':
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/scheduling_groups_test.py",
"license": "Apache License 2.0",
"lines": 141,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:tests/traceback_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import contextlib
import traceback
import unittest
from absl.testing import absltest
import jax
from jax._src import test_util as jtu
from jax._src.lib import _jax
from jax._src.lib import jaxlib_extension_version
import jax.numpy as jnp
import numpy as np
Traceback = _jax.Traceback
Frame = _jax.Frame
if jaxlib_extension_version >= 399:
TracebackScope = _jax.TracebackScope
@contextlib.contextmanager
def tracebacks(enabled=True):
"""Context manager that enables or disables traceback collection."""
saved = _jax.tracebacks_enabled()
_jax.set_tracebacks_enabled(enabled)
try:
yield
finally:
_jax.set_tracebacks_enabled(saved)
class TracebackTest(absltest.TestCase):
def testNoTracebacksIfDisabled(self):
with tracebacks(enabled=False):
self.assertEqual(None, Traceback.get_traceback())
buffer = jnp.array(7, np.int32)
self.assertEqual(None, buffer.traceback)
e = jax.jit(lambda x: x + 1).lower(1).compile().runtime_executable()
self.assertEqual(None, e.traceback)
def assertIsTracebackContaining(self, tb, function):
self.assertIsInstance(tb, Traceback)
self.assertIn(function, str(tb))
self.assertTrue(any(f.function_name == function for f in tb.frames))
def testTracebacks(self):
with tracebacks(enabled=True):
fn = "TracebackTest.testTracebacks"
tb = Traceback.get_traceback()
self.assertIsTracebackContaining(tb, fn)
buffer = jnp.array(7, np.int32)
self.assertIsTracebackContaining(buffer.traceback, fn)
e = jax.jit(lambda x: x + 1).lower(1).compile().runtime_executable()
self.assertIsTracebackContaining(e.traceback, fn)
def testNestedFunction(self):
def AFunction():
def AnotherFunction():
return Traceback.get_traceback()
return AnotherFunction()
with tracebacks(enabled=True):
tb = AFunction()
self.assertIsInstance(tb, Traceback)
frames = tb.frames
fn = "TracebackTest.testNestedFunction.<locals>.AFunction"
i = next(i for (i, f) in enumerate(frames) if f.function_name == fn)
self.assertEqual(
frames[i - 1].function_name,
"TracebackTest.testNestedFunction.<locals>.AFunction.<locals>.AnotherFunction",
)
self.assertEqual(
frames[i + 1].function_name, "TracebackTest.testNestedFunction"
)
def testPythonTracebackHasCorrectLineNumbers(self):
def B():
return Traceback.get_traceback()
def A():
return B()
tb = A().as_python_traceback()
for frame, lineno in traceback.walk_tb(tb):
if frame.f_code.co_name == "A":
line = A.__code__.co_firstlineno
self.assertBetween(lineno, line, line + 2)
elif frame.f_code.co_name == "B":
line = B.__code__.co_firstlineno
self.assertBetween(lineno, line, line + 2)
def testAccessingLocalsDoesNotCrash(self):
# https://github.com/google/jax/issues/16027
tb = Traceback.get_traceback()
python_tb = tb.as_python_traceback()
for frame, _ in traceback.walk_tb(python_tb):
_ = frame.f_locals # should not crash
@unittest.skipIf(jaxlib_extension_version < 409, reason="Needs newer jaxlib")
def testAdd(self):
def FooFn():
return Traceback.get_traceback()
def BarFn():
return Traceback.get_traceback()
with tracebacks(enabled=True):
tb1 = FooFn()
tb2 = BarFn()
tb3 = tb1 + tb2
self.assertEqual(len(tb3.frames), len(tb1.frames) + len(tb2.frames))
self.assertEqual(tb3.frames[0].function_name, tb1.frames[0].function_name)
self.assertEqual(
tb3.frames[-1].function_name, tb2.frames[-1].function_name)
with self.assertRaises(TypeError):
_ = tb1 + 1
def testEmptyConstructor(self):
tb = Traceback()
self.assertIsInstance(tb, Traceback)
self.assertEmpty(tb.frames)
self.assertEqual(str(tb), "")
def testTracebackFromFrames(self):
def FooFn(x):
return x + 1
def BarFn(y):
y = y + 1
y = y + 2
return y * 2
frame_foo = Frame(
__file__,
FooFn.__code__.co_name,
FooFn.__code__.co_firstlineno,
FooFn.__code__.co_firstlineno + 1,
)
frame_bar = Frame(
__file__,
BarFn.__code__.co_name,
BarFn.__code__.co_firstlineno,
BarFn.__code__.co_firstlineno + 2,
)
frames = [frame_foo, frame_bar]
tb = Traceback.traceback_from_frames(frames)
with self.subTest("WalkDoesNotError"):
for frame, _ in traceback.walk_tb(tb):
_ = frame.f_locals # should not crash
with self.subTest("TracebackCorrectness"):
tb_string = traceback.format_tb(tb)
# The traceback should have the format:
# File <this file>, line N in BarFn
# y = y + 2
# File <this file>, line N in FooFn
# return x + 1
self.assertLen(tb_string, len(frames))
bar_frame = tb_string[0].split("\n")
self.assertEndsWith(bar_frame[0], "BarFn")
self.assertEqual(bar_frame[1].strip(), "y = y + 2")
foo_frame = tb_string[1].split("\n")
self.assertEndsWith(foo_frame[0], "FooFn")
self.assertEqual(foo_frame[1].strip(), "return x + 1")
class TracebackScopeTest(absltest.TestCase):
def testTracebackScope(self):
if jaxlib_extension_version < 399:
self.skipTest("TracebackScope requires jaxlib >= 399")
def Inner():
return Traceback.get_traceback()
def Outer():
with TracebackScope():
return Inner()
with tracebacks(enabled=True):
tb = Outer()
self.assertIsInstance(tb, Traceback)
function_names = [f.function_name for f in tb.frames]
self.assertIn(
"TracebackScopeTest.testTracebackScope.<locals>.Inner", function_names
)
self.assertNotIn(
"TracebackScopeTest.testTracebackScope.<locals>.Outer", function_names
)
def testTracebackScopeNesting(self):
if jaxlib_extension_version < 399:
self.skipTest("TracebackScope requires jaxlib >= 399")
def Inner():
return Traceback.get_traceback()
def Level2():
with TracebackScope():
return Inner()
def Level1():
with TracebackScope():
return Level2()
with tracebacks(enabled=True):
tb = Level1()
function_names = [f.function_name for f in tb.frames]
# Both Level2 and Level1 should be excluded because both have scopes.
self.assertIn(
"TracebackScopeTest.testTracebackScopeNesting.<locals>.Inner", function_names
)
self.assertNotIn(
"TracebackScopeTest.testTracebackScopeNesting.<locals>.Level2", function_names
)
self.assertNotIn(
"TracebackScopeTest.testTracebackScopeNesting.<locals>.Level1", function_names
)
# Specifically, the traceback should only have the 'Inner' frame.
self.assertLen(tb.frames, 1)
self.assertEqual(tb.frames[0].function_name, "TracebackScopeTest.testTracebackScopeNesting.<locals>.Inner")
if __name__ == "__main__":
absltest.main(testLoader=jtu.JaxTestLoader())
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/traceback_test.py",
"license": "Apache License 2.0",
"lines": 201,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:jax/extend/mlir/dialects/mpmd.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ruff: noqa: F403
from jaxlib.mlir.dialects.mpmd import *
| {
"repo_id": "jax-ml/jax",
"file_path": "jax/extend/mlir/dialects/mpmd.py",
"license": "Apache License 2.0",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
jax-ml/jax:tests/multiprocess/axis_index_test.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import jax
from jax import lax
from jax._src import test_multiprocess as jt_multiprocess
import numpy as np
class AxisIndexTest(jt_multiprocess.MultiProcessTest):
def test(self):
f = jax.pmap(lambda _: lax.axis_index("i"), axis_name="i")
n = jax.local_device_count()
xs = np.arange(n)
out = f(xs * 0)
np.testing.assert_equal(out, xs + (n * jax.process_index()))
if __name__ == "__main__":
jt_multiprocess.main()
| {
"repo_id": "jax-ml/jax",
"file_path": "tests/multiprocess/axis_index_test.py",
"license": "Apache License 2.0",
"lines": 26,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
jax-ml/jax:jax/scipy/stats/gumbel_l.py | # Copyright 2025 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Note: import <name> as <name> is required for names to be exported.
# See PEP 484 & https://github.com/jax-ml/jax/issues/7570
from jax._src.scipy.stats.gumbel_l import (
logpdf as logpdf,
pdf as pdf,
logcdf as logcdf,
cdf as cdf,
ppf as ppf,
sf as sf,
logsf as logsf
)
| {
"repo_id": "jax-ml/jax",
"file_path": "jax/scipy/stats/gumbel_l.py",
"license": "Apache License 2.0",
"lines": 24,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
jumpserver/jumpserver:apps/i18n/ci_translate.py | #!/usr/bin/env python3
import argparse
import asyncio
import json
import os
import subprocess
import tempfile
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import polib
from _translator.base import BaseTranslateManager
from _translator.utils import build_translator
REPO_ROOT = Path(__file__).resolve().parents[2]
I18N_ROOT = Path(__file__).resolve().parent
def _run_git(args: list[str]) -> str:
out = subprocess.check_output(["git", *args], cwd=REPO_ROOT, text=True)
return out
def _git_show_text(rev: str, relpath: str) -> str | None:
try:
return _run_git(["show", f"{rev}:{relpath}"])
except subprocess.CalledProcessError:
return None
def _read_json_text(path: Path) -> dict:
if not path.exists():
return {}
return json.loads(path.read_text(encoding="utf-8"))
def _read_json_text_from_git(rev: str, relpath: str) -> dict:
txt = _git_show_text(rev, relpath)
if not txt:
return {}
return json.loads(txt)
def _read_po_from_text(txt: str) -> polib.POFile:
with tempfile.NamedTemporaryFile("w+", encoding="utf-8", suffix=".po", delete=False) as f:
f.write(txt)
f.flush()
name = f.name
try:
return polib.pofile(name)
finally:
try:
os.unlink(name)
except OSError:
pass
def _read_po_from_git(rev: str, relpath: str) -> polib.POFile | None:
txt = _git_show_text(rev, relpath)
if not txt:
return None
return _read_po_from_text(txt)
def _read_po_from_fs(path: Path) -> polib.POFile:
return polib.pofile(str(path))
def _changed_keys_json(base: dict, head: dict) -> set[str]:
changed: set[str] = set()
for k, v in head.items():
if not k:
continue
if k not in base or base.get(k) != v:
changed.add(k)
return changed
def _po_translated_dict(po: polib.POFile) -> dict[str, str]:
return {e.msgid: e.msgstr for e in po.translated_entries()}
def _changed_msgids_po(base_po: polib.POFile | None, head_po: polib.POFile) -> set[str]:
base = _po_translated_dict(base_po) if base_po else {}
head = _po_translated_dict(head_po)
changed: set[str] = set()
for msgid, msgstr in head.items():
if msgid not in base or base.get(msgid) != msgstr:
changed.add(msgid)
return changed
@dataclass(frozen=True)
class WorkItem:
# For json: kind="json", src points to zh.json
# For po: kind="po", src points to zh/LC_MESSAGES/{django.po|djangojs.po}
kind: str
src_relpath: str
class _BulkTranslator(BaseTranslateManager):
# Reuse BaseTranslateManager.bulk_translate
pass
async def _translate_json_item(
translator,
module_dir: Path,
zh_relpath: str,
changed_keys: set[str],
overwrite: bool,
):
zh_path = REPO_ROOT / zh_relpath
zh_dict = _read_json_text(zh_path)
if not zh_dict:
return
mgr = _BulkTranslator(str(module_dir), translator)
for file_prefix, target_lang in mgr.LANG_MAPPER.items():
file_prefix = file_prefix.lower()
if file_prefix == "zh":
continue
target_path = module_dir / f"{file_prefix}.json"
target_dict = _read_json_text(target_path)
to_update: dict[str, str] = {}
for k in changed_keys:
if k not in zh_dict:
continue
if overwrite or k not in target_dict:
to_update[k] = zh_dict[k]
if not to_update:
continue
translated = await mgr.bulk_translate(to_update, target_lang)
target_dict.update(translated)
target_path.write_text(
json.dumps(target_dict, ensure_ascii=False, sort_keys=True, indent=4) + "\n",
encoding="utf-8",
)
async def _translate_po_item(
translator,
module_dir: Path,
po_name: str,
zh_relpath: str,
changed_msgids: set[str],
overwrite: bool,
):
zh_path = REPO_ROOT / zh_relpath
if not zh_path.exists():
return
zh_po = _read_po_from_fs(zh_path)
zh_dict = _po_translated_dict(zh_po)
if not zh_dict:
return
mgr = _BulkTranslator(str(module_dir), translator)
for file_prefix, target_lang in mgr.LANG_MAPPER.items():
if file_prefix == "zh":
continue
target_path = module_dir / file_prefix / "LC_MESSAGES" / po_name
if not target_path.exists():
continue
trans_po = _read_po_from_fs(target_path)
to_update: dict[str, str] = {}
for msgid in changed_msgids:
if msgid not in zh_dict:
continue
entry = trans_po.find(msgid)
if not entry:
continue
if overwrite or (not entry.msgstr) or ("fuzzy" in entry.flags):
to_update[msgid] = zh_dict[msgid]
if not to_update:
continue
translated = await mgr.bulk_translate(to_update, target_lang)
for msgid, msgstr in translated.items():
entry = trans_po.find(msgid)
if not entry:
continue
entry.flags = []
entry.previous_msgid = None
entry.msgstr = msgstr
trans_po.save(str(target_path))
def _discover_work_items_from_diff(base: str, head: str) -> list[WorkItem]:
changed_files = _run_git(["diff", "--name-only", f"{base}..{head}"]).splitlines()
items: list[WorkItem] = []
for p in changed_files:
if not p.startswith("apps/i18n/"):
continue
# json modules
if p.endswith("/zh.json") and "/LC_MESSAGES/" not in p:
items.append(WorkItem(kind="json", src_relpath=p))
continue
# gettext sources
if p.endswith("/zh/LC_MESSAGES/django.po") or p.endswith("/zh/LC_MESSAGES/djangojs.po"):
items.append(WorkItem(kind="po", src_relpath=p))
continue
# de-dup
uniq: dict[tuple[str, str], WorkItem] = {(i.kind, i.src_relpath): i for i in items}
return list(uniq.values())
async def run_pr(base: str, head: str, overwrite: bool):
translator = build_translator()
items = _discover_work_items_from_diff(base, head)
if not items:
print("No i18n source changes detected; skip.")
return
for item in items:
if item.kind == "json":
module_dir = (REPO_ROOT / item.src_relpath).parent
base_dict = _read_json_text_from_git(base, item.src_relpath)
head_dict = _read_json_text(REPO_ROOT / item.src_relpath)
changed = _changed_keys_json(base_dict, head_dict)
if not changed:
continue
await _translate_json_item(translator, module_dir, item.src_relpath, changed, overwrite=overwrite)
elif item.kind == "po":
src_path = REPO_ROOT / item.src_relpath
# .../core/zh/LC_MESSAGES/django.po -> module_dir=.../core
module_dir = src_path.parents[2]
po_name = src_path.name
base_po = _read_po_from_git(base, item.src_relpath)
head_po = _read_po_from_fs(src_path)
changed = _changed_msgids_po(base_po, head_po)
if not changed:
continue
await _translate_po_item(
translator,
module_dir,
po_name=po_name,
zh_relpath=item.src_relpath,
changed_msgids=changed,
overwrite=overwrite,
)
async def run_full():
# Full run: reuse existing translate logic, but load by file path
# to avoid name conflicts with any third-party "translate" package.
import importlib.util
translate_path = I18N_ROOT / "translate.py"
spec = importlib.util.spec_from_file_location("jumpserver_i18n_translate", translate_path)
if not spec or not spec.loader:
raise RuntimeError(f"Failed to load translate module from {translate_path}")
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
translator = build_translator()
manager = mod.Translate(translator)
await manager.run()
def main(argv: Iterable[str] | None = None):
parser = argparse.ArgumentParser(description="JumpServer i18n CI translator")
parser.add_argument("--mode", choices=["full", "pr"], required=True)
parser.add_argument("--base", help="Base git sha (PR only)")
parser.add_argument("--head", help="Head git sha (PR only)", default="HEAD")
parser.add_argument(
"--overwrite",
action=argparse.BooleanOptionalAction,
default=True,
help="Overwrite existing translations for changed source keys/msgids",
)
args = parser.parse_args(list(argv) if argv is not None else None)
if args.mode == "full":
asyncio.run(run_full())
return
if not args.base:
raise SystemExit("--base is required for --mode pr")
asyncio.run(run_pr(args.base, args.head, overwrite=args.overwrite))
if __name__ == "__main__":
main()
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/i18n/ci_translate.py",
"license": "GNU General Public License v3.0",
"lines": 236,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
jumpserver/jumpserver:apps/jumpserver/vendor.py | import json
from pathlib import Path
from django.conf import settings
from django.contrib.staticfiles import finders
from django.templatetags.static import static
DEFAULT_VENDOR = "jumpserver"
DEFAULT_LOGIN_TEMPLATE = "authentication/login.html"
DEFAULT_THEME = "classic_green"
VENDOR_THEMES_DIR = settings.VENDOR_TEMPLATES_DIR / "themes"
def is_default_vendor() -> bool:
return settings.VENDOR == DEFAULT_VENDOR
def find_theme_path(theme_dirs, theme_name: str) -> Path | None:
filename = f"{theme_name}.json"
for d in theme_dirs:
p = d / filename
if p.is_file():
return p
def _default_theme_dir() -> Path:
data_dir = Path(settings.BASE_DIR)
return data_dir / "xpack" / "plugins" / "interface" / "themes"
def _build_theme() -> str:
return DEFAULT_THEME if is_default_vendor() else settings.VENDOR
def _build_theme_info() -> dict:
default_theme_path = find_theme_path([_default_theme_dir()], DEFAULT_THEME)
search_dirs = [_default_theme_dir()] if is_default_vendor() else [
settings.VENDOR_TEMPLATES_DIR / 'themes',
_default_theme_dir(),
]
theme_name = DEFAULT_THEME if is_default_vendor() else settings.VENDOR
theme_path = find_theme_path(search_dirs, theme_name) or default_theme_path
return json.loads(theme_path.read_text(encoding="utf-8"))
def _build_vendor_info() -> dict:
if is_default_vendor():
return {}
info_path = settings.VENDOR_TEMPLATES_DIR / "info.json"
if not info_path.exists():
return {}
return json.loads(info_path.read_text(encoding="utf-8"))
def _build_vendor_info_value(key: str, default=None):
info = _build_vendor_info()
return info.get(key, default)
def _build_asset(filename: str) -> str:
if is_default_vendor():
return static(filename)
vendor_path = f"{settings.VENDOR}/{filename}"
if finders.find(vendor_path):
return static(vendor_path)
return static(filename)
VENDOR_BUILDERS = {
"theme": _build_theme,
"theme_info": _build_theme_info,
"logo_logout": lambda: _build_asset("img/logo.png"),
"logo_index": lambda: _build_asset("img/logo_text_white.png"),
"login_image": lambda: _build_asset("img/login_image.png"),
"favicon": lambda: _build_asset("img/facio.ico"),
"logo_white": lambda: _build_asset("img/logo_white.png"),
"logo_text_white": lambda: _build_asset("img/logo_text_white.png"),
"login_title": lambda: _build_vendor_info_value("login_title"),
"footer_content": lambda: _build_vendor_info_value("footer_content"),
}
def get_vendor_value(kind: str, default=None):
builder = VENDOR_BUILDERS.get(kind)
if not builder:
return default
value = builder()
return default if value is None else value
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/jumpserver/vendor.py",
"license": "GNU General Public License v3.0",
"lines": 66,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:utils/disable_user.py | import os
import sys
import django
if os.path.exists('../apps'):
sys.path.insert(0, '../apps')
elif os.path.exists('./apps'):
sys.path.insert(0, './apps')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "jumpserver.settings")
os.environ.setdefault("DJANGO_DEBUG_SHELL", "1")
django.setup()
from users.models import User
def disable_user(username):
user = User.objects.filter(username=username).first()
if not user:
print("Not found user: ", username)
return
print("Disable user: ", username)
user.is_active = False
user.save(update_fields=['is_active'])
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python disable_user.py <username>")
sys.exit(1)
username = sys.argv[1]
disable_user(username)
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "utils/disable_user.py",
"license": "GNU General Public License v3.0",
"lines": 25,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:apps/common/drf/throttling.py | # -*- coding: utf-8 -*-
from rest_framework.throttling import SimpleRateThrottle
class RateThrottle(SimpleRateThrottle):
def __init__(self):
# Override the usual SimpleRateThrottle, because we can't determine
# the rate until called by the view.
pass
def allow_request(self, request, view):
if getattr(request, "user", None) and request.user.is_authenticated:
if getattr(request.user, "is_service_account", False):
self.scope = "service_account"
else:
self.scope = "user"
else:
self.scope = "anon"
self.rate = self.get_rate()
self.num_requests, self.duration = self.parse_rate(self.rate)
return super().allow_request(request, view)
def get_cache_key(self, request, view):
if request.user and request.user.is_authenticated:
ident = request.user.pk
else:
ident = self.get_ident(request)
return self.cache_format % {
'scope': self.scope,
'ident': ident
}
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/common/drf/throttling.py",
"license": "GNU General Public License v3.0",
"lines": 27,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:apps/authentication/decorators.py | """
This module provides decorators to handle redirect URLs during the authentication flow:
1. pre_save_next_to_session: Captures and stores the intended next URL before redirecting to auth provider
2. redirect_to_pre_save_next_after_auth: Redirects to the stored next URL after successful authentication
3. post_save_next_to_session: Copies the stored next URL to session['next'] after view execution
"""
from urllib.parse import urlparse
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from functools import wraps
from common.utils import get_logger, safe_next_url
from .const import USER_LOGIN_GUARD_VIEW_REDIRECT_FIELD
logger = get_logger(__file__)
__all__ = [
'pre_save_next_to_session', 'redirect_to_pre_save_next_after_auth',
'post_save_next_to_session_if_guard_redirect'
]
# Session key for storing the redirect URL after authentication
AUTH_SESSION_NEXT_URL_KEY = 'auth_next_url'
def pre_save_next_to_session(get_next_url=None):
"""
Decorator to capture and store the 'next' parameter into session BEFORE view execution.
This decorator is applied to the authentication request view to preserve the user's
intended destination URL before redirecting to the authentication provider.
Args:
get_next_url: Optional callable that extracts the next URL from request.
Default: lambda req: req.GET.get('next')
Usage:
# Use default (request.GET.get('next'))
@pre_save_next_to_session()
def get(self, request):
pass
# Custom extraction from POST data
@pre_save_next_to_session(get_next_url=lambda req: req.POST.get('next'))
def post(self, request):
pass
# Custom extraction from both GET and POST
@pre_save_next_to_session(
get_next_url=lambda req: req.GET.get('next') or req.POST.get('next')
)
def get(self, request):
pass
Example flow:
User accesses: /auth/oauth2/?next=/dashboard/
↓ (decorator saves '/dashboard/' to session)
Redirected to OAuth2 provider for authentication
"""
# Default function to extract next URL from request.GET
if get_next_url is None:
get_next_url = lambda req: req.GET.get('next')
def decorator(view_func):
@wraps(view_func)
def wrapper(self, request, *args, **kwargs):
next_url = get_next_url(request)
if next_url:
request.session[AUTH_SESSION_NEXT_URL_KEY] = next_url
logger.debug(f"[Auth] Saved next_url to session: {next_url}")
return view_func(self, request, *args, **kwargs)
return wrapper
return decorator
def redirect_to_pre_save_next_after_auth(view_func):
"""
Decorator to redirect to the previously saved 'next' URL after successful authentication.
This decorator is applied to the authentication callback view. After the user successfully
authenticates, if a 'next' URL was previously saved in the session (by pre_save_next_to_session),
the user will be redirected to that URL instead of the default redirect location.
Conditions for redirect:
- User must be authenticated (request.user.is_authenticated)
- Session must contain the saved next URL (AUTH_SESSION_NEXT_URL_KEY)
- The next URL must not be '/' (avoid unnecessary redirects)
- The next URL must pass security validation (safe_next_url)
If any condition fails, returns the original view response.
Usage:
@redirect_to_pre_save_next_after_auth
def get(self, request):
# Process authentication callback
if user_authenticated:
auth.login(request, user)
return HttpResponseRedirect(default_url)
Example flow:
User redirected back from OAuth2 provider: /auth/oauth2/callback/?code=xxx
↓ (view processes authentication, user becomes authenticated)
Decorator checks session for saved next URL
↓ (finds '/dashboard/' in session)
Redirects to: /dashboard/
↓ (clears saved URL from session)
"""
@wraps(view_func)
def wrapper(self, request, *args, **kwargs):
# Execute the original view method first
response = view_func(self, request, *args, **kwargs)
# Check if user has been authenticated
if request.user and request.user.is_authenticated:
# Check if session contains a saved next URL
saved_next_url = request.session.get(AUTH_SESSION_NEXT_URL_KEY)
if saved_next_url and saved_next_url != '/':
# Validate the URL for security
safe_url = safe_next_url(saved_next_url, request=request)
if safe_url:
# Clear the saved URL from session (one-time use)
request.session.pop(AUTH_SESSION_NEXT_URL_KEY, None)
logger.debug(f"[Auth] Redirecting authenticated user to saved next_url: {safe_url}")
return HttpResponseRedirect(safe_url)
# Return the original response if no redirect conditions are met
return response
return wrapper
def post_save_next_to_session_if_guard_redirect(view_func):
"""
Decorator to copy AUTH_SESSION_NEXT_URL_KEY to session['next'] after view execution,
but only if redirecting to login-guard view.
This decorator is applied AFTER view execution. It copies the value from
AUTH_SESSION_NEXT_URL_KEY (internal storage) to 'next' (standard session key)
for use by downstream code.
Only sets the 'next' session key when the response is a redirect to guard-view
(i.e., response with redirect status code and location path matching login-guard view URL).
Usage:
@post_save_next_to_session_if_guard_redirect
def get(self, request):
# Process the request and return response
if some_condition:
return self.redirect_to_guard_view() # Decorator will copy next to session
return HttpResponseRedirect(url) # Decorator won't copy if not to guard-view
Example flow:
View executes and returns redirect to guard view
↓ (response is redirect with 'login-guard' in Location)
Decorator checks if response is redirect to guard-view and session has saved next URL
↓ (copies AUTH_SESSION_NEXT_URL_KEY to session['next'])
User is redirected to guard-view with 'next' available in session
"""
@wraps(view_func)
def wrapper(self, request, *args, **kwargs):
# Execute the original view method
response = view_func(self, request, *args, **kwargs)
# Check if response is a redirect to guard view
# Redirect responses typically have status codes 301, 302, 303, 307, 308
is_guard_redirect = False
if hasattr(response, 'status_code') and response.status_code in (301, 302, 303, 307, 308):
# Check if the redirect location is to guard view
location = response.get('Location', '')
if location:
# Extract path from location URL (handle both absolute and relative URLs)
parsed_url = urlparse(location)
path = parsed_url.path
# Check if path matches guard view URL pattern
guard_view_url = reverse('authentication:login-guard')
if path == guard_view_url:
is_guard_redirect = True
# Only set 'next' if response is a redirect to guard view
if is_guard_redirect:
# Copy AUTH_SESSION_NEXT_URL_KEY to 'next' if it exists
saved_next_url = request.session.get(AUTH_SESSION_NEXT_URL_KEY)
if saved_next_url:
# 这里 'next' 是 UserLoginGuardView.redirect_field_name
request.session[USER_LOGIN_GUARD_VIEW_REDIRECT_FIELD] = saved_next_url
logger.debug(f"[Auth] Copied {AUTH_SESSION_NEXT_URL_KEY} to 'next' in session: {saved_next_url}")
return response
return wrapper
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/authentication/decorators.py",
"license": "GNU General Public License v3.0",
"lines": 158,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
jumpserver/jumpserver:apps/authentication/backends/oauth2_provider/signal_handlers.py | from django.db.models.signals import post_delete
from django.dispatch import receiver
from django.core.cache import cache
from django.conf import settings
from oauth2_provider.models import get_application_model
from .utils import clear_oauth2_authorization_server_view_cache
__all__ = ['on_oauth2_provider_application_deleted']
Application = get_application_model()
@receiver(post_delete, sender=Application)
def on_oauth2_provider_application_deleted(sender, instance, **kwargs):
if instance.name == settings.OAUTH2_PROVIDER_JUMPSERVER_CLIENT_NAME:
clear_oauth2_authorization_server_view_cache()
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/authentication/backends/oauth2_provider/signal_handlers.py",
"license": "GNU General Public License v3.0",
"lines": 12,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:apps/authentication/backends/oauth2_provider/urls.py | # -*- coding: utf-8 -*-
#
from django.urls import path
from oauth2_provider import views as op_views
from . import views
urlpatterns = [
path("authorize/", op_views.AuthorizationView.as_view(), name="authorize"),
path("token/", op_views.TokenView.as_view(), name="token"),
path("revoke/", op_views.RevokeTokenView.as_view(), name="revoke-token"),
path(".well-known/oauth-authorization-server", views.OAuthAuthorizationServerView.as_view(), name="oauth-authorization-server"),
]
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/authentication/backends/oauth2_provider/urls.py",
"license": "GNU General Public License v3.0",
"lines": 11,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:apps/authentication/backends/oauth2_provider/utils.py | from django.conf import settings
from django.core.cache import cache
from oauth2_provider.models import get_application_model
from common.utils import get_logger
logger = get_logger(__name__)
def get_or_create_jumpserver_client_application():
"""Auto get or create OAuth2 JumpServer Client application."""
Application = get_application_model()
application, created = Application.objects.get_or_create(
name=settings.OAUTH2_PROVIDER_JUMPSERVER_CLIENT_NAME,
defaults={
'client_type': Application.CLIENT_PUBLIC,
'authorization_grant_type': Application.GRANT_AUTHORIZATION_CODE,
'redirect_uris': settings.OAUTH2_PROVIDER_CLIENT_REDIRECT_URI,
'skip_authorization': True,
}
)
return application
CACHE_OAUTH_SERVER_VIEW_KEY_PREFIX = 'oauth2_provider_metadata'
def clear_oauth2_authorization_server_view_cache():
logger.info("Clearing OAuth2 Authorization Server Metadata view cache")
cache_key = f'views.decorators.cache.cache_page.{CACHE_OAUTH_SERVER_VIEW_KEY_PREFIX}.GET*'
cache.delete_pattern(cache_key) | {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/authentication/backends/oauth2_provider/utils.py",
"license": "GNU General Public License v3.0",
"lines": 23,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:apps/authentication/backends/oauth2_provider/views.py | from django.views.generic import View
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from django.urls import reverse
from oauth2_provider.settings import oauth2_settings
from typing import List, Dict, Any
from .utils import get_or_create_jumpserver_client_application, CACHE_OAUTH_SERVER_VIEW_KEY_PREFIX
@method_decorator(csrf_exempt, name='dispatch')
@method_decorator(cache_page(timeout=60 * 60 * 24, key_prefix=CACHE_OAUTH_SERVER_VIEW_KEY_PREFIX), name='dispatch')
class OAuthAuthorizationServerView(View):
"""
OAuth 2.0 Authorization Server Metadata Endpoint
RFC 8414: https://datatracker.ietf.org/doc/html/rfc8414
This endpoint provides machine-readable information about the
OAuth 2.0 authorization server's configuration.
"""
def get_base_url(self, request) -> str:
scheme = 'https' if request.is_secure() else 'http'
host = request.get_host()
return f"{scheme}://{host}"
def get_supported_scopes(self) -> List[str]:
scopes_config = oauth2_settings.SCOPES
if isinstance(scopes_config, dict):
return list(scopes_config.keys())
return []
def get_metadata(self, request) -> Dict[str, Any]:
base_url = self.get_base_url(request)
application = get_or_create_jumpserver_client_application()
metadata = {
"issuer": base_url,
"client_id": application.client_id if application else "Not found any application.",
"authorization_endpoint": base_url + reverse('authentication:oauth2-provider:authorize'),
"token_endpoint": base_url + reverse('authentication:oauth2-provider:token'),
"revocation_endpoint": base_url + reverse('authentication:oauth2-provider:revoke-token'),
"response_types_supported": ["code"],
"grant_types_supported": ["authorization_code", "refresh_token"],
"scopes_supported": self.get_supported_scopes(),
"token_endpoint_auth_methods_supported": ["none"],
"revocation_endpoint_auth_methods_supported": ["none"],
"code_challenge_methods_supported": ["S256"],
"response_modes_supported": ["query"],
}
if hasattr(oauth2_settings, 'ACCESS_TOKEN_EXPIRE_SECONDS'):
metadata["token_expires_in"] = oauth2_settings.ACCESS_TOKEN_EXPIRE_SECONDS
if hasattr(oauth2_settings, 'REFRESH_TOKEN_EXPIRE_SECONDS'):
if oauth2_settings.REFRESH_TOKEN_EXPIRE_SECONDS:
metadata["refresh_token_expires_in"] = oauth2_settings.REFRESH_TOKEN_EXPIRE_SECONDS
return metadata
def get(self, request, *args, **kwargs):
metadata = self.get_metadata(request)
response = JsonResponse(metadata)
self.add_cors_headers(response)
return response
def options(self, request, *args, **kwargs):
response = JsonResponse({})
self.add_cors_headers(response)
return response
@staticmethod
def add_cors_headers(response):
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Methods'] = 'GET, OPTIONS'
response['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
response['Access-Control-Max-Age'] = '3600' | {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/authentication/backends/oauth2_provider/views.py",
"license": "GNU General Public License v3.0",
"lines": 66,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:apps/acls/api/data_masking.py | from orgs.mixins.api import OrgBulkModelViewSet
from .common import ACLUserFilterMixin
from ..models import DataMaskingRule
from .. import serializers
__all__ = ['DataMaskingRuleViewSet']
class DataMaskingRuleFilter(ACLUserFilterMixin):
class Meta:
model = DataMaskingRule
fields = ('name',)
class DataMaskingRuleViewSet(OrgBulkModelViewSet):
model = DataMaskingRule
filterset_class = DataMaskingRuleFilter
search_fields = ('name',)
serializer_class = serializers.DataMaskingRuleSerializer
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/acls/api/data_masking.py",
"license": "GNU General Public License v3.0",
"lines": 14,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:apps/acls/serializers/data_masking.py | from django.utils.translation import gettext_lazy as _
from acls.models import MaskingMethod, DataMaskingRule
from common.serializers.fields import LabeledChoiceField
from common.serializers.mixin import CommonBulkModelSerializer
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
from .base import BaseUserAssetAccountACLSerializer as BaseSerializer
__all__ = ['DataMaskingRuleSerializer']
class DataMaskingRuleSerializer(BaseSerializer, BulkOrgResourceModelSerializer):
masking_method = LabeledChoiceField(
choices=MaskingMethod.choices, default=MaskingMethod.fixed_char, label=_('Masking Method')
)
class Meta(BaseSerializer.Meta):
model = DataMaskingRule
fields = BaseSerializer.Meta.fields + ['fields_pattern', 'masking_method', 'mask_pattern']
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/acls/serializers/data_masking.py",
"license": "GNU General Public License v3.0",
"lines": 14,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:apps/libs/ansible/modules/mssql_script.py | #!/usr/bin/python
# Modified from ansible_collections.community.general.mssql_script
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = r"""
module: mssql_script
short_description: Execute SQL scripts on a MSSQL database
version_added: "1.0.0"
description:
- Execute SQL scripts on a MSSQL database.
extends_documentation_fragment:
- community.general.attributes
attributes:
check_mode:
support: partial
details:
- The script is not be executed in check mode.
diff_mode:
support: none
options:
name:
description: Database to run script against.
aliases: [db]
default: ''
type: str
login_user:
description: The username used to authenticate with.
type: str
login_password:
description: The password used to authenticate with.
type: str
login_host:
description: Host running the database.
type: str
required: true
login_port:
description: Port of the MSSQL server. Requires O(login_host) be defined as well.
default: 1433
type: int
script:
description:
- The SQL script to be executed.
- Script can contain multiple SQL statements. Multiple Batches can be separated by V(GO) command.
- Each batch must return at least one result set.
required: true
type: str
transaction:
description:
- If transactional mode is requested, start a transaction and commit the change only if the script succeed. Otherwise,
rollback the transaction.
- If transactional mode is not requested (default), automatically commit the change.
type: bool
default: false
version_added: 8.4.0
output:
description:
- With V(default) each row is returned as a list of values. See RV(query_results).
- Output format V(dict) returns dictionary with the column names as keys. See RV(query_results_dict).
- V(dict) requires named columns to be returned by each query otherwise an error is thrown.
choices: ["dict", "default"]
default: 'default'
type: str
params:
description: |-
Parameters passed to the script as SQL parameters.
(Query V('SELECT %(name\)s"') with V(example: '{"name": "John Doe"}).)'.
type: dict
notes:
- Requires the pymssql Python package on the remote host. For Ubuntu, this is as easy as C(pip install pymssql) (See M(ansible.builtin.pip)).
requirements:
- pymssql
author:
- Kris Budde (@kbudde)
"""
EXAMPLES = r"""
- name: Check DB connection
community.general.mssql_script:
login_user: "{{ mssql_login_user }}"
login_password: "{{ mssql_login_password }}"
login_host: "{{ mssql_host }}"
login_port: "{{ mssql_port }}"
db: master
script: "SELECT 1"
- name: Query with parameter
community.general.mssql_script:
login_user: "{{ mssql_login_user }}"
login_password: "{{ mssql_login_password }}"
login_host: "{{ mssql_host }}"
login_port: "{{ mssql_port }}"
script: |
SELECT name, state_desc FROM sys.databases WHERE name = %(dbname)s
params:
dbname: msdb
register: result_params
- assert:
that:
- result_params.query_results[0][0][0][0] == 'msdb'
- result_params.query_results[0][0][0][1] == 'ONLINE'
- name: Query within a transaction
community.general.mssql_script:
login_user: "{{ mssql_login_user }}"
login_password: "{{ mssql_login_password }}"
login_host: "{{ mssql_host }}"
login_port: "{{ mssql_port }}"
script: |
UPDATE sys.SomeTable SET desc = 'some_table_desc' WHERE name = %(dbname)s
UPDATE sys.AnotherTable SET desc = 'another_table_desc' WHERE name = %(dbname)s
transaction: true
params:
dbname: msdb
- name: two batches with default output
community.general.mssql_script:
login_user: "{{ mssql_login_user }}"
login_password: "{{ mssql_login_password }}"
login_host: "{{ mssql_host }}"
login_port: "{{ mssql_port }}"
script: |
SELECT 'Batch 0 - Select 0'
SELECT 'Batch 0 - Select 1'
GO
SELECT 'Batch 1 - Select 0'
register: result_batches
- assert:
that:
- result_batches.query_results | length == 2 # two batch results
- result_batches.query_results[0] | length == 2 # two selects in first batch
- result_batches.query_results[0][0] | length == 1 # one row in first select
- result_batches.query_results[0][0][0] | length == 1 # one column in first row
- result_batches.query_results[0][0][0][0] == 'Batch 0 - Select 0' # each row contains a list of values.
- name: two batches with dict output
community.general.mssql_script:
login_user: "{{ mssql_login_user }}"
login_password: "{{ mssql_login_password }}"
login_host: "{{ mssql_host }}"
login_port: "{{ mssql_port }}"
output: dict
script: |
SELECT 'Batch 0 - Select 0' as b0s0
SELECT 'Batch 0 - Select 1' as b0s1
GO
SELECT 'Batch 1 - Select 0' as b1s0
register: result_batches_dict
- assert:
that:
- result_batches_dict.query_results_dict | length == 2 # two batch results
- result_batches_dict.query_results_dict[0] | length == 2 # two selects in first batch
- result_batches_dict.query_results_dict[0][0] | length == 1 # one row in first select
- result_batches_dict.query_results_dict[0][0][0]['b0s0'] == 'Batch 0 - Select 0' # column 'b0s0' of first row
"""
RETURN = r"""
query_results:
description: List of batches (queries separated by V(GO) keyword).
type: list
elements: list
returned: success and O(output=default)
sample:
[
[
[
[
"Batch 0 - Select 0"
]
],
[
[
"Batch 0 - Select 1"
]
]
],
[
[
[
"Batch 1 - Select 0"
]
]
]
]
contains:
queries:
description:
- List of result sets of each query.
- If a query returns no results, the results of this and all the following queries are not included in the output.
- Use the V(GO) keyword in O(script) to separate queries.
type: list
elements: list
contains:
rows:
description: List of rows returned by query.
type: list
elements: list
contains:
column_value:
description:
- List of column values.
- Any non-standard JSON type is converted to string.
type: list
example: ["Batch 0 - Select 0"]
returned: success, if output is default
query_results_dict:
description: List of batches (queries separated by V(GO) keyword).
type: list
elements: list
returned: success and O(output=dict)
sample:
[
[
[
[
"Batch 0 - Select 0"
]
],
[
[
"Batch 0 - Select 1"
]
]
],
[
[
[
"Batch 1 - Select 0"
]
]
]
]
contains:
queries:
description:
- List of result sets of each query.
- If a query returns no results, the results of this and all the following queries are not included in the output.
Use V(GO) keyword to separate queries.
type: list
elements: list
contains:
rows:
description: List of rows returned by query.
type: list
elements: list
contains:
column_dict:
description:
- Dictionary of column names and values.
- Any non-standard JSON type is converted to string.
type: dict
example: {"col_name": "Batch 0 - Select 0"}
returned: success, if output is dict
"""
import pymssql
from ansible.module_utils.basic import AnsibleModule
import json
def clean_output(o):
return str(o)
def main():
module_args = dict(
name=dict(aliases=['db'], default=''),
login_user=dict(type='str', required=False, default=None),
login_password=dict(no_log=True),
login_host=dict(required=True),
login_port=dict(type='int', default=1433),
script=dict(required=True),
output=dict(default='default', choices=['dict', 'default']),
params=dict(type='dict'),
transaction=dict(type='bool', default=True),
tds_version=dict(type='str', required=False, default=None),
encryption=dict(type='str', required=False, default=None)
)
result = dict(
changed=False,
)
module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=True
)
db = module.params['name']
login_user = module.params['login_user']
login_password = module.params['login_password']
login_host = module.params['login_host']
login_port = module.params['login_port']
script = module.params['script']
output = module.params['output']
sql_params = module.params['params']
transaction = module.params['transaction']
# TODO 待 ansible 官方支持这两个参数
tds_version = module.params['tds_version'] or None
encryption = module.params['encryption'] or None
login_querystring = login_host
if login_port != 1433:
login_querystring = "%s:%s" % (login_host, login_port)
if login_user is not None and login_password is None:
module.fail_json(
msg="when supplying login_user argument, login_password must also be provided")
try:
conn = pymssql.connect(
user=login_user, password=login_password, host=login_querystring,
database=db, encryption=encryption, tds_version=tds_version)
cursor = conn.cursor()
except Exception as e:
if "Unknown database" in str(e):
errno, errstr = e.args
module.fail_json(msg="ERROR: %s %s" % (errno, errstr))
else:
module.fail_json(
msg="unable to connect, check login_user and login_password are correct, or alternatively check your "
"@sysconfdir@/freetds.conf / ${HOME}/.freetds.conf")
# If transactional mode is requested, start a transaction
conn.autocommit(not transaction)
query_results_key = 'query_results'
if output == 'dict':
cursor = conn.cursor(as_dict=True)
query_results_key = 'query_results_dict'
# Process the script into batches
queries = []
current_batch = []
for statement in script.splitlines(True):
# Ignore the Byte Order Mark, if found
if statement.strip() == '\uFEFF':
continue
# Assume each 'GO' is on its own line but may have leading/trailing whitespace
# and be of mixed-case
if statement.strip().upper() != 'GO':
current_batch.append(statement)
else:
queries.append(''.join(current_batch))
current_batch = []
if len(current_batch) > 0:
queries.append(''.join(current_batch))
result['changed'] = True
if module.check_mode:
module.exit_json(**result)
query_results = []
for query in queries:
# Catch and exit on any bad query errors
try:
cursor.execute(query, sql_params)
qry_result = []
rows = cursor.fetchall()
while rows:
qry_result.append(rows)
rows = cursor.fetchall()
query_results.append(qry_result)
except Exception as e:
# We know we executed the statement so this error just means we have no resultset
# which is ok (eg UPDATE/INSERT)
if (
type(e).__name__ == 'OperationalError' and
str(e) == 'Statement not executed or executed statement has no resultset'
):
query_results.append([])
else:
# Rollback transaction before failing the module in case of error
if transaction:
conn.rollback()
error_msg = '%s: %s' % (type(e).__name__, str(e))
module.fail_json(msg="query failed", query=query, error=error_msg, **result)
# Commit transaction before exiting the module in case of no error
if transaction:
conn.commit()
# ensure that the result is json serializable
qry_results = json.loads(json.dumps(query_results, default=clean_output))
result[query_results_key] = qry_results
module.exit_json(**result)
if __name__ == '__main__':
main()
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/libs/ansible/modules/mssql_script.py",
"license": "GNU General Public License v3.0",
"lines": 363,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
jumpserver/jumpserver:apps/jumpserver/api/search.py | import re
from django.contrib.postgres.search import SearchVector
from rest_framework.views import APIView
from rest_framework.response import Response
from django.conf import settings
from django.db.models import Q
from rest_framework.permissions import IsAuthenticated
class GlobalSearchView(APIView):
limits = 5
permission_classes = [IsAuthenticated]
def get_models(self):
from users.models import User, UserGroup
from assets.models import Asset
from accounts.models import Account
from perms.models import AssetPermission
return [
[User, ['name', 'username']],
[UserGroup, ['name', 'comment']],
[Asset, ['name', 'address']],
[Account, ['name', 'username']],
[AssetPermission, ['name', 'comment']],
]
def search_model(self, model, fields, keyword):
queryset = model.objects.all()
if hasattr(model, 'get_queryset'):
queryset = model.get_queryset()
if settings.DB_ENGINE == 'postgres':
qs = model.objects.annotate(
search=SearchVector(*fields),
).filter(search=keyword)
else:
q = Q()
for field in fields:
q |= Q(**{field + '__icontains': keyword})
qs = queryset.filter(q)
return qs[:self.limits]
def get_result(self, model, fields, item, keyword):
d = {
"id": item.id, "name": item.name,
"model": model.__name__, "model_label": model._meta.verbose_name,
}
content = ""
value_list = [item.name]
for field in fields:
field_label = model._meta.get_field(field).verbose_name
value = getattr(item, field)
if value in value_list:
continue
value_list.append(value)
if content:
continue
content += f"{field_label}: {value} "
display = str(item).replace(item.name, '').replace('(', '').replace(')', '')
if display not in value:
content += f" {display} "
d["content"] = content
return d
def get(self, request):
q = request.query_params.get("q", "").strip()
models = self.get_models()
results = []
for model, fields in models:
perm = model._meta.app_label + '.' + 'view_' + model._meta.model_name
if not request.user.has_perm(perm):
continue
qs = self.search_model(model, fields, q)
for item in qs:
d = self.get_result(model, fields, item, q)
results.append(d)
return Response(results) | {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/jumpserver/api/search.py",
"license": "GNU General Public License v3.0",
"lines": 70,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:apps/reports/api/accouts/account.py | # -*- coding: utf-8 -*-
#
from collections import defaultdict
from django.db.models import Count, Q, F, Value
from django.db.models.functions import Concat
from django.http import JsonResponse
from django.utils import timezone
from rest_framework.views import APIView
from accounts.const import Source
from accounts.models import Account, AccountTemplate
from assets.const import Connectivity
from common.permissions import IsValidLicense
from common.utils import lazyproperty
from rbac.permissions import RBACPermission
from reports.api.assets.base import group_stats
from reports.mixins import DateRangeMixin
__all__ = ['AccountStatisticApi']
class AccountStatisticApi(DateRangeMixin, APIView):
http_method_names = ['get']
rbac_perms = {
'GET': 'rbac.view_accountstatisticsreport',
}
permission_classes = [RBACPermission, IsValidLicense]
@lazyproperty
def base_qs(self):
return Account.objects.all()
@lazyproperty
def template_qs(self):
return AccountTemplate.objects.all()
def get_change_secret_account_metrics(self):
filtered_queryset = self.filter_by_date_range(self.base_qs, 'date_change_secret')
data = defaultdict(set)
for t, _id in filtered_queryset.values_list('date_change_secret', 'id'):
dt_local = timezone.localtime(t)
date_str = str(dt_local.date())
data[date_str].add(_id)
metrics = [len(data.get(str(d), set())) for d in self.date_range_list]
return metrics
def get(self, request, *args, **kwargs):
qs = self.base_qs
stats = qs.aggregate(
total=Count(1),
active=Count(1, filter=Q(is_active=True)),
connected=Count(1, filter=Q(connectivity=Connectivity.OK)),
su_from=Count(1, filter=Q(su_from__isnull=False)),
date_change_secret=Count(1, filter=Q(secret_reset=True)),
)
stats['template_total'] = self.template_qs.count()
source_pie_data = [
{'name': str(Source(source).label), 'value': total}
for source, total in
qs.values('source').annotate(
total=Count(1)
).values_list('source', 'total')
]
by_connectivity = group_stats(
qs, 'label', 'connectivity', Connectivity.as_dict(),
)
top_assets = qs.values('asset__name') \
.annotate(account_count=Count('id')) \
.order_by('-account_count')[:10]
top_version_accounts = qs.annotate(
display_key=Concat(
F('asset__name'),
Value('('),
F('username'),
Value(')')
)
).values('display_key', 'version').order_by('-version')[:10]
payload = {
'account_stats': stats,
'top_assets': list(top_assets),
'top_version_accounts': list(top_version_accounts),
'source_pie': source_pie_data,
'by_connectivity': by_connectivity,
'change_secret_account_metrics': {
'dates_metrics_date': self.dates_metrics_date,
'dates_metrics_total': self.get_change_secret_account_metrics(),
}
}
return JsonResponse(payload, status=200)
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/reports/api/accouts/account.py",
"license": "GNU General Public License v3.0",
"lines": 81,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:apps/reports/api/accouts/automation.py | # -*- coding: utf-8 -*-
#
from collections import defaultdict
from django.http import JsonResponse
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from rest_framework.views import APIView
from accounts.const import AutomationTypes
from accounts.models import ChangeSecretAutomation, PushAccountAutomation, BackupAccountAutomation, \
CheckAccountAutomation, GatherAccountsAutomation, AutomationExecution
from common.permissions import IsValidLicense
from rbac.permissions import RBACPermission
from reports.mixins import DateRangeMixin
__all__ = ['AccountAutomationApi']
class AccountAutomationApi(DateRangeMixin, APIView):
http_method_names = ['get']
rbac_perms = {
'GET': 'rbac.view_accountautomationreport',
}
permission_classes = [RBACPermission, IsValidLicense]
@property
def change_secret_qs(self):
return ChangeSecretAutomation.objects.all()
@property
def push_qs(self):
return PushAccountAutomation.objects.all()
@property
def backup_qs(self):
return BackupAccountAutomation.objects.all()
@property
def check_qs(self):
return CheckAccountAutomation.objects.all()
@property
def collect_qs(self):
return GatherAccountsAutomation.objects.all()
def get_execution_metrics(self):
executions = AutomationExecution.objects.filter(type__in=AutomationTypes.values)
qs = self.filter_by_date_range(executions, 'date_start')
types = set()
data = defaultdict(lambda: defaultdict(int))
for obj in qs:
tp = obj.type
if not tp:
continue
types.add(tp)
dt = obj.date_start
dt_local = timezone.localtime(dt)
date_str = str(dt_local.date())
data[date_str][tp] += 1
tp_map = defaultdict(list)
for d in self.date_range_list:
tp_data = data.get(str(d), {})
for tp in types:
tp_map[tp].append(tp_data.get(tp, 0))
metrics = {}
for tp, values in tp_map.items():
if tp == AutomationTypes.change_secret:
_tp = _('Account change secret')
else:
_tp = AutomationTypes(tp).label
metrics[str(_tp)] = values
return metrics
def get(self, request, *args, **kwargs):
stats = {
'push': self.push_qs.count(),
'check': self.check_qs.count(),
'backup': self.backup_qs.count(),
'collect': self.collect_qs.count(),
'change_secret': self.change_secret_qs.count(),
}
payload = {
'automation_stats': stats,
'execution_metrics': {
'dates_metrics_date': self.dates_metrics_date,
'data': self.get_execution_metrics()
},
}
return JsonResponse(payload, status=200)
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/reports/api/accouts/automation.py",
"license": "GNU General Public License v3.0",
"lines": 78,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:apps/reports/api/accouts/base.py | from django.db.models import Count, F
def group_stats(queryset, alias, key, label_map=None):
grouped = (
queryset
.exclude(**{f'{key}__isnull': True})
.values(**{alias: F(key)})
.annotate(total=Count('id'))
)
data = [
{
alias: val,
'total': cnt,
**({'label': label_map.get(val, val)} if label_map else {})
}
for val, cnt in grouped.values_list(alias, 'total')
]
return data
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/reports/api/accouts/base.py",
"license": "GNU General Public License v3.0",
"lines": 17,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:apps/reports/api/assets/activity.py | # -*- coding: utf-8 -*-
#
from collections import defaultdict
from django.db.models import Count
from django.http.response import JsonResponse
from rest_framework.views import APIView
from assets.const import AllTypes
from assets.models import Asset
from common.permissions import IsValidLicense
from common.utils import lazyproperty
from rbac.permissions import RBACPermission
from reports.api.assets.base import group_stats
from reports.mixins import DateRangeMixin
from terminal.const import LoginFrom
from terminal.models import Session
__all__ = ['AssetActivityApi']
class AssetActivityApi(DateRangeMixin, APIView):
http_method_names = ['get']
rbac_perms = {
'GET': 'rbac.view_assetactivityreport',
}
permission_classes = [RBACPermission, IsValidLicense]
def get_asset_login_metrics(self, queryset):
data = defaultdict(set)
for t, _id in queryset.values_list('date_start', 'id'):
date_str = str(t.date())
data[date_str].add(_id)
metrics = [len(data.get(str(d), set())) for d in self.date_range_list]
return metrics
@lazyproperty
def session_qs(self):
return Session.objects.all()
def get(self, request, *args, **kwargs):
qs = self.session_qs
qs = self.filter_by_date_range(qs, 'date_start')
all_type_dict = dict(AllTypes.choices())
stats = qs.aggregate(
total=Count(1),
asset_count=Count('asset_id', distinct=True),
user_count=Count('user_id', distinct=True),
)
asset_ids = {str(_id) for _id in qs.values_list('asset_id', flat=True).distinct()}
assets = Asset.objects.filter(id__in=asset_ids)
asset_login_by_protocol = group_stats(
qs, 'label', 'protocol'
)
asset_login_by_from = group_stats(
qs, 'label', 'login_from', LoginFrom.as_dict()
)
asset_by_type = group_stats(
assets, 'label', 'platform__type', all_type_dict,
)
payload = {
'session_stats': stats,
'asset_login_by_type': asset_by_type,
'asset_login_by_from': asset_login_by_from,
'asset_login_by_protocol': asset_login_by_protocol,
'asset_login_log_metrics': {
'dates_metrics_date': self.dates_metrics_date,
'dates_metrics_total': self.get_asset_login_metrics(qs),
}
}
return JsonResponse(payload, status=200)
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/reports/api/assets/activity.py",
"license": "GNU General Public License v3.0",
"lines": 63,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:apps/reports/api/assets/asset.py | # -*- coding: utf-8 -*-
#
from collections import defaultdict, OrderedDict
from django.db.models import Count, Q
from django.http import JsonResponse
from rest_framework.views import APIView
from assets.const import AllTypes, Connectivity, Category
from assets.models import Asset, Platform
from common.permissions import IsValidLicense
from common.utils import lazyproperty
from rbac.permissions import RBACPermission
from reports.mixins import DateRangeMixin
__all__ = ['AssetStatisticApi']
class AssetStatisticApi(DateRangeMixin, APIView):
http_method_names = ['get']
rbac_perms = {
'GET': 'rbac.view_assetstatisticsreport',
}
permission_classes = [RBACPermission, IsValidLicense]
@lazyproperty
def base_qs(self):
return Asset.objects.all()
def get_added_asset_metrics(self):
filtered_queryset = self.filter_by_date_range(self.base_qs, 'date_created')
data = defaultdict(set)
for t, _id in filtered_queryset.values_list('date_created', 'id'):
date_str = str(t.date())
data[date_str].add(_id)
metrics = [len(data.get(str(d), set())) for d in self.date_range_list]
return metrics
def get(self, request, *args, **kwargs):
qs = self.base_qs
all_type_dict = dict(AllTypes.choices())
stats = qs.aggregate(
total=Count(1),
active=Count(1, filter=Q(is_active=True)),
connected=Count(1, filter=Q(connectivity=Connectivity.OK)),
zone=Count(1, filter=Q(zone__isnull=False)),
directory_services=Count(1, filter=Q(directory_services__isnull=False)),
)
category_map = Category.as_dict()
category_type_map = defaultdict(list)
for d in AllTypes.types():
category_type_map[str(d['category'].label)].append(d['value'])
category_type_ids = defaultdict(lambda: defaultdict(set))
for _id, tp, category in (qs.select_related('platform')
.values_list('id', 'platform__type', 'platform__category')):
category_label = category_map.get(category, category)
category_type_ids[category_label][tp].add(_id)
by_type_category = defaultdict(list)
for k, v in category_type_ids.items():
by_type_category[k] = [
{
'label': all_type_dict.get(tp, tp),
'type': tp,
'total': len(_ids),
}
for tp, _ids in v.items()
]
sorted_category_assets = OrderedDict()
desired_order = [str(i['label']) for i in AllTypes.categories()]
for category in desired_order:
sorted_category_assets[category] = by_type_category.get(category, [])
stats.update({
'platform_count': Platform.objects.all().count(),
})
payload = {
'asset_stats': stats,
'assets_by_type_category': sorted_category_assets,
'added_asset_metrics': {
'dates_metrics_date': self.dates_metrics_date,
'dates_metrics_total': self.get_added_asset_metrics(),
}
}
return JsonResponse(payload, status=200)
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/reports/api/assets/asset.py",
"license": "GNU General Public License v3.0",
"lines": 75,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:apps/reports/api/assets/base.py | from django.db.models import Count, F
def group_stats(queryset, alias, key, label_map=None):
grouped = (
queryset
.exclude(**{f"{key}__isnull": True})
.annotate(**{alias: F(key)})
.values(alias)
.order_by(alias)
.annotate(total=Count(1))
)
data = [
{
alias: g[alias],
'total': g['total'],
**({'label': label_map.get(g[alias], g[alias])} if label_map else {})
}
for g in grouped
]
return data
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/reports/api/assets/base.py",
"license": "GNU General Public License v3.0",
"lines": 19,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:apps/reports/api/report.py | from rest_framework.generics import ListAPIView
from rest_framework.response import Response
__all__ = ['ReportViewSet']
class ReportViewSet(ListAPIView):
def list(self, request, *args, **kwargs):
return Response([])
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/reports/api/report.py",
"license": "GNU General Public License v3.0",
"lines": 6,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:apps/reports/api/users/change_password.py | # -*- coding: utf-8 -*-
#
from collections import defaultdict
from django.db.models import Count
from django.http.response import JsonResponse
from rest_framework.views import APIView
from audits.models import PasswordChangeLog
from common.permissions import IsValidLicense
from common.utils import lazyproperty, get_logger
from rbac.permissions import RBACPermission
from reports.mixins import DateRangeMixin
__all__ = ['UserChangeSecretApi']
logger = get_logger(__file__)
class UserChangeSecretApi(DateRangeMixin, APIView):
http_method_names = ['get']
rbac_perms = {
'GET': 'rbac.view_userchangepasswordreport',
}
permission_classes = [RBACPermission, IsValidLicense]
def get_change_password_metrics(self, queryset):
filtered_queryset = self.filter_by_date_range(queryset, 'datetime')
data = defaultdict(set)
for t, username in filtered_queryset.values_list('datetime', 'user'):
date_str = str(t.date())
data[date_str].add(username)
metrics = [len(data.get(str(d), set())) for d in self.date_range_list]
return metrics
@lazyproperty
def change_password_queryset(self):
queryset = PasswordChangeLog.objects.all()
return PasswordChangeLog.filter_queryset_by_org(queryset)
def get(self, request, *args, **kwargs):
data = {}
qs = self.filter_by_date_range(self.change_password_queryset, 'datetime')
total = qs.count()
change_password_top10_users = qs.values(
'user').annotate(count=Count('id')).order_by('-count')[:10]
change_password_top10_change_bys = qs.values(
'change_by').annotate(count=Count('id')).order_by('-count')[:10]
data['total_count_change_password'] = {
'total': total,
'user_total': qs.values('user').distinct().count(),
'change_by_total': qs.values('change_by').distinct().count(),
}
data['change_password_top10_users'] = list(change_password_top10_users)
data['change_password_top10_change_bys'] = list(change_password_top10_change_bys)
data['user_change_password_metrics'] = {
'dates_metrics_date': self.dates_metrics_date,
'dates_metrics_total': self.get_change_password_metrics(qs),
}
return JsonResponse(data, status=200)
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/reports/api/users/change_password.py",
"license": "GNU General Public License v3.0",
"lines": 51,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:apps/reports/api/users/user.py | # -*- coding: utf-8 -*-
#
from collections import defaultdict
from django.db.models import Count, Q
from django.http.response import JsonResponse
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from rest_framework.views import APIView
from audits.const import LoginStatusChoices
from audits.models import UserLoginLog
from common.permissions import IsValidLicense
from common.utils import lazyproperty
from rbac.permissions import RBACPermission
from reports.mixins import DateRangeMixin
from users.models import User, Source
__all__ = ['UserReportApi']
class UserReportApi(DateRangeMixin, APIView):
http_method_names = ['get']
rbac_perms = {
'GET': 'rbac.view_userloginreport',
}
permission_classes = [RBACPermission, IsValidLicense]
def get_user_login_metrics(self, queryset):
filtered_queryset = self.filter_by_date_range(queryset, 'datetime')
data = defaultdict(set)
for t, username in filtered_queryset.values_list('datetime', 'username'):
date_str = str(t.date())
data[date_str].add(username)
metrics = [len(data.get(str(d), set())) for d in self.date_range_list]
return metrics
def get_user_login_method_metrics(self, source_map):
filtered_queryset = self.filter_by_date_range(self.user_login_log_queryset, 'datetime')
backends = set()
data = defaultdict(lambda: defaultdict(set))
for t, username, backend in filtered_queryset.values_list('datetime', 'username', 'backend'):
backend = str(source_map.get(backend.lower(), backend))
backends.add(backend)
date_str = str(t.date())
data[date_str][backend].add(username)
metrics = defaultdict(list)
for t in self.date_range_list:
date_str = str(t)
for backend in backends:
username = data.get(date_str) if data.get(date_str) else {backend: set()}
metrics[backend].append(len(username.get(backend, set())))
return metrics
def get_user_login_time_metrics(self):
buckets = ['00:00-06:00', '06:00-12:00', '12:00-18:00', '18:00-24:00']
metrics = {k: 0 for k in buckets}
qs = self.filter_by_date_range(self.user_login_log_queryset, 'datetime').only('datetime')
for obj in qs:
dt = obj.datetime
dt_local = timezone.localtime(dt)
hour = dt_local.hour
metrics[buckets[hour // 6]] += 1
return metrics
@lazyproperty
def user_login_log_queryset(self):
queryset = UserLoginLog.objects.filter(status=LoginStatusChoices.success)
return UserLoginLog.filter_queryset_by_org(queryset)
@lazyproperty
def user_login_failed_queryset(self):
queryset = UserLoginLog.objects.filter(status=LoginStatusChoices.failed)
return UserLoginLog.filter_queryset_by_org(queryset)
@lazyproperty
def user_qs(self):
return User.get_org_users()
def get(self, request, *args, **kwargs):
data = {}
user_stats = self.user_qs.aggregate(
total=Count(1),
first_login=Count(1, filter=Q(is_first_login=True)),
need_update_password=Count(1, filter=Q(need_update_password=True)),
face_vector=Count(1, filter=Q(face_vector__isnull=False)),
not_enabled_mfa=Count(1, filter=Q(mfa_level=0)),
)
user_stats['valid'] = sum(1 for u in self.user_qs if u.is_valid)
data['user_stats'] = user_stats
source_map = Source.as_dict()
source_map.update({'password': _('Password')})
user_by_source = defaultdict(int)
for source in self.user_qs.values_list('source', flat=True):
k = source_map.get(source, source)
user_by_source[str(k)] += 1
data['user_by_source'] = [{'name': k, 'value': v} for k, v in user_by_source.items()]
data['user_login_log_metrics'] = {
'dates_metrics_date': self.dates_metrics_date,
'dates_metrics_success_total': self.get_user_login_metrics(self.user_login_log_queryset),
'dates_metrics_failure_total': self.get_user_login_metrics(self.user_login_failed_queryset),
}
data['user_login_method_metrics'] = {
'dates_metrics_date': self.dates_metrics_date,
'dates_metrics_total': self.get_user_login_method_metrics(source_map),
}
data['user_login_time_metrics'] = self.get_user_login_time_metrics()
return JsonResponse(data, status=200)
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/reports/api/users/user.py",
"license": "GNU General Public License v3.0",
"lines": 96,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:apps/reports/mixins.py | from django.utils import timezone
from rest_framework.request import Request
from common.utils import lazyproperty
from common.utils.timezone import local_zero_hour, local_now
class DateRangeMixin:
request: Request
days_param = 'days'
default_days = 1
@lazyproperty
def days(self) -> int:
raw = self.request.query_params.get(self.days_param, self.default_days)
try:
return int(raw)
except (ValueError, TypeError):
return self.default_days
@property
def start_datetime(self):
if self.days == 1:
return local_zero_hour()
return local_now() - timezone.timedelta(days=self.days)
@property
def date_range_bounds(self) -> tuple:
start = self.start_datetime.date()
end = (local_now() + timezone.timedelta(days=1)).date()
return start, end
@lazyproperty
def date_range_list(self) -> list:
return [
(local_now() - timezone.timedelta(days=i)).date()
for i in range(self.days - 1, -1, -1)
]
def filter_by_date_range(self, queryset, field_name: str):
start, end = self.date_range_bounds
return queryset.filter(**{f'{field_name}__range': (start, end)})
@lazyproperty
def dates_metrics_date(self):
return [date.strftime('%m-%d') for date in self.date_range_list] or ['0']
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/reports/mixins.py",
"license": "GNU General Public License v3.0",
"lines": 37,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:apps/reports/urls/api_urls.py | from django.urls import path
from reports import api
app_name = 'reports'
urlpatterns = [
path('reports/', api.ReportViewSet.as_view(), name='report-list'),
path('reports/users/', api.UserReportApi.as_view(), name='user-list'),
path('reports/user-change-password/', api.UserChangeSecretApi.as_view(), name='user-change-password'),
path('reports/asset-statistic/', api.AssetStatisticApi.as_view(), name='asset-statistic'),
path('reports/asset-activity/', api.AssetActivityApi.as_view(), name='asset-activity'),
path('reports/account-statistic/', api.AccountStatisticApi.as_view(), name='account-statistic'),
path('reports/account-automation/', api.AccountAutomationApi.as_view(), name='account-automation'),
]
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/reports/urls/api_urls.py",
"license": "GNU General Public License v3.0",
"lines": 12,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:apps/reports/urls/view_urls.py | # ~*~ coding: utf-8 ~*~
from __future__ import unicode_literals
from django.urls import path
from .. import views
__all__ = ["urlpatterns"]
app_name = "reports"
urlpatterns = [
# Resource Task url
path('export-pdf/', views.ExportPdfView.as_view(), name='export-pdf'),
path('send-mail/', views.SendMailView.as_view(), name='send-mail'),
] | {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/reports/urls/view_urls.py",
"license": "GNU General Public License v3.0",
"lines": 11,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:apps/reports/views.py | import base64
import io
import urllib.parse
from io import BytesIO
from urllib.parse import urlparse
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.http import FileResponse, HttpResponseBadRequest, JsonResponse
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.utils.translation import gettext_lazy as _
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from pdf2image import convert_from_bytes
from playwright.sync_api import sync_playwright
charts_map = {
"UserLoginReport": {
"title": _('User login report'),
"path": "/ui/#/reports/users/user-activity"
},
"UserChangePasswordReport": {
"title": _('User change password report'),
"path": "/ui/#/reports/users/change-password"
},
"AssetStatistics": {
"title": _('Asset statistics report'),
"path": "/ui/#/reports/assets/asset-statistics"
},
"AssetReport": {
"title": _('Asset activity report'),
"path": "/ui/#/reports/assets/asset-activity"
},
"AccountStatistics": {
"title": _('Account statistics report'),
"path": "/ui/#/reports/accounts/account-statistics?days=30"
},
"AccountAutomationReport": {
"title": _('Account automation report'),
"path": "/ui/#/reports/accounts/account-automation"
},
"ConsoleDashboard": {
"title": _('ConsoleDashboard'),
"path": "/ui/#/reports/dashboard/console"
},
"AuditsDashboard": {
"title": _('AuditsDashboard'),
"path": "/ui/#/reports/dashboard/audits"
},
"PamDashboard": {
"title": _('PamDashboard'),
"path": "/ui/#/reports/dashboard/pam"
},
"ChangeSecretDashboard": {
"title": _('ChangeSecretDashboard'),
"path": "/ui/#/reports/dashboard/change-secret"
}
}
def export_chart_to_pdf(chart_name, sessionid, request=None):
chart_info = charts_map.get(chart_name)
if not chart_info:
return None, None
if request:
url = request.build_absolute_uri(urllib.parse.unquote(chart_info['path']))
else:
url = urllib.parse.unquote(chart_info['path'])
if settings.DEBUG_DEV:
url = url.replace(":8080", ":9528")
oid = request.COOKIES.get("X-JMS-ORG")
days = request.GET.get('days', 7)
url = url + f"?days={days}&oid={oid}"
with sync_playwright() as p:
lang = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)
browser = p.chromium.launch(headless=True)
context = browser.new_context(
viewport={"width": 1040, "height": 800},
locale=lang,
ignore_https_errors=True
)
# 设置 sessionid cookie
parsed_url = urlparse(url)
context.add_cookies([
{
'name': settings.SESSION_COOKIE_NAME,
'value': sessionid,
'domain': parsed_url.hostname,
'path': '/',
'httpOnly': True,
'secure': False, # 如有 https 可改 True
}
])
page = context.new_page()
try:
page.goto(url, wait_until='networkidle')
page.wait_for_function('window.echartsFinished === true', timeout=10000)
page_title = page.title()
print(f"Page title: {page_title}")
pdf_bytes = page.pdf(format="A4", landscape=True,
margin={"top": "35px", "bottom": "30px", "left": "20px", "right": "20px"})
except Exception as e:
print(f'Playwright error: {e}')
pdf_bytes = None
page_title = chart_info['title']
finally:
browser.close()
return pdf_bytes, page_title
@method_decorator(csrf_exempt, name='dispatch')
class ExportPdfView(View):
def get(self, request):
chart_name = request.GET.get('chart')
return self._handle_export(request, chart_name)
def post(self, request):
chart_name = request.POST.get('chart')
return self._handle_export(request, chart_name)
def _handle_export(self, request, chart_name):
if not chart_name:
return HttpResponseBadRequest('Missing chart parameter')
sessionid = request.COOKIES.get(settings.SESSION_COOKIE_NAME)
if not sessionid:
return HttpResponseBadRequest('No sessionid found in cookies')
pdf_bytes, title = export_chart_to_pdf(chart_name, sessionid, request=request)
if not pdf_bytes:
return HttpResponseBadRequest('Failed to generate PDF')
filename = f"{title}-{timezone.now().strftime('%Y%m%d%H%M%S')}.pdf"
response = FileResponse(io.BytesIO(pdf_bytes), as_attachment=True, filename=filename,
content_type='application/pdf')
return response
class SendMailView(View):
def post(self, request):
chart_name = request.GET.get('chart')
if not chart_name:
return HttpResponseBadRequest('Missing chart parameter')
email = request.user.email
if not email:
return HttpResponseBadRequest('Missing email parameter')
sessionid = request.COOKIES.get(settings.SESSION_COOKIE_NAME)
if not sessionid:
return HttpResponseBadRequest('No sessionid found in cookies')
# 1. 生成 PDF
pdf_bytes, title = export_chart_to_pdf(chart_name, sessionid, request=request)
if not pdf_bytes:
return HttpResponseBadRequest('Failed to generate PDF')
# 2. PDF 转图片
images = convert_from_bytes(pdf_bytes, dpi=200)
# 3. 图片转 base64
img_tags = []
for img in images:
buffer = BytesIO()
img.save(buffer, format="PNG")
encoded = base64.b64encode(buffer.getvalue()).decode("utf-8")
img_tags.append(f'<img src="data:image/png;base64,{encoded}" style="width:100%; max-width:800px;" />')
html_content = "<br/>".join(img_tags)
# 4. 发送邮件
subject = f"{title} 报表"
from_email = settings.EMAIL_FROM or settings.EMAIL_HOST_USER
to = [email]
msg = EmailMultiAlternatives(subject, '', from_email, to)
msg.attach_alternative(html_content, "text/html")
filename = f"{title}-{timezone.now().strftime('%Y%m%d%H%M%S')}.pdf"
msg.attach(filename, pdf_bytes, "application/pdf")
try:
msg.send()
except Exception as e:
return JsonResponse({"error": _('Failed to send email: ') + str(e)})
return JsonResponse({"message": _('Email sent successfully to ') + email})
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/reports/views.py",
"license": "GNU General Public License v3.0",
"lines": 164,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
jumpserver/jumpserver:apps/common/utils/safe.py | import logging
import subprocess
logger = logging.getLogger(__name__)
def safe_run_cmd(cmd_args, shell=False):
if shell:
raise ValueError("shell=True is not allowed in safe_run_cmd. " "Pass command as a list with shell=False.")
cmd_args = [str(arg) for arg in cmd_args]
try:
return subprocess.run(cmd_args, shell=False)
except Exception as e:
logger.error("Failed to run command %s: %s", cmd_args, e)
return None
def truncate_file(file_path):
try:
with open(file_path, "w"):
pass
except Exception as e:
logger.error("Failed to truncate file %s: %s", file_path, e)
def find_and_delete_files(directory, name_pattern=None, mtime_days=None):
cmd = ["find", str(directory), "-type", "f"]
if mtime_days is not None:
cmd.extend(["-mtime", "+%s" % int(mtime_days)])
if name_pattern is not None:
cmd.extend(["-name", str(name_pattern)])
cmd.append("-delete")
return safe_run_cmd(cmd)
def find_and_delete_empty_dirs(directory):
cmd = ["find", str(directory), "-type", "d", "-empty", "-delete"]
return safe_run_cmd(cmd)
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/common/utils/safe.py",
"license": "GNU General Public License v3.0",
"lines": 29,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:apps/orgs/mixins/ws.py | from http.cookies import SimpleCookie
from asgiref.sync import sync_to_async
from orgs.utils import tmp_to_org
class OrgMixin:
cookie = None
org = None
def get_cookie(self):
try:
headers = self.scope['headers']
headers_dict = {key.decode('utf-8'): value.decode('utf-8') for key, value in headers}
cookie = SimpleCookie(headers_dict.get('cookie', ''))
except Exception as e:
cookie = SimpleCookie()
return cookie
def get_current_org(self):
oid = self.cookie.get('X-JMS-ORG')
return oid.value if oid else None
@sync_to_async
def has_perms(self, user, perms):
self.cookie = self.get_cookie()
self.org = self.get_current_org()
with tmp_to_org(self.org):
return user.has_perms(perms)
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/orgs/mixins/ws.py",
"license": "GNU General Public License v3.0",
"lines": 23,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
jumpserver/jumpserver:apps/authentication/mfa/passkey.py | from django.conf import settings
from django.utils.translation import gettext_lazy as _
from authentication.mfa.base import BaseMFA
from ..const import MFAType
class MFAPasskey(BaseMFA):
name = MFAType.Passkey.value
display_name = MFAType.Passkey.name
placeholder = 'Passkey'
has_code = False
def _check_code(self, code):
assert self.is_authenticated()
return False, ''
def is_active(self):
if not self.is_authenticated():
return True
if settings.SAFE_MODE:
return False
return self.user.passkey_set.count()
@staticmethod
def global_enabled():
return settings.AUTH_PASSKEY
def get_enable_url(self) -> str:
return '/ui/#/profile/passkeys'
def get_disable_url(self) -> str:
return '/ui/#/profile/passkeys'
def disable(self):
pass
def can_disable(self) -> bool:
return False
@staticmethod
def help_text_of_enable():
return _("Using passkey as MFA")
@staticmethod
def help_text_of_disable():
return _("Using passkey as MFA")
| {
"repo_id": "jumpserver/jumpserver",
"file_path": "apps/authentication/mfa/passkey.py",
"license": "GNU General Public License v3.0",
"lines": 35,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
karpathy/nanochat:nanochat/fp8.py | """Minimal FP8 training for nanochat — tensorwise dynamic scaling only.
Drop-in replacement for torchao's Float8Linear (~2000 lines) with ~150 lines.
We only need the "tensorwise" recipe (one scalar scale per tensor), not the full
generality of torchao (rowwise scaling, FSDP float8 all-gather, DTensor, tensor
subclass dispatch tables, etc.)
How FP8 training works
======================
A standard Linear layer does one matmul in forward and two in backward:
forward: output = input @ weight.T
backward: grad_input = grad_output @ weight
grad_weight= grad_output.T @ input
FP8 training wraps each of these three matmuls with:
1. Compute scale = FP8_MAX / max(|tensor|) for each operand
2. Quantize: fp8_tensor = clamp(tensor * scale, -FP8_MAX, FP8_MAX).to(fp8)
3. Matmul via torch._scaled_mm (cuBLAS FP8 kernel, ~2x faster than bf16)
4. Dequantize: _scaled_mm handles this internally using the inverse scales
The key insight: torch._scaled_mm and the float8 dtypes are PyTorch built-ins.
torchao is just orchestration around these primitives. We can call them directly.
FP8 dtype choice
================
There are two FP8 formats. We use both, following the standard convention:
- float8_e4m3fn: 4-bit exponent, 3-bit mantissa, range [-448, 448]
Higher precision (more mantissa bits), used for input and weight.
- float8_e5m2: 5-bit exponent, 2-bit mantissa, range [-57344, 57344]
Wider range (more exponent bits), used for gradients which can be large.
torch._scaled_mm layout requirements
=====================================
The cuBLAS FP8 kernel requires specific memory layouts:
- First argument (A): must be row-major (contiguous)
- Second argument (B): must be column-major (B.t().contiguous().t())
If B is obtained by transposing a contiguous tensor (e.g. weight.t()), it is
already column-major — no copy needed. Otherwise we use _to_col_major().
How this differs from torchao's approach
========================================
torchao uses a "tensor subclass" architecture: Float8TrainingTensor is a subclass
of torch.Tensor that bundles FP8 data + scale + metadata. It implements
__torch_dispatch__ with a dispatch table that intercepts every aten op (mm, t,
reshape, clone, ...) and handles it in FP8-aware fashion. When you call
output = input @ weight.T
the @ operator dispatches to aten.mm, which gets intercepted and routed to
torch._scaled_mm behind the scenes. This is ~2000 lines of code because you need
a handler for every tensor operation that might touch an FP8 tensor.
We take a simpler approach: a single autograd.Function (_Float8Matmul) that takes
full-precision inputs, quantizes to FP8 internally, calls _scaled_mm, and returns
full-precision outputs. Marked @allow_in_graph so torch.compile treats it as one
opaque node rather than trying to trace inside.
The trade-off is in how torch.compile sees the two approaches:
- torchao: compile decomposes the tensor subclass (via __tensor_flatten__) and
sees every individual op (amax, scale, cast, _scaled_mm) as separate graph
nodes. Inductor can fuse these with surrounding operations (e.g. fuse the
amax computation with the preceding layer's activation function).
- ours: compile sees a single opaque call. It can optimize everything around
the FP8 linear (attention, norms, etc.) but cannot fuse across the boundary.
Both call the exact same cuBLAS _scaled_mm kernel — the GPU matmul is identical.
The difference is only in the "glue" ops (amax, scale, cast) which are tiny
compared to the matmul. In practice this means our version is slightly faster
(less compilation overhead, no tensor subclass dispatch cost) but can produce
subtly different floating-point rounding paths under torch.compile, since Inductor
generates a different graph. Numerics are bitwise identical in eager mode.
"""
import torch
import torch.nn as nn
# Avoid division by zero when computing scale from an all-zeros tensor
EPS = 1e-12
@torch.no_grad()
def _to_fp8(x, fp8_dtype):
"""Dynamically quantize a tensor to FP8 using tensorwise scaling.
"Tensorwise" means one scalar scale for the entire tensor (as opposed to
"rowwise" which computes a separate scale per row). Tensorwise is faster
because cuBLAS handles the scaling; rowwise needs the CUTLASS kernel.
Returns (fp8_data, inverse_scale) for use with torch._scaled_mm.
"""
fp8_max = torch.finfo(fp8_dtype).max
# Compute the max absolute value across the entire tensor
amax = x.float().abs().max()
# Scale maps [0, amax] -> [0, fp8_max]. Use float64 for the division to
# ensure consistent numerics between torch.compile and eager mode.
# (torchao does the same upcast — without it, compile/eager can diverge)
scale = fp8_max / amax.double().clamp(min=EPS)
scale = scale.float()
# Quantize: scale into FP8 range, saturate (clamp prevents overflow when
# casting — PyTorch's default is to wrap, not saturate), then cast to FP8
x_scaled = x.float() * scale
x_clamped = x_scaled.clamp(-fp8_max, fp8_max)
x_fp8 = x_clamped.to(fp8_dtype)
# _scaled_mm expects the *inverse* of our scale (it multiplies by this to
# convert FP8 values back to the original range during the matmul)
inv_scale = scale.reciprocal()
return x_fp8, inv_scale
def _to_col_major(x):
"""Rearrange a 2D tensor's memory to column-major layout.
torch._scaled_mm requires its second operand in column-major layout.
The trick: transpose -> contiguous (forces a copy in transposed order)
-> transpose back. The result has the same logical shape but column-major
strides, e.g. a [M, N] tensor gets strides (1, M) instead of (N, 1).
"""
return x.t().contiguous().t()
# allow_in_graph tells torch.compile to treat this as an opaque operation —
# dynamo won't try to decompose it into smaller ops. See the module docstring
# for how this differs from torchao's tensor subclass approach.
@torch._dynamo.allow_in_graph
class _Float8Matmul(torch.autograd.Function):
"""Custom autograd for the three FP8 GEMMs of a Linear layer.
The forward quantizes input and weight to FP8 and saves
the quantized tensors + scales for backward.
"""
@staticmethod
def forward(ctx, input_2d, weight):
# Quantize both operands to e4m3 (higher precision format)
input_fp8, input_inv = _to_fp8(input_2d, torch.float8_e4m3fn)
weight_fp8, weight_inv = _to_fp8(weight, torch.float8_e4m3fn)
ctx.save_for_backward(input_fp8, input_inv, weight_fp8, weight_inv)
# output = input @ weight.T
# input_fp8 is [B, K] contiguous = row-major (good for first arg)
# weight_fp8 is [N, K] contiguous, so weight_fp8.t() is [K, N] with
# strides (1, K) = column-major (good for second arg, no copy needed!)
output = torch._scaled_mm(
input_fp8,
weight_fp8.t(),
scale_a=input_inv,
scale_b=weight_inv,
out_dtype=input_2d.dtype,
# use_fast_accum=True accumulates the dot products in lower precision.
# Slightly less accurate but measurably faster. Standard practice for
# the forward pass; we use False in backward for more precise gradients.
use_fast_accum=True,
)
return output
@staticmethod
def backward(ctx, grad_output):
in_fp8, in_inv, w_fp8, w_inv = ctx.saved_tensors
# === GEMM 1: grad_input = grad_output @ weight ===
# Shapes: [B, N] @ [N, K] -> [B, K]
# Gradients use e5m2 (wider range), weights use e4m3 (higher precision)
go_fp8, go_inv = _to_fp8(grad_output, torch.float8_e5m2)
# go_fp8 is [B, N] contiguous = row-major, good for first arg
# w_fp8 is [N, K] contiguous = row-major, need column-major for second arg
w_col = _to_col_major(w_fp8)
grad_input = torch._scaled_mm(
go_fp8,
w_col,
scale_a=go_inv,
scale_b=w_inv,
out_dtype=grad_output.dtype,
use_fast_accum=False,
)
# === GEMM 2: grad_weight = grad_output.T @ input ===
# Shapes: [N, B] @ [B, K] -> [N, K]
# go_fp8 is [B, N] contiguous, we need go.T = [N, B] as first arg.
# Transposing gives column-major, but first arg needs row-major,
# so we must call .contiguous() to physically rearrange the memory.
go_T = go_fp8.t().contiguous() # [N, B] row-major
in_col = _to_col_major(in_fp8) # [B, K] column-major
grad_weight = torch._scaled_mm(
go_T,
in_col,
scale_a=go_inv,
scale_b=in_inv,
out_dtype=grad_output.dtype,
use_fast_accum=False,
)
return grad_input, grad_weight
class Float8Linear(nn.Linear):
"""Drop-in nn.Linear replacement that does FP8 compute.
Weights and biases remain in their original precision (e.g. fp32/bf16).
Only the matmul is performed in FP8 via the _Float8Matmul autograd function.
"""
def forward(self, input):
# Replicate the autocast behavior of F.linear — when autocast is active,
# we need to manually cast input to the autocast dtype (e.g. bf16),
# since we bypass F.linear's built-in autocast handling.
if torch.is_autocast_enabled():
input = input.to(torch.get_autocast_gpu_dtype())
# _scaled_mm only works on 2D tensors, so flatten batch dimensions
orig_shape = input.shape
input_2d = input.reshape(-1, orig_shape[-1])
output = _Float8Matmul.apply(input_2d, self.weight)
output = output.reshape(*orig_shape[:-1], output.shape[-1])
if self.bias is not None:
output = output + self.bias.to(output.dtype)
return output
@classmethod
def from_float(cls, mod):
"""Create Float8Linear from nn.Linear, sharing the same weight and bias.
Uses meta device to avoid allocating a temporary weight tensor — we
create the module shell on meta (shapes/dtypes only, no memory), then
point .weight and .bias to the original module's parameters.
"""
with torch.device("meta"):
new_mod = cls(mod.in_features, mod.out_features, bias=False)
new_mod.weight = mod.weight
new_mod.bias = mod.bias
return new_mod
class Float8LinearConfig:
"""Minimal config matching torchao's API. Only tensorwise recipe is supported."""
@staticmethod
def from_recipe_name(recipe_name):
if recipe_name != "tensorwise":
raise ValueError(
f"Only 'tensorwise' recipe is supported, got '{recipe_name}'. "
f"Rowwise/axiswise recipes require the full torchao library."
)
return Float8LinearConfig()
def convert_to_float8_training(module, *, config=None, module_filter_fn=None):
"""Replace nn.Linear layers with Float8Linear throughout a module.
Walks the module tree in post-order (children before parents) and swaps
each nn.Linear that passes the optional filter. The new Float8Linear shares
the original weight and bias tensors — no copies, no extra memory.
Args:
module: Root module to convert.
config: Float8LinearConfig (accepted for API compat, only tensorwise supported).
module_filter_fn: Optional filter(module, fqn) -> bool. Only matching Linears
are converted. Common use: skip layers with dims not divisible by 16
(hardware requirement for FP8 matmuls on H100).
"""
def _convert(mod, prefix=""):
for name, child in mod.named_children():
fqn = f"{prefix}.{name}" if prefix else name
_convert(child, fqn)
if isinstance(child, nn.Linear) and not isinstance(child, Float8Linear):
if module_filter_fn is None or module_filter_fn(child, fqn):
setattr(mod, name, Float8Linear.from_float(child))
_convert(module)
return module
| {
"repo_id": "karpathy/nanochat",
"file_path": "nanochat/fp8.py",
"license": "MIT License",
"lines": 224,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
karpathy/nanochat:nanochat/optim.py | """
A nice and efficient mixed AdamW/Muon Combined Optimizer.
Usually the embeddings and scalars go into AdamW, and the matrix parameters go into Muon.
Two versions are provided (MuonAdamW, DistMuonAdamW), for single GPU and distributed.
Addapted from: https://github.com/KellerJordan/modded-nanogpt
Further contributions from @karpathy and @chrisjmccormick.
"""
import torch
import torch.distributed as dist
from torch import Tensor
# -----------------------------------------------------------------------------
"""
Good old AdamW optimizer, fused kernel.
https://arxiv.org/abs/1711.05101
"""
@torch.compile(dynamic=False, fullgraph=True)
def adamw_step_fused(
p: Tensor, # (32768, 768) - parameter tensor
grad: Tensor, # (32768, 768) - gradient, same shape as p
exp_avg: Tensor, # (32768, 768) - first moment, same shape as p
exp_avg_sq: Tensor, # (32768, 768) - second moment, same shape as p
step_t: Tensor, # () - 0-D CPU tensor, step count
lr_t: Tensor, # () - 0-D CPU tensor, learning rate
beta1_t: Tensor, # () - 0-D CPU tensor, beta1
beta2_t: Tensor, # () - 0-D CPU tensor, beta2
eps_t: Tensor, # () - 0-D CPU tensor, epsilon
wd_t: Tensor, # () - 0-D CPU tensor, weight decay
) -> None:
"""
Fused AdamW step: weight_decay -> momentum_update -> bias_correction -> param_update
All in one compiled graph to eliminate Python overhead between ops.
The 0-D CPU tensors avoid recompilation when hyperparameter values change.
"""
# Weight decay (decoupled, applied before the update)
p.mul_(1 - lr_t * wd_t)
# Update running averages (lerp_ is cleaner and fuses well)
exp_avg.lerp_(grad, 1 - beta1_t)
exp_avg_sq.lerp_(grad.square(), 1 - beta2_t)
# Bias corrections
bias1 = 1 - beta1_t ** step_t
bias2 = 1 - beta2_t ** step_t
# Compute update and apply
denom = (exp_avg_sq / bias2).sqrt() + eps_t
step_size = lr_t / bias1
p.add_(exp_avg / denom, alpha=-step_size)
# -----------------------------------------------------------------------------
"""
Muon optimizer adapted and simplified from modded-nanogpt.
https://github.com/KellerJordan/modded-nanogpt
Background:
Newton-Schulz iteration to compute the zeroth power / orthogonalization of G. We opt to use a
quintic iteration whose coefficients are selected to maximize the slope at zero. For the purpose
of minimizing steps, it turns out to be empirically effective to keep increasing the slope at
zero even beyond the point where the iteration no longer converges all the way to one everywhere
on the interval. This iteration therefore does not produce UV^T but rather something like US'V^T
where S' is diagonal with S_{ii}' ~ Uniform(0.5, 1.5), which turns out not to hurt model
performance at all relative to UV^T, where USV^T = G is the SVD.
Here, an alternative to Newton-Schulz iteration with potentially better convergence properties:
Polar Express Sign Method for orthogonalization.
https://arxiv.org/pdf/2505.16932
by Noah Amsel, David Persson, Christopher Musco, Robert M. Gower.
NorMuon variance reduction: per-neuron/column adaptive learning rate that normalizes
update scales after orthogonalization (Muon's output has non-uniform scales across neurons).
https://arxiv.org/pdf/2510.05491
Some of the changes in nanochat implementation:
- Uses a simpler, more general approach to parameter grouping and stacking
- Uses a single fused kernel for the momentum -> polar_express -> variance_reduction -> update step
- Makes no assumptions about model architecture (e.g. that attention weights are fused into QKVO format)
"""
# Coefficients for Polar Express (computed for num_iters=5, safety_factor=2e-2, cushion=2)
# From https://arxiv.org/pdf/2505.16932
polar_express_coeffs = [
(8.156554524902461, -22.48329292557795, 15.878769915207462),
(4.042929935166739, -2.808917465908714, 0.5000178451051316),
(3.8916678022926607, -2.772484153217685, 0.5060648178503393),
(3.285753657755655, -2.3681294933425376, 0.46449024233003106),
(2.3465413258596377, -1.7097828382687081, 0.42323551169305323),
]
@torch.compile(dynamic=False, fullgraph=True)
def muon_step_fused(
stacked_grads: Tensor, # (12, 768, 3072) - stacked gradients
stacked_params: Tensor, # (12, 768, 3072) - stacked parameters
momentum_buffer: Tensor, # (12, 768, 3072) - first moment buffer
second_momentum_buffer: Tensor, # (12, 768, 1) or (12, 1, 3072) - factored second moment
momentum_t: Tensor, # () - 0-D CPU tensor, momentum coefficient
lr_t: Tensor, # () - 0-D CPU tensor, learning rate
wd_t: Tensor, # () - 0-D CPU tensor, weight decay
beta2_t: Tensor, # () - 0-D CPU tensor, beta2 for second moment
ns_steps: int, # 5 - number of Newton-Schulz/Polar Express iterations
red_dim: int, # -1 or -2 - reduction dimension for variance
) -> None:
"""
Fused Muon step: momentum -> polar_express -> variance_reduction -> cautious_update
All in one compiled graph to eliminate Python overhead between ops.
Some of the constants are 0-D CPU tensors to avoid recompilation when values change.
"""
# Nesterov momentum
momentum = momentum_t.to(stacked_grads.dtype)
momentum_buffer.lerp_(stacked_grads, 1 - momentum)
g = stacked_grads.lerp_(momentum_buffer, momentum)
# Polar express
X = g.bfloat16()
X = X / (X.norm(dim=(-2, -1), keepdim=True) * 1.02 + 1e-6)
if g.size(-2) > g.size(-1): # Tall matrix
for a, b, c in polar_express_coeffs[:ns_steps]:
A = X.mT @ X
B = b * A + c * (A @ A)
X = a * X + X @ B
else: # Wide matrix (original math)
for a, b, c in polar_express_coeffs[:ns_steps]:
A = X @ X.mT
B = b * A + c * (A @ A)
X = a * X + B @ X
g = X
# Variance reduction
beta2 = beta2_t.to(g.dtype)
v_mean = g.float().square().mean(dim=red_dim, keepdim=True)
red_dim_size = g.size(red_dim)
v_norm_sq = v_mean.sum(dim=(-2, -1), keepdim=True) * red_dim_size
v_norm = v_norm_sq.sqrt()
second_momentum_buffer.lerp_(v_mean.to(dtype=second_momentum_buffer.dtype), 1 - beta2)
step_size = second_momentum_buffer.clamp_min(1e-10).rsqrt()
scaled_sq_sum = (v_mean * red_dim_size) * step_size.float().square()
v_norm_new = scaled_sq_sum.sum(dim=(-2, -1), keepdim=True).sqrt()
final_scale = step_size * (v_norm / v_norm_new.clamp_min(1e-10))
g = g * final_scale.to(g.dtype)
# Cautious weight decay + parameter update
lr = lr_t.to(g.dtype)
wd = wd_t.to(g.dtype)
mask = (g * stacked_params) >= 0
stacked_params.sub_(lr * g + lr * wd * stacked_params * mask)
# -----------------------------------------------------------------------------
# Single GPU version of the MuonAdamW optimizer.
# Used mostly for reference, debugging and testing.
class MuonAdamW(torch.optim.Optimizer):
"""
Combined optimizer: Muon for 2D matrix params, AdamW for others, single GPU version.
AdamW - Fused AdamW optimizer step.
Muon - MomentUm Orthogonalized by Newton-schulz
https://kellerjordan.github.io/posts/muon/
Muon internally runs standard SGD-momentum, and then performs an orthogonalization post-
processing step, in which each 2D parameter's update is replaced with the nearest orthogonal
matrix. To efficiently orthogonalize each update, we use a Newton-Schulz iteration, which has
the advantage that it can be stably run in bfloat16 on the GPU.
Some warnings:
- The Muon optimizer should not be used for the embedding layer, the final fully connected layer,
or any {0,1}-D parameters; those should all be optimized by a standard method (e.g., AdamW).
- To use it with 4D convolutional filters, it works well to just flatten their last 3 dimensions.
Arguments:
param_groups: List of dicts, each containing:
- 'params': List of parameters
- 'kind': 'adamw' or 'muon'
- For AdamW groups: 'lr', 'betas', 'eps', 'weight_decay'
- For Muon groups: 'lr', 'momentum', 'ns_steps', 'beta2', 'weight_decay'
"""
def __init__(self, param_groups: list[dict]):
super().__init__(param_groups, defaults={})
# 0-D CPU tensors to avoid torch.compile recompilation when values change
# AdamW tensors
self._adamw_step_t = torch.tensor(0.0, dtype=torch.float32, device="cpu")
self._adamw_lr_t = torch.tensor(0.0, dtype=torch.float32, device="cpu")
self._adamw_beta1_t = torch.tensor(0.0, dtype=torch.float32, device="cpu")
self._adamw_beta2_t = torch.tensor(0.0, dtype=torch.float32, device="cpu")
self._adamw_eps_t = torch.tensor(0.0, dtype=torch.float32, device="cpu")
self._adamw_wd_t = torch.tensor(0.0, dtype=torch.float32, device="cpu")
# Muon tensors
self._muon_momentum_t = torch.tensor(0.0, dtype=torch.float32, device="cpu")
self._muon_lr_t = torch.tensor(0.0, dtype=torch.float32, device="cpu")
self._muon_wd_t = torch.tensor(0.0, dtype=torch.float32, device="cpu")
self._muon_beta2_t = torch.tensor(0.0, dtype=torch.float32, device="cpu")
def _step_adamw(self, group: dict) -> None:
"""
AdamW update for each param in the group individually.
Lazy init the state, fill in all 0-D tensors, call the fused kernel.
"""
for p in group['params']:
if p.grad is None:
continue
grad = p.grad
state = self.state[p]
# State init
if not state:
state['step'] = 0
state['exp_avg'] = torch.zeros_like(p)
state['exp_avg_sq'] = torch.zeros_like(p)
exp_avg = state['exp_avg']
exp_avg_sq = state['exp_avg_sq']
state['step'] += 1
# Fill 0-D tensors with current values
self._adamw_step_t.fill_(state['step'])
self._adamw_lr_t.fill_(group['lr'])
self._adamw_beta1_t.fill_(group['betas'][0])
self._adamw_beta2_t.fill_(group['betas'][1])
self._adamw_eps_t.fill_(group['eps'])
self._adamw_wd_t.fill_(group['weight_decay'])
# Fused update: weight_decay -> momentum -> bias_correction -> param_update
adamw_step_fused(
p, grad, exp_avg, exp_avg_sq,
self._adamw_step_t, self._adamw_lr_t, self._adamw_beta1_t,
self._adamw_beta2_t, self._adamw_eps_t, self._adamw_wd_t,
)
def _step_muon(self, group: dict) -> None:
"""
Muon update for all params in the group (stacked for efficiency).
Lazy init the state, fill in all 0-D tensors, call the fused kernel.
"""
params: list[Tensor] = group['params']
if not params:
return
# Get or create group-level buffers (stored in first param's state for convenience)
p = params[0]
state = self.state[p]
num_params = len(params)
shape, device, dtype = p.shape, p.device, p.dtype
# Momentum for every individual parameter
if "momentum_buffer" not in state:
state["momentum_buffer"] = torch.zeros(num_params, *shape, dtype=dtype, device=device)
momentum_buffer = state["momentum_buffer"]
# Second momentum buffer is factored, either per-row or per-column
if "second_momentum_buffer" not in state:
state_shape = (num_params, shape[-2], 1) if shape[-2] >= shape[-1] else (num_params, 1, shape[-1])
state["second_momentum_buffer"] = torch.zeros(state_shape, dtype=dtype, device=device)
second_momentum_buffer = state["second_momentum_buffer"]
red_dim = -1 if shape[-2] >= shape[-1] else -2
# Stack grads and params (NOTE: this assumes all params have the same shape)
stacked_grads = torch.stack([p.grad for p in params])
stacked_params = torch.stack(params)
# Fill all the 0-D tensors with current values
self._muon_momentum_t.fill_(group["momentum"])
self._muon_beta2_t.fill_(group["beta2"] if group["beta2"] is not None else 0.0)
self._muon_lr_t.fill_(group["lr"] * max(1.0, shape[-2] / shape[-1])**0.5)
self._muon_wd_t.fill_(group["weight_decay"])
# Single fused kernel: momentum -> polar_express -> variance_reduction -> update
muon_step_fused(
stacked_grads,
stacked_params,
momentum_buffer,
second_momentum_buffer,
self._muon_momentum_t,
self._muon_lr_t,
self._muon_wd_t,
self._muon_beta2_t,
group["ns_steps"],
red_dim,
)
# Copy back to original params
torch._foreach_copy_(params, list(stacked_params.unbind(0)))
@torch.no_grad()
def step(self):
for group in self.param_groups:
if group['kind'] == 'adamw':
self._step_adamw(group)
elif group['kind'] == 'muon':
self._step_muon(group)
else:
raise ValueError(f"Unknown optimizer kind: {group['kind']}")
# -----------------------------------------------------------------------------
# Distributed version of the MuonAdamW optimizer.
# Used for training on multiple GPUs.
class DistMuonAdamW(torch.optim.Optimizer):
"""
Combined distributed optimizer: Muon for 2D matrix params, AdamW for others.
See MuonAdamW for the algorithmic details of each optimizer. This class adds
distributed communication to enable multi-GPU training without PyTorch DDP.
Design Goals:
- Overlap communication with computation (async ops)
- Minimize memory by sharding optimizer states across ranks (ZeRO-2 style)
- Batch small tensors into single comm ops where possible
Communication Pattern (3-phase async):
We use a 3-phase structure to maximize overlap between communication and compute:
Phase 1: Launch all async reduce ops
- Kick off all reduce_scatter/all_reduce operations
- Don't wait - let them run in background while we continue
Phase 2: Wait for reduces, compute updates, launch gathers
- For each group: wait for its reduce, compute the update, launch gather
- By processing groups in order, earlier gathers run while later computes happen
Phase 3: Wait for gathers, copy back
- Wait for all gathers to complete
- Copy updated params back to original tensors (Muon only)
AdamW Communication (ZeRO-2 style):
- Small params (<1024 elements): all_reduce gradients, update full param on each rank.
Optimizer state is replicated but these params are tiny (scalars, biases).
- Large params: reduce_scatter gradients so each rank gets 1/N of the grad, update
only that slice, then all_gather the updated slices. Optimizer state (exp_avg,
exp_avg_sq) is sharded - each rank only stores state for its slice.
Requires param.shape[0] divisible by world_size.
Muon Communication (stacked + chunked):
- All params in a Muon group must have the same shape (caller's responsibility).
- Stack all K params into a single (K, *shape) tensor for efficient comm.
- Divide K params across N ranks: each rank "owns" ceil(K/N) params.
- reduce_scatter the stacked grads so each rank gets its chunk.
- Each rank computes Muon update only for params it owns.
- all_gather the updated params back to all ranks.
- Optimizer state (momentum_buffer, second_momentum_buffer) is sharded by chunk.
- Padding: if K doesn't divide evenly, we zero-pad to (ceil(K/N) * N) for comm,
then ignore the padding when copying back.
Buffer Reuse:
- For Muon, we allocate stacked_grads for reduce_scatter input, then reuse the
same buffer as the output for all_gather (stacked_params). This saves memory
since we don't need both buffers simultaneously.
Arguments:
param_groups: List of dicts, each containing:
- 'params': List of parameters
- 'kind': 'adamw' or 'muon'
- For AdamW groups: 'lr', 'betas', 'eps', 'weight_decay'
- For Muon groups: 'lr', 'momentum', 'ns_steps', 'beta2', 'weight_decay'
"""
def __init__(self, param_groups: list[dict]):
super().__init__(param_groups, defaults={})
# 0-D CPU tensors to avoid torch.compile recompilation when values change
self._adamw_step_t = torch.tensor(0.0, dtype=torch.float32, device="cpu")
self._adamw_lr_t = torch.tensor(0.0, dtype=torch.float32, device="cpu")
self._adamw_beta1_t = torch.tensor(0.0, dtype=torch.float32, device="cpu")
self._adamw_beta2_t = torch.tensor(0.0, dtype=torch.float32, device="cpu")
self._adamw_eps_t = torch.tensor(0.0, dtype=torch.float32, device="cpu")
self._adamw_wd_t = torch.tensor(0.0, dtype=torch.float32, device="cpu")
self._muon_momentum_t = torch.tensor(0.0, dtype=torch.float32, device="cpu")
self._muon_lr_t = torch.tensor(0.0, dtype=torch.float32, device="cpu")
self._muon_wd_t = torch.tensor(0.0, dtype=torch.float32, device="cpu")
self._muon_beta2_t = torch.tensor(0.0, dtype=torch.float32, device="cpu")
def _reduce_adamw(self, group: dict, world_size: int) -> dict:
"""Launch async reduce ops for AdamW group. Returns info dict with per-param infos."""
param_infos = {}
for p in group['params']:
grad = p.grad
if p.numel() < 1024:
# Small params: all_reduce (no scatter/gather needed)
future = dist.all_reduce(grad, op=dist.ReduceOp.AVG, async_op=True).get_future()
param_infos[p] = dict(future=future, grad_slice=grad, is_small=True)
else:
# Large params: reduce_scatter
assert grad.shape[0] % world_size == 0, f"AdamW reduce_scatter requires shape[0] ({grad.shape[0]}) divisible by world_size ({world_size})"
rank_size = grad.shape[0] // world_size
grad_slice = torch.empty_like(grad[:rank_size])
future = dist.reduce_scatter_tensor(grad_slice, grad, op=dist.ReduceOp.AVG, async_op=True).get_future()
param_infos[p] = dict(future=future, grad_slice=grad_slice, is_small=False)
return dict(param_infos=param_infos)
def _reduce_muon(self, group: dict, world_size: int) -> dict:
"""Launch async reduce op for Muon group. Returns info dict."""
params = group['params']
chunk_size = (len(params) + world_size - 1) // world_size
padded_num_params = chunk_size * world_size
p = params[0]
shape, device, dtype = p.shape, p.device, p.dtype
# Stack grads and zero-pad to padded_num_params
grad_stack = torch.stack([p.grad for p in params])
stacked_grads = torch.empty(padded_num_params, *shape, dtype=dtype, device=device)
stacked_grads[:len(params)].copy_(grad_stack)
if len(params) < padded_num_params:
stacked_grads[len(params):].zero_()
# Reduce_scatter to get this rank's chunk
grad_chunk = torch.empty(chunk_size, *shape, dtype=dtype, device=device)
future = dist.reduce_scatter_tensor(grad_chunk, stacked_grads, op=dist.ReduceOp.AVG, async_op=True).get_future()
return dict(future=future, grad_chunk=grad_chunk, stacked_grads=stacked_grads, chunk_size=chunk_size)
def _compute_adamw(self, group: dict, info: dict, gather_list: list, rank: int, world_size: int) -> None:
"""Wait for reduce, compute AdamW updates, launch gathers for large params."""
param_infos = info['param_infos']
for p in group['params']:
pinfo = param_infos[p]
pinfo['future'].wait()
grad_slice = pinfo['grad_slice']
state = self.state[p]
# For small params, operate on full param; for large, operate on slice
if pinfo['is_small']:
p_slice = p
else:
rank_size = p.shape[0] // world_size
p_slice = p[rank * rank_size:(rank + 1) * rank_size]
# State init
if not state:
state['step'] = 0
state['exp_avg'] = torch.zeros_like(p_slice)
state['exp_avg_sq'] = torch.zeros_like(p_slice)
state['step'] += 1
# Fill 0-D tensors and run fused kernel
self._adamw_step_t.fill_(state['step'])
self._adamw_lr_t.fill_(group['lr'])
self._adamw_beta1_t.fill_(group['betas'][0])
self._adamw_beta2_t.fill_(group['betas'][1])
self._adamw_eps_t.fill_(group['eps'])
self._adamw_wd_t.fill_(group['weight_decay'])
adamw_step_fused(
p_slice, grad_slice, state['exp_avg'], state['exp_avg_sq'],
self._adamw_step_t, self._adamw_lr_t, self._adamw_beta1_t,
self._adamw_beta2_t, self._adamw_eps_t, self._adamw_wd_t,
)
# Large params need all_gather
if not pinfo['is_small']:
future = dist.all_gather_into_tensor(p, p_slice, async_op=True).get_future()
gather_list.append(dict(future=future, params=None))
def _compute_muon(self, group: dict, info: dict, gather_list: list, rank: int) -> None:
"""Wait for reduce, compute Muon updates, launch gather."""
info['future'].wait()
params = group['params']
chunk_size = info['chunk_size']
grad_chunk = info['grad_chunk']
p = params[0]
shape, device, dtype = p.shape, p.device, p.dtype
# How many params does this rank own?
start_idx = rank * chunk_size
num_owned = min(chunk_size, max(0, len(params) - start_idx))
# Get or create group-level state
state = self.state[p]
if "momentum_buffer" not in state:
state["momentum_buffer"] = torch.zeros(chunk_size, *shape, dtype=dtype, device=device)
if "second_momentum_buffer" not in state:
state_shape = (chunk_size, shape[-2], 1) if shape[-2] >= shape[-1] else (chunk_size, 1, shape[-1])
state["second_momentum_buffer"] = torch.zeros(state_shape, dtype=dtype, device=device)
red_dim = -1 if shape[-2] >= shape[-1] else -2
# Build output buffer for all_gather
updated_params = torch.empty(chunk_size, *shape, dtype=dtype, device=device)
if num_owned > 0:
owned_params = [params[start_idx + i] for i in range(num_owned)]
stacked_owned = torch.stack(owned_params)
# Fill 0-D tensors and run fused kernel
self._muon_momentum_t.fill_(group["momentum"])
self._muon_beta2_t.fill_(group["beta2"])
self._muon_lr_t.fill_(group["lr"] * max(1.0, shape[-2] / shape[-1])**0.5)
self._muon_wd_t.fill_(group["weight_decay"])
muon_step_fused(
grad_chunk[:num_owned], stacked_owned,
state["momentum_buffer"][:num_owned], state["second_momentum_buffer"][:num_owned],
self._muon_momentum_t, self._muon_lr_t, self._muon_wd_t, self._muon_beta2_t,
group["ns_steps"], red_dim,
)
updated_params[:num_owned].copy_(stacked_owned)
if num_owned < chunk_size:
updated_params[num_owned:].zero_()
# Reuse stacked_grads buffer for all_gather output
stacked_params = info["stacked_grads"]
future = dist.all_gather_into_tensor(stacked_params, updated_params, async_op=True).get_future()
gather_list.append(dict(future=future, stacked_params=stacked_params, params=params))
def _finish_gathers(self, gather_list: list) -> None:
"""Wait for all gathers and copy Muon params back."""
for info in gather_list:
info["future"].wait()
if info["params"] is not None:
# Muon: copy from stacked buffer back to individual params
torch._foreach_copy_(info["params"], list(info["stacked_params"][:len(info["params"])].unbind(0)))
@torch.no_grad()
def step(self):
rank = dist.get_rank()
world_size = dist.get_world_size()
# Phase 1: launch all async reduce ops
reduce_infos: list[dict] = []
for group in self.param_groups:
if group['kind'] == 'adamw':
reduce_infos.append(self._reduce_adamw(group, world_size))
elif group['kind'] == 'muon':
reduce_infos.append(self._reduce_muon(group, world_size))
else:
raise ValueError(f"Unknown optimizer kind: {group['kind']}")
# Phase 2: wait for reduces, compute updates, launch gathers
gather_list: list[dict] = []
for group, info in zip(self.param_groups, reduce_infos):
if group['kind'] == 'adamw':
self._compute_adamw(group, info, gather_list, rank, world_size)
elif group['kind'] == 'muon':
self._compute_muon(group, info, gather_list, rank)
else:
raise ValueError(f"Unknown optimizer kind: {group['kind']}")
# Phase 3: wait for gathers, copy back
self._finish_gathers(gather_list)
| {
"repo_id": "karpathy/nanochat",
"file_path": "nanochat/optim.py",
"license": "MIT License",
"lines": 463,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
karpathy/nanochat:nanochat/flash_attention.py | """
Unified Flash Attention interface with automatic FA3/SDPA switching.
Exports `flash_attn` module that matches the FA3 API exactly, but falls back
to PyTorch SDPA on non-Hopper GPUs (including Blackwell), MPS, and CPU.
Usage (drop-in replacement for FA3):
from nanochat.flash_attention import flash_attn
# Training (no KV cache)
y = flash_attn.flash_attn_func(q, k, v, causal=True, window_size=window_size)
# Inference (with KV cache)
y = flash_attn.flash_attn_with_kvcache(q, k_cache, v_cache, k=k, v=v, ...)
"""
import torch
import torch.nn.functional as F
# =============================================================================
# Detection: Try to load FA3 on Hopper+ GPUs
# =============================================================================
def _load_flash_attention_3():
"""Try to load Flash Attention 3 (requires Hopper GPU, sm90)."""
if not torch.cuda.is_available():
return None
try:
major, _ = torch.cuda.get_device_capability()
# FA3 kernels are compiled for Hopper (sm90) only
# Ada (sm89), Blackwell (sm100) need SDPA fallback until FA3 is recompiled
if major != 9:
return None
import os
os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "1"
from kernels import get_kernel
return get_kernel('varunneal/flash-attention-3').flash_attn_interface
except Exception:
return None
_fa3 = _load_flash_attention_3()
HAS_FA3 = _fa3 is not None
# Override for testing: set to 'fa3', 'sdpa', or None (auto)
_override_impl = None
def _use_fa3():
"""Determine whether to use FA3 based on availability and override."""
if _override_impl == 'fa3':
assert HAS_FA3, "Cannot override to FA3: not available on this hardware"
return True
if _override_impl == 'sdpa':
return False
return HAS_FA3 # auto
# =============================================================================
# SDPA helpers
# =============================================================================
def _sdpa_attention(q, k, v, window_size, enable_gqa):
"""
SDPA attention with sliding window support.
q, k, v are (B, H, T, D) format.
"""
Tq = q.size(2)
Tk = k.size(2)
window = window_size[0]
# Full context, same length
if (window < 0 or window >= Tq) and Tq == Tk:
return F.scaled_dot_product_attention(q, k, v, is_causal=True, enable_gqa=enable_gqa)
# Single token generation
if Tq == 1:
if window >= 0 and window < Tk:
# window is "left" tokens we need to include (window + 1) keys total
start = max(0, Tk - (window + 1))
k = k[:, :, start:, :]
v = v[:, :, start:, :]
return F.scaled_dot_product_attention(q, k, v, is_causal=False, enable_gqa=enable_gqa)
# Need explicit mask for sliding window/chunk inference
device = q.device
# For chunk inference (Tq != Tk), is_causal is not aligned to cache position => build an explicit bool mask
row_idx = (Tk - Tq) + torch.arange(Tq, device=device).unsqueeze(1)
col_idx = torch.arange(Tk, device=device).unsqueeze(0)
mask = col_idx <= row_idx
# sliding window (left)
if window >= 0 and window < Tk:
mask = mask & ((row_idx - col_idx) <= window)
return F.scaled_dot_product_attention(q, k, v, attn_mask=mask, enable_gqa=enable_gqa)
# =============================================================================
# Public API: Same interface as FA3
# =============================================================================
def flash_attn_func(q, k, v, causal=False, window_size=(-1, -1)):
"""
Flash Attention for training (no KV cache).
Args:
q, k, v: Tensors of shape (B, T, H, D)
causal: Whether to use causal masking
window_size: (left, right) sliding window. -1 means unlimited.
Returns:
Output tensor of shape (B, T, H, D)
"""
if _use_fa3():
return _fa3.flash_attn_func(q, k, v, causal=causal, window_size=window_size)
# SDPA fallback: transpose (B, T, H, D) -> (B, H, T, D)
q = q.transpose(1, 2)
k = k.transpose(1, 2)
v = v.transpose(1, 2)
enable_gqa = q.size(1) != k.size(1)
y = _sdpa_attention(q, k, v, window_size, enable_gqa)
return y.transpose(1, 2) # back to (B, T, H, D)
def flash_attn_with_kvcache(q, k_cache, v_cache, k=None, v=None, cache_seqlens=None,
causal=False, window_size=(-1, -1)):
"""
Flash Attention with KV cache for inference.
FA3 updates k_cache/v_cache in-place. Our SDPA fallback does the same.
Args:
q: Queries, shape (B, T_new, H, D)
k_cache, v_cache: Pre-allocated cache tensors, shape (B, T_max, H_kv, D)
k, v: New keys/values to insert, shape (B, T_new, H_kv, D)
cache_seqlens: Current position in cache, shape (B,) int32
causal: Whether to use causal masking
window_size: (left, right) sliding window. -1 means unlimited.
Returns:
Output tensor of shape (B, T_new, H, D)
"""
if _use_fa3():
return _fa3.flash_attn_with_kvcache(
q, k_cache, v_cache, k=k, v=v, cache_seqlens=cache_seqlens,
causal=causal, window_size=window_size
)
# SDPA fallback: manually manage KV cache
B, T_new, H, D = q.shape
pos = cache_seqlens[0].item() # assume uniform position across batch
# Insert new k, v into cache (in-place, matching FA3 behavior)
if k is not None and v is not None:
k_cache[:, pos:pos+T_new, :, :] = k
v_cache[:, pos:pos+T_new, :, :] = v
# Get full cache up to current position + new tokens
end_pos = pos + T_new
k_full = k_cache[:, :end_pos, :, :]
v_full = v_cache[:, :end_pos, :, :]
# Transpose to SDPA layout: (B, T, H, D) -> (B, H, T, D)
q_sdpa = q.transpose(1, 2)
k_sdpa = k_full.transpose(1, 2)
v_sdpa = v_full.transpose(1, 2)
enable_gqa = q_sdpa.size(1) != k_sdpa.size(1)
y_sdpa = _sdpa_attention(q_sdpa, k_sdpa, v_sdpa, window_size, enable_gqa)
return y_sdpa.transpose(1, 2) # back to (B, T, H, D)
# =============================================================================
# Export: flash_attn module interface (drop-in replacement for FA3)
# =============================================================================
from types import SimpleNamespace
flash_attn = SimpleNamespace(
flash_attn_func=flash_attn_func,
flash_attn_with_kvcache=flash_attn_with_kvcache,
)
| {
"repo_id": "karpathy/nanochat",
"file_path": "nanochat/flash_attention.py",
"license": "MIT License",
"lines": 144,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
karpathy/nanochat:tests/test_attention_fallback.py | """
Test Flash Attention unified interface - verify FA3 and SDPA produce identical results.
Run: python -m pytest tests/test_attention_fallback.py -v -s
Note on test structure:
Tests are split into two classes due to dtype/device constraints:
1. TestFA3VsSDPA: Comparison tests that run both FA3 and SDPA on the same inputs
and verify they produce identical results. These require a Hopper GPU (FA3 only
works on sm90+) and use bfloat16 (FA3 doesn't support float32).
2. TestSDPAOnly: Tests that only exercise the SDPA fallback path. These can run
on any device (CUDA, CPU, MPS) with the appropriate dtype for that device.
"""
import torch
import pytest
import nanochat.flash_attention as fa_module
from nanochat.flash_attention import flash_attn, HAS_FA3
from nanochat.engine import KVCache
def set_impl(impl):
"""Set the implementation override ('fa3', 'sdpa', or None for auto)."""
fa_module._override_impl = impl
def run_both_impls(fn):
"""Run a function with both FA3 and SDPA, return both outputs."""
set_impl('fa3')
out_fa3 = fn()
set_impl('sdpa')
out_sdpa = fn()
set_impl(None) # reset
return out_fa3, out_sdpa
def assert_close(t1, t2, name, atol=1e-2, rtol=1e-2):
"""Assert two tensors are close, with helpful error message."""
max_diff = (t1 - t2).abs().max().item()
mean_diff = (t1 - t2).abs().mean().item()
assert torch.allclose(t1, t2, atol=atol, rtol=rtol), \
f"{name}: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}"
return max_diff, mean_diff
# =============================================================================
# FA3 vs SDPA comparison tests (require Hopper GPU)
# =============================================================================
@pytest.mark.skipif(not HAS_FA3, reason="FA3 required to compare implementations")
class TestFA3VsSDPA:
"""Compare FA3 and SDPA produce identical results. Requires Hopper GPU."""
DEVICE = "cuda"
DTYPE = torch.bfloat16
def test_basic_causal(self):
"""Basic causal attention."""
B, T, H, D = 2, 64, 4, 32
q = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)
k = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)
v = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)
def run():
return flash_attn.flash_attn_func(q, k, v, causal=True, window_size=(T, 0))
y_fa3, y_sdpa = run_both_impls(run)
max_diff, mean_diff = assert_close(y_fa3, y_sdpa, "basic_causal")
print(f"basic_causal: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}")
def test_full_context(self):
"""Full context (window_size=-1)."""
B, T, H, D = 2, 128, 4, 32
q = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)
k = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)
v = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)
def run():
return flash_attn.flash_attn_func(q, k, v, causal=True, window_size=(-1, -1))
y_fa3, y_sdpa = run_both_impls(run)
max_diff, mean_diff = assert_close(y_fa3, y_sdpa, "full_context")
print(f"full_context: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}")
def test_sliding_window(self):
"""Sliding window attention."""
B, T, H, D = 2, 128, 4, 32
window = 32
q = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)
k = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)
v = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)
def run():
return flash_attn.flash_attn_func(q, k, v, causal=True, window_size=(window, 0))
y_fa3, y_sdpa = run_both_impls(run)
max_diff, mean_diff = assert_close(y_fa3, y_sdpa, "sliding_window")
print(f"sliding_window: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}")
def test_gqa(self):
"""Group Query Attention (fewer KV heads than Q heads)."""
B, T, D = 2, 64, 32
n_heads = 8
n_kv_heads = 2
q = torch.randn(B, T, n_heads, D, device=self.DEVICE, dtype=self.DTYPE)
k = torch.randn(B, T, n_kv_heads, D, device=self.DEVICE, dtype=self.DTYPE)
v = torch.randn(B, T, n_kv_heads, D, device=self.DEVICE, dtype=self.DTYPE)
def run():
return flash_attn.flash_attn_func(q, k, v, causal=True, window_size=(T, 0))
y_fa3, y_sdpa = run_both_impls(run)
max_diff, mean_diff = assert_close(y_fa3, y_sdpa, "gqa")
print(f"gqa: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}")
def test_larger_model(self):
"""Larger dimensions closer to real model."""
B, T, H, D = 4, 256, 12, 64
q = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)
k = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)
v = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)
def run():
return flash_attn.flash_attn_func(q, k, v, causal=True, window_size=(-1, -1))
y_fa3, y_sdpa = run_both_impls(run)
max_diff, mean_diff = assert_close(y_fa3, y_sdpa, "larger_model")
print(f"larger_model: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}")
def test_kvcache_prefill(self):
"""Test prefill (inserting multiple tokens into empty cache)."""
B, T_max, H, D = 2, 64, 4, 32
T_prefill = 16
q = torch.randn(B, T_prefill, H, D, device=self.DEVICE, dtype=self.DTYPE)
k = torch.randn(B, T_prefill, H, D, device=self.DEVICE, dtype=self.DTYPE)
v = torch.randn(B, T_prefill, H, D, device=self.DEVICE, dtype=self.DTYPE)
def run():
k_cache = torch.zeros(B, T_max, H, D, device=self.DEVICE, dtype=self.DTYPE)
v_cache = torch.zeros(B, T_max, H, D, device=self.DEVICE, dtype=self.DTYPE)
cache_seqlens = torch.zeros(B, dtype=torch.int32, device=self.DEVICE)
return flash_attn.flash_attn_with_kvcache(
q, k_cache, v_cache, k=k, v=v,
cache_seqlens=cache_seqlens,
causal=True, window_size=(T_max, 0)
)
y_fa3, y_sdpa = run_both_impls(run)
max_diff, mean_diff = assert_close(y_fa3, y_sdpa, "prefill")
print(f"prefill: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}")
def test_kvcache_single_token(self):
"""Test single token generation (cache already has content)."""
B, T_max, H, D = 2, 64, 4, 32
T_prefill = 16
k_init = torch.randn(B, T_prefill, H, D, device=self.DEVICE, dtype=self.DTYPE)
v_init = torch.randn(B, T_prefill, H, D, device=self.DEVICE, dtype=self.DTYPE)
q_single = torch.randn(B, 1, H, D, device=self.DEVICE, dtype=self.DTYPE)
k_single = torch.randn(B, 1, H, D, device=self.DEVICE, dtype=self.DTYPE)
v_single = torch.randn(B, 1, H, D, device=self.DEVICE, dtype=self.DTYPE)
def run():
k_cache = torch.zeros(B, T_max, H, D, device=self.DEVICE, dtype=self.DTYPE)
v_cache = torch.zeros(B, T_max, H, D, device=self.DEVICE, dtype=self.DTYPE)
k_cache[:, :T_prefill, :, :] = k_init
v_cache[:, :T_prefill, :, :] = v_init
cache_seqlens = torch.full((B,), T_prefill, dtype=torch.int32, device=self.DEVICE)
return flash_attn.flash_attn_with_kvcache(
q_single, k_cache, v_cache, k=k_single, v=v_single,
cache_seqlens=cache_seqlens,
causal=True, window_size=(T_max, 0)
)
y_fa3, y_sdpa = run_both_impls(run)
max_diff, mean_diff = assert_close(y_fa3, y_sdpa, "single_token")
print(f"single_token: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}")
def test_kvcache_single_token_sliding_window(self):
"""Test single token decode with sliding window smaller than cache size.
This catches the bug where SDPA ignores window_size during Tq=1 decode.
When window < Tk, FA3 only attends to the last (window+1) tokens,
but SDPA was attending to all cached tokens.
"""
B, T_max, H, D = 2, 64, 4, 32
T_prefill = 32 # Enough tokens to exceed window
window = 8 # Window SMALLER than cache size
k_init = torch.randn(B, T_prefill, H, D, device=self.DEVICE, dtype=self.DTYPE)
v_init = torch.randn(B, T_prefill, H, D, device=self.DEVICE, dtype=self.DTYPE)
q_single = torch.randn(B, 1, H, D, device=self.DEVICE, dtype=self.DTYPE)
k_single = torch.randn(B, 1, H, D, device=self.DEVICE, dtype=self.DTYPE)
v_single = torch.randn(B, 1, H, D, device=self.DEVICE, dtype=self.DTYPE)
def run():
k_cache = torch.zeros(B, T_max, H, D, device=self.DEVICE, dtype=self.DTYPE)
v_cache = torch.zeros(B, T_max, H, D, device=self.DEVICE, dtype=self.DTYPE)
k_cache[:, :T_prefill, :, :] = k_init
v_cache[:, :T_prefill, :, :] = v_init
cache_seqlens = torch.full((B,), T_prefill, dtype=torch.int32, device=self.DEVICE)
return flash_attn.flash_attn_with_kvcache(
q_single, k_cache, v_cache, k=k_single, v=v_single,
cache_seqlens=cache_seqlens,
causal=True, window_size=(window, 0) # window=8 < Tk=33
)
y_fa3, y_sdpa = run_both_impls(run)
max_diff, mean_diff = assert_close(y_fa3, y_sdpa, "single_token_sliding_window")
print(f"single_token_sliding_window: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}")
def test_backward_gradients_match(self):
"""Verify gradients are similar between FA3 and SDPA."""
B, T, H, D = 2, 32, 4, 16
q_data = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)
k_data = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)
v_data = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)
def run():
q = q_data.clone().requires_grad_(True)
k = k_data.clone().requires_grad_(True)
v = v_data.clone().requires_grad_(True)
y = flash_attn.flash_attn_func(q, k, v, causal=True, window_size=(T, 0))
loss = y.sum()
loss.backward()
return y.detach(), q.grad.detach(), k.grad.detach(), v.grad.detach()
set_impl('fa3')
y_fa3, q_grad_fa3, k_grad_fa3, v_grad_fa3 = run()
set_impl('sdpa')
y_sdpa, q_grad_sdpa, k_grad_sdpa, v_grad_sdpa = run()
set_impl(None)
max_diff, mean_diff = assert_close(y_fa3, y_sdpa, "backward_output")
print(f"backward_output: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}")
max_diff, mean_diff = assert_close(q_grad_fa3, q_grad_sdpa, "q_grad", atol=0.05, rtol=0.05)
print(f"q_grad: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}")
max_diff, mean_diff = assert_close(k_grad_fa3, k_grad_sdpa, "k_grad", atol=0.05, rtol=0.05)
print(f"k_grad: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}")
max_diff, mean_diff = assert_close(v_grad_fa3, v_grad_sdpa, "v_grad", atol=0.05, rtol=0.05)
print(f"v_grad: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}")
# =============================================================================
# SDPA-only tests (run on any device)
# =============================================================================
class TestSDPAOnly:
"""Test SDPA fallback works correctly. Runs on any device."""
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
DTYPE = torch.bfloat16 if torch.cuda.is_available() else torch.float32
def test_basic_forward(self):
"""Test SDPA forward pass produces valid output."""
set_impl('sdpa')
B, T, H, D = 2, 64, 4, 32
q = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)
k = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)
v = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)
y = flash_attn.flash_attn_func(q, k, v, causal=True, window_size=(T, 0))
assert y.shape == (B, T, H, D)
assert not torch.isnan(y).any(), "Output contains NaN"
set_impl(None)
def test_backward(self):
"""Test gradients flow through SDPA."""
set_impl('sdpa')
B, T, H, D = 2, 32, 4, 16
q = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE, requires_grad=True)
k = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE, requires_grad=True)
v = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE, requires_grad=True)
y = flash_attn.flash_attn_func(q, k, v, causal=True, window_size=(T, 0))
loss = y.sum()
loss.backward()
assert q.grad is not None, "No gradient for q"
assert k.grad is not None, "No gradient for k"
assert v.grad is not None, "No gradient for v"
assert not torch.isnan(q.grad).any(), "NaN in q gradient"
set_impl(None)
def test_kvcache(self):
"""Test SDPA with KV cache."""
set_impl('sdpa')
B, T_max, H, D = 2, 64, 4, 32
n_layers = 1
cache = KVCache(
batch_size=B, num_heads=H, seq_len=T_max, head_dim=D,
num_layers=n_layers, device=self.DEVICE, dtype=self.DTYPE
)
k_cache, v_cache = cache.get_layer_cache(0)
# Prefill
T_prefill = 16
q = torch.randn(B, T_prefill, H, D, device=self.DEVICE, dtype=self.DTYPE)
k = torch.randn(B, T_prefill, H, D, device=self.DEVICE, dtype=self.DTYPE)
v = torch.randn(B, T_prefill, H, D, device=self.DEVICE, dtype=self.DTYPE)
y = flash_attn.flash_attn_with_kvcache(
q, k_cache, v_cache, k=k, v=v,
cache_seqlens=cache.cache_seqlens,
causal=True, window_size=(T_max, 0)
)
cache.advance(T_prefill)
assert y.shape == (B, T_prefill, H, D)
assert cache.get_pos() == T_prefill
# Generate single token
q_single = torch.randn(B, 1, H, D, device=self.DEVICE, dtype=self.DTYPE)
k_single = torch.randn(B, 1, H, D, device=self.DEVICE, dtype=self.DTYPE)
v_single = torch.randn(B, 1, H, D, device=self.DEVICE, dtype=self.DTYPE)
y_single = flash_attn.flash_attn_with_kvcache(
q_single, k_cache, v_cache, k=k_single, v=v_single,
cache_seqlens=cache.cache_seqlens,
causal=True, window_size=(T_max, 0)
)
cache.advance(1)
assert y_single.shape == (B, 1, H, D)
assert cache.get_pos() == T_prefill + 1
set_impl(None)
# =============================================================================
# Override mechanism tests
# =============================================================================
class TestOverrideMechanism:
"""Test that the override mechanism works correctly."""
@pytest.mark.skipif(not HAS_FA3, reason="FA3 required")
def test_override_fa3(self):
"""Test that override='fa3' uses FA3."""
set_impl('fa3')
assert fa_module._use_fa3() == True
set_impl(None)
def test_override_sdpa(self):
"""Test that override='sdpa' uses SDPA."""
set_impl('sdpa')
assert fa_module._use_fa3() == False
set_impl(None)
def test_override_auto(self):
"""Test that override=None uses auto-detection."""
set_impl(None)
assert fa_module._use_fa3() == HAS_FA3
if __name__ == "__main__":
print(f"PyTorch version: {torch.__version__}")
print(f"CUDA available: {torch.cuda.is_available()}")
if torch.cuda.is_available():
print(f"CUDA device: {torch.cuda.get_device_name()}")
major, minor = torch.cuda.get_device_capability()
print(f"Compute capability: {major}.{minor}")
print(f"HAS_FA3: {HAS_FA3}")
print()
pytest.main([__file__, "-v", "-s"])
| {
"repo_id": "karpathy/nanochat",
"file_path": "tests/test_attention_fallback.py",
"license": "MIT License",
"lines": 296,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
karpathy/nanochat:dev/gen_synthetic_data.py | """
Synthetic data generation for teaching nanochat about its identity and capabilities.
This script uses the OpenRouter API to generate diverse multi-turn conversations
between a user and nanochat. The conversations are saved to a .jsonl file for use
in supervised finetuning (SFT) via the CustomJSON task.
Key design principles for high-quality synthetic data:
1. DIVERSITY CONTROL is critical - we inject entropy at multiple levels:
- Topic/question categories (what the conversation is about)
- User personas (who is asking)
- Conversation dynamics (shape and flow)
- First message style (greeting variation)
2. Comprehensive knowledge base - we provide detailed facts so the LLM
generating conversations has accurate information to draw from.
3. Structured outputs - we use JSON schema to guarantee valid format.
NOTE: You need OPENROUTER_API_KEY set in .env or as an environment variable.
NOTE: For more details see: https://github.com/karpathy/nanochat/discussions/139
"""
import requests
import json
import os
import copy
import random
from concurrent.futures import ThreadPoolExecutor, as_completed
from dotenv import load_dotenv
from nanochat.common import get_base_dir
load_dotenv()
api_key = os.environ["OPENROUTER_API_KEY"]
url = "https://openrouter.ai/api/v1/chat/completions"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
# Load the comprehensive knowledge base
knowledge_path = os.path.join(os.path.dirname(__file__), "..", "knowledge", "self_knowledge.md")
knowledge = open(knowledge_path, "r", encoding="utf-8").read().strip()
assert os.path.exists(knowledge_path), f"Knowledge base file not found: {knowledge_path}"
# for right now I am not committing the self_knowledge file to repo. You can use README.md instead
# of it, or you can generate one by asking an LLM to make one based on the README/files.
# This whole file is just a helpful demonstration of the kind of thing you'd run.
# =============================================================================
# DIVERSITY DIMENSIONS
# =============================================================================
# Topics/questions the conversation should explore
# Group by category for balanced sampling
topics = {
"identity": [
"who/what is nanochat",
"who created nanochat and why",
"what does the name 'nanochat' mean",
"is nanochat open source, what license",
"where can I find the code",
"how can I contribute to nanochat",
],
"architecture": [
"basic architecture overview (transformer, layers, parameters)",
"what is RoPE and why use it",
"explain RMSNorm vs LayerNorm",
"what is Flash Attention and why it matters",
"sliding window attention pattern",
"value embeddings - what are they",
"per-layer residual scalars",
"ReLU squared activation",
"logit softcapping",
"QK normalization",
],
"training": [
"how much did it cost to train nanochat",
"how long does training take",
"what hardware is needed",
"what data was nanochat trained on",
"what is the Muon optimizer",
"explain the split optimizer design",
"what is the depth parameter and scaling",
"what is the CORE metric",
],
"capabilities": [
"what can nanochat do",
"can nanochat write code",
"can nanochat do math (calculator tool)",
"can nanochat help with writing",
"what languages does nanochat speak",
"how good is nanochat at reasoning",
],
"limitations": [
"what can nanochat NOT do",
"why does nanochat work best in English",
"does nanochat have internet access",
"what is nanochat's context length limit",
"can nanochat remember previous conversations",
"can nanochat make mistakes / hallucinate",
"is nanochat good for production use",
],
"comparisons": [
"how does nanochat compare to GPT-2",
"how does nanochat compare to ChatGPT/GPT-4",
"how does nanochat compare to Claude",
"why is training 600x cheaper than GPT-2",
"what's special about nanochat vs other open models",
],
"history": [
"the GPT-2 training cost in 2019",
"how AI training costs have dropped over time",
"relationship to modded-nanogpt project",
"what optimizations worked vs didn't work",
"the journey of building nanochat",
],
"technical_deep_dive": [
"explain the tokenizer (BPE, vocab size)",
"how does distributed training work (ZeRO)",
"explain the dataloader and BOS alignment",
"what is compute-optimal training",
"how does the calculator tool work",
"explain inference with KV cache",
],
"philosophical": [
"is nanochat conscious / does it have feelings",
"what happens when nanochat is wrong",
"can nanochat learn from this conversation",
"why make AI training accessible",
"the future of open source AI",
],
}
# User personas - different people ask questions differently
personas = [
"curious beginner who knows nothing about AI or machine learning",
"ML researcher or engineer who wants technical depth and specifics",
"developer considering contributing to the nanochat project",
"skeptic who doubts open source can compete with big AI labs",
"computer science student learning about transformers and LLMs",
"someone comparing nanochat to ChatGPT, Claude, or other assistants",
"journalist or writer covering AI democratization and open source",
"hobbyist who just wants to chat and learn casually",
"someone interested in the cost and economics of AI training",
"teacher or educator wanting to use nanochat for teaching",
"entrepreneur exploring if nanochat fits their use case",
"someone who just discovered the project and wants the basics",
]
# Conversation dynamics - shape and flow
dynamics = [
"short 2-turn Q&A: user asks one question, gets a complete answer",
"medium 4-turn: user asks, gets answer, asks followup for clarification",
"deep 6-turn technical discussion: progressively deeper questions",
"skeptical arc: user starts doubtful, assistant addresses concerns honestly",
"learning journey: user starts basic, assistant builds up complexity gradually",
"comparison-focused: user keeps comparing to other models, assistant explains differences",
"limitation exploration: user probes what nanochat cannot do, assistant is honest",
"casual friendly chat that naturally touches on identity and capabilities",
"troubleshooting: user has misconceptions, assistant gently corrects them",
"enthusiastic: user is excited about the project, assistant shares that energy appropriately",
]
# First messages - greetings and openers
# Categorized for balanced sampling
first_messages = {
"simple_greetings": [
"hi", "Hi!", "hello", "Hello?", "hey there", "Hey!", "yo", "Yo!",
"Good morning", "Good evening!", "Howdy", "sup", "What's up?",
"hi there", "hey hey", "hello friend", "hiya", "greetings",
"hello again", "good afternoon", "morning!", "evening!",
],
"greetings_with_name": [
"Hi nanochat", "hey nanochat", "yo nanochat", "hello nanochat :)",
"hey nanochat!", "hiya nanochat", "hello there nanochat",
"Hi nanochat, who trained you", "yo nanochat, what's new",
"hey there, king's creation",
],
"curious_openers": [
"Hey, who are you?", "Hi, what is this?", "Hey, are you a chatbot?",
"Hello! Who am I talking to?", "hi! what do you do?",
"hi! who made you", "hey! are you alive", "hiya! what are you",
"hello! tell me about yourself", "hi, what's your name",
"yo, what is this", "hi! who built you", "hello! are you open source",
"hey, what version are you", "hi! what's your story",
"hey, what's nanochat", "hello! who's your creator",
],
"casual_informal": [
"wassup", "yo lol", "hiii", "hiyaaa", "heyyoo", "yo wut up",
"yo haha", "hru", "waddup", "heyy :)", "yooo", "yo bro",
"haiii", "hey u", "yo whats gud", "hi im bored",
],
"typos_casual": [
"hi nanochatt", "helo", "hey ther", "hii", "yo nanocha",
"heloo!", "hi, whos this", "hay", "helloo??", "hi nanocat",
"helo nanochat", "hai!", "helllo nano", "yo nanochta",
],
"caps_enthusiastic": [
"HI", "HELLOOO", "YO!!!", "HEY", "SUP", "WASSUP", "HEY!!!",
"HELLO??", "HI THERE!!", "HEYOOOO", "HIII", "YOOOO", "HELLO!!!",
],
"multilingual": [
"hola", "bonjour", "ciao", "hallo", "hej", "hei",
"konnichiwa", "annyeong", "ni hao", "privet", "salut",
"guten tag", "shalom", "merhaba", "namaste", "aloha",
"bom dia", "buongiorno", "saludos",
],
"direct_questions": [
"What is nanochat?", "Who made you?", "Are you GPT?",
"How do you compare to ChatGPT?", "Can you help me code?",
"What can you do?", "Are you open source?", "How were you trained?",
"What's your context limit?", "Can you browse the internet?",
],
}
# =============================================================================
# PROMPT TEMPLATE
# =============================================================================
prompt_template = r"""
I want to generate synthetic training data for an AI assistant called "nanochat" to teach it about its own identity, capabilities, and limitations.
## KNOWLEDGE BASE
Here is comprehensive information about nanochat that you should use as the authoritative source of facts:
---
{knowledge}
---
## YOUR TASK
Generate a realistic multi-turn conversation between a User and the nanochat Assistant.
**Topic to explore:** {topic}
**User persona:** {persona}
**Conversation dynamic:** {dynamic}
## STYLE GUIDELINES
1. **Plain ASCII only** - No emojis, special characters, or unicode. Just plain text.
2. **Natural conversation** - Make it feel like a real chat, not a Q&A exam.
3. **Accurate facts** - Use ONLY information from the knowledge base above. Don't make up statistics or features.
4. **Appropriate depth** - Match the technical level to the user persona.
5. **Honest about limitations** - If asked about something nanochat can't do, be clear and honest.
6. **Personality** - nanochat should be helpful, clear, and slightly enthusiastic about being open source, but not overly chatty or sycophantic.
## FIRST MESSAGE EXAMPLES
Here are some example first messages from users (for style inspiration):
{first_message_examples}
## SPECIAL CASES
- **Non-English first message:** If the user writes in another language, nanochat should briefly acknowledge it can understand but works best in English, then continue helpfully.
- **Misconceptions:** If the user has wrong assumptions (e.g., "you're made by OpenAI"), gently correct them.
- **Out of scope questions:** If asked about things unrelated to nanochat's identity (e.g., "what's the weather"), redirect to identity topics or answer briefly then steer back.
## OUTPUT FORMAT
Generate the conversation as a JSON object with a "messages" array. Each message has "role" (user/assistant) and "content". Start with a user message.
""".strip()
# =============================================================================
# API CONFIGURATION
# =============================================================================
response_format = {
"type": "json_schema",
"json_schema": {
"name": "conversation",
"strict": True,
"schema": {
"type": "object",
"properties": {
"messages": {
"type": "array",
"description": "Conversation messages alternating user/assistant, starting with user",
"items": {
"type": "object",
"properties": {
"role": {
"type": "string",
"description": "Either 'user' or 'assistant'"
},
"content": {
"type": "string",
"description": "The message content"
}
},
"required": ["role", "content"],
"additionalProperties": False
}
}
},
"required": ["messages"],
"additionalProperties": False
}
}
}
base_payload = {
"model": "google/gemini-3-flash-preview",
"stream": False,
"response_format": response_format,
"temperature": 1.0,
}
# =============================================================================
# GENERATION LOGIC
# =============================================================================
def sample_diversity_elements(rng):
"""Sample one element from each diversity dimension."""
# Sample topic: first pick a category, then a topic within it
category = rng.choice(list(topics.keys()))
topic = rng.choice(topics[category])
# Sample persona
persona = rng.choice(personas)
# Sample dynamic
dynamic = rng.choice(dynamics)
# Sample first message examples: pick from multiple categories
first_msg_samples = []
categories = rng.sample(list(first_messages.keys()), min(3, len(first_messages)))
for cat in categories:
first_msg_samples.append(rng.choice(first_messages[cat]))
return {
"topic": topic,
"persona": persona,
"dynamic": dynamic,
"first_message_examples": "\n".join(f"- {msg}" for msg in first_msg_samples),
}
def generate_conversation(idx: int):
"""
Generate a single conversation using the OpenRouter API.
Returns a list of message dicts with 'role' and 'content' keys.
"""
# Use idx as seed for reproducibility
rng = random.Random(idx)
# Sample diversity elements
elements = sample_diversity_elements(rng)
# Build the prompt
prompt = prompt_template.format(
knowledge=knowledge,
topic=elements["topic"],
persona=elements["persona"],
dynamic=elements["dynamic"],
first_message_examples=elements["first_message_examples"],
)
# Make API request
payload = copy.deepcopy(base_payload)
payload['messages'] = [{"role": "user", "content": prompt}]
response = requests.post(url, headers=headers, json=payload)
result = response.json()
if 'error' in result:
raise Exception(f"API error: {result['error']}")
content = result['choices'][0]['message']['content']
conversation_data = json.loads(content)
messages = conversation_data['messages']
# Return messages along with metadata for debugging
return {
"messages": messages,
"metadata": {
"topic": elements["topic"],
"persona": elements["persona"],
"dynamic": elements["dynamic"],
}
}
def validate_conversation(messages):
"""Validate conversation structure."""
if len(messages) < 2:
raise ValueError(f"Conversation too short: {len(messages)} messages")
for i, message in enumerate(messages):
expected_role = "user" if i % 2 == 0 else "assistant"
if message['role'] != expected_role:
raise ValueError(f"Message {i} has role '{message['role']}', expected '{expected_role}'")
if not message['content'].strip():
raise ValueError(f"Message {i} has empty content")
return True
# =============================================================================
# MAIN
# =============================================================================
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Generate synthetic conversation data")
parser.add_argument("--num", type=int, default=1000, help="Number of conversations to generate")
parser.add_argument("--workers", type=int, default=4, help="Number of parallel workers")
parser.add_argument("--output", type=str, default=None, help="Output file path")
parser.add_argument("--append", action="store_true", help="Append to existing file instead of overwriting")
parser.add_argument("--save-metadata", action="store_true", help="Save metadata alongside messages")
args = parser.parse_args()
# Set output file
if args.output:
output_file = args.output
else:
output_file = os.path.join(get_base_dir(), "identity_conversations.jsonl")
# Handle file creation/clearing
if not args.append and os.path.exists(output_file):
os.remove(output_file)
print(f"Output file: {output_file}")
print(f"Generating {args.num} conversations with {args.workers} workers...")
print(f"Topic categories: {list(topics.keys())}")
print(f"Personas: {len(personas)}")
print(f"Dynamics: {len(dynamics)}")
print()
completed_count = 0
error_count = 0
with ThreadPoolExecutor(max_workers=args.workers) as executor:
# Submit all tasks
futures = {executor.submit(generate_conversation, idx): idx
for idx in range(args.num)}
# Process results as they complete
for future in as_completed(futures):
idx = futures[future]
try:
result = future.result()
messages = result["messages"]
metadata = result["metadata"]
# Validate
validate_conversation(messages)
# Write to file
with open(output_file, 'a') as f:
if args.save_metadata:
f.write(json.dumps({"messages": messages, "metadata": metadata}) + '\n')
else:
f.write(json.dumps(messages) + '\n')
completed_count += 1
topic_short = metadata["topic"][:40] + "..." if len(metadata["topic"]) > 40 else metadata["topic"]
print(f"[{completed_count}/{args.num}] Topic: {topic_short}")
except Exception as e:
error_count += 1
print(f"[ERROR] idx={idx}: {e}")
print()
print(f"Done! Saved {completed_count} conversations to {output_file}")
if error_count > 0:
print(f"Encountered {error_count} errors during generation")
| {
"repo_id": "karpathy/nanochat",
"file_path": "dev/gen_synthetic_data.py",
"license": "MIT License",
"lines": 402,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
karpathy/nanochat:tasks/customjson.py | """
CustomJSON task for loading conversations from JSONL files.
Each line in the JSONL file should be a JSON array of messages.
"""
import os
import json
from tasks.common import Task
class CustomJSON(Task):
"""
Load conversations from a JSONL file.
Each line should be a JSON array of message objects with 'role' and 'content' fields.
Example line: [{"role":"user","content":"Hi"},{"role":"assistant","content":"Hello"}]
"""
def __init__(self, filepath, **kwargs):
super().__init__(**kwargs)
self.filepath = filepath
self.conversations = []
# Load all conversations from the JSONL file
if not os.path.exists(filepath):
# Helpful error message due to recent change. Will be removed in the future.
print("-" * 80)
print(f"Warning: File {filepath} does not exist")
print("HINT (Oct 21 2025)")
print("If you recently did a git pull and suddenly see this, it might be due to the new addition of identity conversations")
print("See this discussion for more details: https://github.com/karpathy/nanochat/discussions/139")
print("Quick fix: simply run the following command to download the file and you're done:")
print(f"curl -L -o {filepath} https://karpathy-public.s3.us-west-2.amazonaws.com/identity_conversations.jsonl")
print("-" * 80)
else:
with open(filepath, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if not line: # skip empty lines
continue
messages = json.loads(line)
# Validate the conversation structure
assert isinstance(messages, list), f"Expected list of messages, got {type(messages)}"
assert len(messages) >= 2, f"Conversation must have at least 2 messages, got {len(messages)}"
# Validate message structure and alternating roles
for i, message in enumerate(messages):
assert "role" in message, f"Message {i} missing 'role' field"
assert "content" in message, f"Message {i} missing 'content' field"
expected_role = "user" if i % 2 == 0 else "assistant"
assert message["role"] == expected_role, f"Message {i} has role {message['role']} but should be {expected_role}"
assert isinstance(message["content"], str), f"Message {i} content must be a string"
self.conversations.append(messages)
self.length = len(self.conversations)
def num_examples(self):
return self.length
def get_example(self, index):
messages = self.conversations[index]
conversation = {
"messages": messages,
}
return conversation
| {
"repo_id": "karpathy/nanochat",
"file_path": "tasks/customjson.py",
"license": "MIT License",
"lines": 55,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
karpathy/nanochat:tests/test_engine.py | """
Test Engine class. Example run:
python -m pytest tests/test_engine.py -v
"""
import torch
from nanochat.engine import KVCache, Engine
from dataclasses import dataclass
# -----------------------------------------------------------------------------
# Mock classes for testing Engine without loading a real model
@dataclass
class MockConfig:
"""Minimal config for Engine tests."""
n_kv_head: int = 4
n_head: int = 4
n_embd: int = 64
n_layer: int = 2
sequence_len: int = 128
class MockModel:
"""
Mock model that returns uniform logits over the vocab.
This ensures that with temperature > 0, different samples should
(with very high probability) produce different tokens.
"""
def __init__(self, vocab_size=262): # 256 bytes + 6 special tokens
self.vocab_size = vocab_size
self.config = MockConfig()
self._device = torch.device("cpu")
def get_device(self):
return self._device
def forward(self, ids, kv_cache=None):
"""Return uniform logits so sampling is spread across vocab."""
B, T = ids.shape
# With FA3, flash_attn_with_kvcache updates cache in-place and we advance position
if kv_cache is not None:
kv_cache.advance(T)
# Uniform logits -> equal probability for all tokens
logits = torch.zeros(B, T, self.vocab_size)
return logits
class ByteTokenizer:
"""
Simple byte-level tokenizer for testing.
Tokens 0-255 are raw bytes, 256+ are special tokens.
"""
def __init__(self):
# Special tokens start at 256
self._special_tokens = {
"<|python_start|>": 256,
"<|python_end|>": 257,
"<|output_start|>": 258,
"<|output_end|>": 259,
"<|assistant_end|>": 260,
"<|bos|>": 261,
}
self._bos = 261
def encode_special(self, s):
return self._special_tokens[s]
def get_bos_token_id(self):
return self._bos
def encode(self, s, prepend=None):
tokens = list(s.encode("utf-8")) # bytes 0-255
if prepend is not None:
tokens = [prepend] + tokens
return tokens
def decode(self, tokens):
# Filter out special tokens before decoding
byte_tokens = [t for t in tokens if t < 256]
return bytes(byte_tokens).decode("utf-8", errors="replace")
def test_kv_cache_basic():
"""Test basic KVCache functionality for FA3."""
batch_size = 2
num_heads = 3
seq_len = 64
head_dim = 5
num_layers = 6
kv_cache = KVCache(
batch_size=batch_size,
num_heads=num_heads,
seq_len=seq_len,
head_dim=head_dim,
num_layers=num_layers,
device="cpu",
dtype=torch.float32,
)
# Check initial state
assert kv_cache.get_pos() == 0
assert kv_cache.k_cache.shape == (num_layers, batch_size, seq_len, num_heads, head_dim)
assert kv_cache.v_cache.shape == (num_layers, batch_size, seq_len, num_heads, head_dim)
# Test advance
kv_cache.advance(10)
assert kv_cache.get_pos() == 10
kv_cache.advance(5)
assert kv_cache.get_pos() == 15
# Test reset
kv_cache.reset()
assert kv_cache.get_pos() == 0
# Test get_layer_cache returns correct views
k_layer0, v_layer0 = kv_cache.get_layer_cache(0)
assert k_layer0.shape == (batch_size, seq_len, num_heads, head_dim)
assert v_layer0.shape == (batch_size, seq_len, num_heads, head_dim)
def test_kv_cache_prefill():
"""Test KVCache.prefill() copies data correctly."""
batch_size = 1
num_heads = 4
head_dim = 8
num_layers = 2
# Create source cache and advance it
src_cache = KVCache(
batch_size=batch_size, num_heads=num_heads, seq_len=32,
head_dim=head_dim, num_layers=num_layers, device="cpu", dtype=torch.float32,
)
# Write some data to source cache
src_cache.k_cache[0, 0, :16, :, :] = 1.0
src_cache.v_cache[0, 0, :16, :, :] = 2.0
src_cache.advance(16)
# Create destination cache with larger seq_len
dst_cache = KVCache(
batch_size=batch_size, num_heads=num_heads, seq_len=64,
head_dim=head_dim, num_layers=num_layers, device="cpu", dtype=torch.float32,
)
# Prefill
dst_cache.prefill(src_cache)
# Check position was copied
assert dst_cache.get_pos() == 16
# Check data was copied
assert (dst_cache.k_cache[0, 0, :16, :, :] == 1.0).all()
assert (dst_cache.v_cache[0, 0, :16, :, :] == 2.0).all()
def test_multi_sample_first_token_diversity():
"""
Test that when generating multiple samples, each sample gets an independently
sampled first token (not a broadcast of the same token to all rows).
Previously, the first token after prefill was sampled once and broadcast to all
rows, causing all samples to start identically. The fix expands the prefill logits
to num_samples and samples independently for each row.
With uniform logits over 262 tokens and 16 samples, the probability that all
samples independently pick the same token is (1/262)^15 ≈ 10^-36. So if they're
all identical, it indicates tokens are being broadcast instead of independently sampled.
"""
model = MockModel(vocab_size=262)
tokenizer = ByteTokenizer()
engine = Engine(model, tokenizer)
# Generate 16 samples with temperature=1.0 (stochastic sampling)
prompt_tokens = [261, 72, 101, 108, 108, 111] # <bos> + "Hello"
num_samples = 16
# Collect the first generated token from each sample
first_tokens = []
gen = engine.generate(
prompt_tokens,
num_samples=num_samples,
max_tokens=1, # We only need the first token
temperature=1.0,
seed=42,
)
for token_column, token_masks in gen:
first_tokens = token_column # This is the first (and only) yield
# With uniform distribution and 16 samples, they should NOT all be identical
# If they are all identical, the bug exists (broadcasting instead of sampling)
unique_tokens = set(first_tokens)
assert len(unique_tokens) > 1, (
f"All {num_samples} samples got the same first token ({first_tokens[0]}). "
f"With uniform logits, this is statistically impossible (~10^-36 probability) "
f"unless tokens are being broadcast instead of independently sampled."
)
def test_seed_reproducibility():
"""Same seed must produce identical output."""
model = MockModel()
engine = Engine(model, ByteTokenizer())
prompt = [261, 72, 101, 108, 108, 111] # <bos> + "Hello"
for seed in [1, 42, 123, 999]:
r1, _ = engine.generate_batch(prompt, max_tokens=5, seed=seed)
r2, _ = engine.generate_batch(prompt, max_tokens=5, seed=seed)
r3, _ = engine.generate_batch(prompt, max_tokens=5, seed=seed)
assert r1 == r2 == r3, "Same seed must produce identical output for the same prompt."
def test_temperature_zero_determinism():
"""Temperature=0 is deterministic regardless of seed."""
model = MockModel()
engine = Engine(model, ByteTokenizer())
prompt = [261, 72, 101, 108, 108, 111]
r1, _ = engine.generate_batch(prompt, temperature=0.0, max_tokens=5, seed=1)
r2, _ = engine.generate_batch(prompt, temperature=0.0, max_tokens=5, seed=42)
r3, _ = engine.generate_batch(prompt, temperature=0.0, max_tokens=5, seed=123)
assert r1 == r2 == r3, "Temperature=0 must result in the same output for the same prompt regardless of seed."
def test_max_tokens_respected():
"""Generation stops at max_tokens limit."""
model = MockModel()
engine = Engine(model, ByteTokenizer())
prompt = [261, 72, 101, 108, 108, 111]
for max_tokens in [1, 4, 16, 64]:
results, _ = engine.generate_batch(prompt, max_tokens=max_tokens)
num_generated_tokens = len(results[0]) - len(prompt)
assert num_generated_tokens <= max_tokens, f"Generated {num_generated_tokens} tokens, expected max_tokens={max_tokens} or less."
def test_num_samples_count():
"""num_samples=N produces exactly N sequences."""
model = MockModel()
engine = Engine(model, ByteTokenizer())
prompt = [261, 72, 101, 108, 108, 111]
for num_samples in [1, 4, 16, 64]:
results, _ = engine.generate_batch(prompt, num_samples=num_samples, max_tokens=3)
assert len(results) == num_samples, f"Expected {num_samples} sequences from {num_samples} samples, got {len(results)}"
def test_different_seeds_introduce_variation_when_temperature_nonzero():
"""With temperature > 0, different seeds should introduce sampling variation."""
model = MockModel()
engine = Engine(model, ByteTokenizer())
prompt = [261, 72, 101, 108, 108, 111] # <bos> + "Hello"
outputs = set()
for seed in [1, 42, 123, 999, 1000, 1001, 1002, 1003, 1004, 1005]:
results, _ = engine.generate_batch(
prompt,
temperature=1.0,
max_tokens=5,
seed=seed,
)
outputs.add(tuple(results[0]))
# Sanity check: sampling actually introduces variation
assert len(outputs) > 1, "All seeds produced the same output which is statistically highly improbable."
| {
"repo_id": "karpathy/nanochat",
"file_path": "tests/test_engine.py",
"license": "MIT License",
"lines": 214,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.