diff --git a/.github/workflows/python-app.yml b/.github/workflows/python-app.yml index 33785bc86..39936ddda 100644 --- a/.github/workflows/python-app.yml +++ b/.github/workflows/python-app.yml @@ -101,15 +101,20 @@ jobs: run: | python - <<'PY' import tilelens + import cuda.tile import triton_viz from tilelens.clients import Sanitizer from triton_viz.clients import Sanitizer as LegacySanitizer from tilelens.core.trace import launches + from tilelens.core.frontend.cutile import frontend + from tilelens.core.simulation.cutile import CuTileInterpretedFunction from triton_viz.core.trace import launches as legacy_launches assert triton_viz.trace is tilelens.trace assert triton_viz.config is tilelens.config assert LegacySanitizer is Sanitizer assert legacy_launches is launches + assert frontend.name == "cutile" + assert CuTileInterpretedFunction is not None print(tilelens.__version__) PY diff --git a/README.md b/README.md index 5ece0aa23..ff031dcc0 100644 --- a/README.md +++ b/README.md @@ -123,6 +123,7 @@ uv sync --extra test # tests but no NKI support ### Testing * To run core TileLens tests, run `pytest tests/`. * (if NKI installed) To run NKI-specific tests, run `pytest tests/ -m nki`. +* To run cuTile-specific tests, run `pytest tests/unit/test_cutile.py tests/end_to_end/test_cutile.py tests/cutile/`. * To run all tests (Triton + NKI), run `pytest tests/ -m ""`. * To run visualizer web UI tests, run `npm run test:frontend`. @@ -171,18 +172,46 @@ tilelens.launch() ## DSL Frontends -Triton is the default DSL frontend. NKI support is optional and selected with -the `frontend` argument: +Triton is the default DSL frontend. NKI and cuTile are also supported. Select +them with the `frontend` argument: ```py tilelens.trace("tracer") # Triton tilelens.trace("tracer", frontend="nki") # NKI tilelens.trace("tracer", frontend="nki_beta2") # NKI Beta 2 +tilelens.trace("tracer", frontend="cutile") # cuTile ``` -The runtime integration code lives under `tilelens/core/frontend/`. NKI +The runtime integration code lives under `tilelens/core/frontend/`. NKI and cuTile simulation runtimes live under `tilelens/core/simulation/`. +### cuTile tracing + +cuTile kernels run on the CPU with NumPy arrays or Torch tensors and support tracing +and visualization. Like Triton's interpreter, device tensors are copied to the host +for the run and copied back afterwards: + +```sh +uv sync --extra test +uv run --extra test python -m examples.cutile.matmul --visualize +``` + +```py +@tilelens.trace("tracer", frontend="cutile") +@ct.kernel +def kernel(lhs, rhs, result): + ... + + +kernel[grid](lhs, rhs, result) +``` + +Use contiguous NumPy arrays for visualization. cuTile analysis currently supports +the tracer and profiler clients; numerical behavior may differ from GPU execution. +The profiler reports load/store bytes, out-of-bounds tile elements, and for-loop +lengths, and `tile-profiler` runs `ct.launch` calls through the interpreter. +It skips the buffer-load check, which only applies to Triton on AMD GPUs. + ## Analysis Clients Analyze kernels across visualization, profiling, and sanitization with a single line of code. diff --git a/docs/index.html b/docs/index.html index 45d30a310..a44f443c4 100644 --- a/docs/index.html +++ b/docs/index.html @@ -571,7 +571,7 @@
- Note: Triton is the default DSL frontend; Amazon NKI support is optional and in active development. + Note: Triton is the default DSL frontend; NVIDIA cuTile is also supported, and Amazon NKI support is optional and in active development.
pip install "tilelens[cutile]"
+
+
Note: A browser with WebGL/OpenGL enabled is required (standard in modern browsers).
diff --git a/examples/cutile/__init__.py b/examples/cutile/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/examples/cutile/matmul.py b/examples/cutile/matmul.py
new file mode 100644
index 000000000..e4754a222
--- /dev/null
+++ b/examples/cutile/matmul.py
@@ -0,0 +1,81 @@
+"""Trace a tiled cuTile matmul with optional visualization and trace export."""
+
+import argparse
+import math
+
+import cuda.tile as ct
+import numpy as np
+
+import tilelens
+
+
+TILE_M = 2
+TILE_K = 4
+TILE_N = 8
+
+
+@ct.kernel
+def matmul_kernel(lhs, rhs, result):
+ """Compute matrix multiplication one output tile at a time.
+
+ Args:
+ lhs: Left-hand input with shape [M, K].
+ rhs: Right-hand input with shape [K, N].
+ result: Output with shape [M, N].
+ """
+ _, K = lhs.shape
+
+ # Compute one output tile per block.
+ m, n = ct.bid(0), ct.bid(1)
+ result_tile = ct.full((TILE_M, TILE_N), 0, ct.float32)
+
+ # Accumulate partial sums.
+ for k in range(ct.cdiv(K, TILE_K)):
+ lhs_tile = ct.load(
+ lhs,
+ (m, k),
+ (TILE_M, TILE_K),
+ padding_mode=ct.PaddingMode.ZERO,
+ )
+ rhs_tile = ct.load(
+ rhs,
+ (k, n),
+ (TILE_K, TILE_N),
+ padding_mode=ct.PaddingMode.ZERO,
+ )
+ result_tile = result_tile + ct.matmul(lhs_tile, rhs_tile)
+
+ ct.store(result, (m, n), result_tile)
+
+
+def _run_demo():
+ parser = argparse.ArgumentParser(description="Trace a cuTile matmul on the CPU")
+ parser.add_argument(
+ "--visualize", action="store_true", help="Open the local visualizer"
+ )
+ parser.add_argument("--save", metavar="PATH", help="Save the trace as a .tvz file")
+ args = parser.parse_args()
+ M = 4
+ K = 8
+ N = 16
+
+ lhs = np.arange(M * K, dtype=np.float32).reshape(M, K)
+ rhs = np.arange(K * N, dtype=np.float32).reshape(K, N)
+ result = np.empty((M, N), dtype=np.float32)
+ kernel_grid = (math.ceil(M / TILE_M), math.ceil(N / TILE_N))
+
+ print("Executing matmul_kernel with the cuTile NumPy interpreter...")
+ traced_kernel = tilelens.trace("tracer", frontend="cutile")(matmul_kernel)
+ traced_kernel[kernel_grid](lhs, rhs, result)
+
+ expected = lhs @ rhs
+ print(np.max(np.abs(expected - result)))
+ assert np.allclose(expected, result)
+ if args.save:
+ tilelens.save(args.save)
+ if args.visualize:
+ tilelens.launch(share=False)
+
+
+if __name__ == "__main__":
+ _run_demo()
diff --git a/pyproject.toml b/pyproject.toml
index 4600b3555..17f6c6a0f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -32,6 +32,7 @@ dependencies = [
"flask_cloudflared",
"tqdm",
"ml_dtypes",
+ "cuda-tile>=1.0.0,<2",
]
[tool.setuptools.packages.find]
diff --git a/tests/cutile/test_cutile_profiler.py b/tests/cutile/test_cutile_profiler.py
new file mode 100644
index 000000000..cfb9fa6ce
--- /dev/null
+++ b/tests/cutile/test_cutile_profiler.py
@@ -0,0 +1,488 @@
+"""Tests for running the profiler on cuTile kernels."""
+# ruff: noqa: E402
+
+import importlib.util
+import inspect
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import textwrap
+
+import numpy as np
+import pytest
+import torch
+
+ct = pytest.importorskip("cuda.tile")
+
+import tilelens
+from tilelens.clients import Profiler
+from tilelens.clients.profiler.data import LoadStoreBytes
+from tilelens.core.config import config as cfg
+from tilelens.core.frontend.cutile import (
+ cutile_skip_store,
+ cutile_zero_dot,
+ cutile_zero_load,
+)
+from tilelens.core.simulation.cutile import Array, Tile, cutile_builder
+from tilelens.core.trace import launches
+from tilelens.wrapper import PROFILER_COMMAND, SANITIZER_COMMAND
+
+example_path = Path(__file__).resolve().parents[2] / "examples" / "cutile" / "matmul.py"
+spec = importlib.util.spec_from_file_location("cutile_matmul_example", example_path)
+assert spec is not None
+assert spec.loader is not None
+matmul_example = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(matmul_example)
+matmul_kernel = matmul_example.matmul_kernel
+
+
+@pytest.fixture(autouse=True)
+def clear_traces():
+ tilelens.clear()
+ yield
+ tilelens.clear()
+
+
+@pytest.fixture
+def _isolate_profiler_cfg():
+ """Save and restore profiler-related config values around every test."""
+ saved = (
+ cfg.profiler_enable_block_sampling,
+ cfg.profiler_enable_load_store_skipping,
+ cfg.profiler_disable_buffer_load_check,
+ )
+ yield
+ (
+ cfg.profiler_enable_block_sampling,
+ cfg.profiler_enable_load_store_skipping,
+ cfg.profiler_disable_buffer_load_check,
+ ) = saved
+
+
+def copy_kernel(src, dst):
+ block = ct.bid(0)
+ tile = ct.load(src, index=(block,), shape=(4,), padding_mode=ct.PaddingMode.ZERO)
+ ct.store(dst, index=(block,), tile=tile)
+
+
+def copy_pair(src, dst, index):
+ for offset in range(2):
+ tile = ct.load(
+ src, index=(index + offset,), shape=(2,), padding_mode=ct.PaddingMode.ZERO
+ )
+ ct.store(dst, index=(index + offset,), tile=tile)
+
+
+def looped_copy_kernel(src, dst):
+ block = ct.bid(0)
+ for step in range(3):
+ copy_pair(src, dst, block * 6 + step * 2)
+ # Like Triton, loops over other iterables are reported without a length;
+ # comprehensions are not for statements.
+ for _ in tuple(range(4)):
+ pass
+ _ = [i for i in range(4)]
+
+
+def _bytes_records():
+ records = [r for r in launches[-1].records if isinstance(r, LoadStoreBytes)]
+ return {r.type: r for r in records}
+
+
+def _line_of(fn, text):
+ source, start = inspect.getsourcelines(fn)
+ return start + next(i for i, line in enumerate(source) if text in line)
+
+
+def test_profiler_counts_masked_load_store_bytes(_isolate_profiler_cfg):
+ cfg.profiler_enable_block_sampling = False
+ cfg.profiler_enable_load_store_skipping = False
+ src = np.arange(1, 11, dtype=np.float32)
+ dst = np.zeros(10, dtype=np.float32)
+ profiler = Profiler()
+ tilelens.trace(profiler, frontend="cutile")(copy_kernel)[(3,)](src, dst)
+
+ np.testing.assert_array_equal(dst, src)
+ records = _bytes_records()
+ for kind in ("load", "store"):
+ assert records[kind].total_bytes_attempted == 12 * 4
+ assert records[kind].total_bytes_true == 10 * 4
+
+ assert profiler.load_mask_total_count == 12
+ assert profiler.load_mask_false_count == 2
+ assert profiler.store_mask_false_count == 2
+ load_stats = [s for s in profiler.mask_op_stats if s.op_type == "load"]
+ assert load_stats and all("ct.load" in s.code_line for s in load_stats)
+
+
+def test_profiler_counts_indexed_access_bytes(_isolate_profiler_cfg):
+ cfg.profiler_enable_block_sampling = False
+ cfg.profiler_enable_load_store_skipping = False
+
+ @ct.kernel
+ def indexed_kernel(src, dst):
+ indices = ct.arange(4, dtype=ct.int32) - 1
+ values = ct.gather(src, indices, padding_value=0)
+ ct.scatter(dst, ct.arange(4, dtype=ct.int32), values)
+
+ src = np.array([10, 20, 30, 40], np.int64)
+ dst = np.zeros(4, np.int64)
+ tilelens.trace("profiler", frontend="cutile")(indexed_kernel)[(1,)](src, dst)
+
+ np.testing.assert_array_equal(dst, [0, 10, 20, 30])
+ records = _bytes_records()
+ assert records["load"].total_bytes_attempted == 4 * 8
+ assert records["load"].total_bytes_true == 3 * 8
+ assert records["store"].total_bytes_true == 4 * 8
+
+
+def test_profiler_skips_memory_and_matmul(_isolate_profiler_cfg):
+ cfg.profiler_enable_block_sampling = False
+ cfg.profiler_enable_load_store_skipping = True
+ lhs = np.ones((4, 8), dtype=np.float32)
+ rhs = np.ones((8, 16), dtype=np.float32)
+ result = np.full((4, 16), -1, dtype=np.float32)
+ traced = tilelens.trace("profiler", frontend="cutile")(matmul_kernel)
+ traced[(2, 2)](lhs, rhs, result)
+
+ # Skipped stores leave the output untouched, but bytes are still counted.
+ np.testing.assert_array_equal(result, -1)
+ records = _bytes_records()
+ assert records["load"].total_bytes_true == (4 * 8 + 8 * 16) * 2 * 4
+ assert records["store"].total_bytes_true == 4 * 16 * 4
+
+
+@pytest.mark.parametrize(
+ "shape, index, load_shape, kwargs",
+ [
+ ((10,), (2,), (4,), {}),
+ ((4, 6), (1, 1), (2, 4), {"order": "F"}),
+ ((4, 8), (1, 0), (2, 8), {"traversal_steps": (1, 8)}),
+ ],
+)
+def test_zero_load_matches_tiled_load(shape, index, load_shape, kwargs):
+ array = Array(np.arange(np.prod(shape), dtype=np.float16).reshape(shape))
+ expected = cutile_builder.load(
+ array, index, load_shape, padding_mode=ct.PaddingMode.ZERO, **kwargs
+ )
+ zeros = cutile_zero_load(
+ array, index, load_shape, padding_mode=ct.PaddingMode.ZERO, **kwargs
+ )
+ assert zeros.shape == expected.shape
+ assert zeros.dtype == expected.dtype
+ assert not zeros.data.any()
+
+
+def test_zero_load_matches_gather():
+ array = Array(np.arange(12, dtype=np.int32).reshape(3, 4))
+ indices = (Tile(np.array([[0], [2]], np.int32)), Tile(np.arange(4, dtype=np.int32)))
+ expected = cutile_builder.gather(array, indices)
+ zeros = cutile_zero_load(array, indices, None, mask=None, check_bounds=True)
+ assert zeros.shape == expected.shape == (2, 4)
+ assert zeros.dtype == expected.dtype
+ assert not zeros.data.any()
+ assert cutile_skip_store(array, indices, zeros, _indexed=True) is None
+ np.testing.assert_array_equal(array.data, np.arange(12).reshape(3, 4))
+
+
+@pytest.mark.parametrize(
+ "lhs, rhs",
+ [
+ (np.ones((2, 3), np.float32), np.ones((3, 4), np.float32)),
+ (np.ones((2, 2, 3), np.float16), np.ones((2, 3, 5), np.float16)),
+ (np.ones((2, 3), np.float16), np.ones((3, 4), np.float32)),
+ ],
+)
+def test_zero_dot_matches_matmul(lhs, rhs):
+ x, y = Tile(lhs), Tile(rhs)
+ expected = cutile_builder.matmul(x, y)
+ zeros = cutile_zero_dot(x, y)
+ assert zeros.shape == expected.shape
+ assert zeros.dtype == expected.dtype
+ assert not zeros.data.any()
+
+
+def test_zero_dot_matches_mma_accumulators():
+ x = Tile(np.ones((2, 3), np.float16))
+ y = Tile(np.ones((3, 4), np.float16))
+ acc = Tile(np.full((2, 4), 7, np.float32))
+ expected = cutile_builder.mma(x, y, acc)
+ for zeros in (cutile_zero_dot(x, y, acc), cutile_zero_dot(x, y, acc=acc)):
+ assert zeros.shape == expected.shape
+ assert zeros.dtype == expected.dtype
+ assert not zeros.data.any()
+
+ # mma_scaled passes (x, x_scale, y, y_scale, acc); only acc decides the result.
+ scale = Tile(np.ones((2, 1), np.float32))
+ for zeros in (
+ cutile_zero_dot(x, scale, y, scale, acc),
+ cutile_zero_dot(x, scale, y, scale, acc=acc),
+ ):
+ assert zeros.shape == acc.shape
+ assert zeros.dtype == ct.float32
+ assert not zeros.data.any()
+
+
+def test_profiler_reports_range_loops(_isolate_profiler_cfg):
+ cfg.profiler_enable_block_sampling = False
+ cfg.profiler_enable_load_store_skipping = False
+ src = np.arange(1, 13, dtype=np.float32)
+ dst = np.zeros(12, dtype=np.float32)
+ profiler = Profiler()
+ tilelens.trace(profiler, frontend="cutile")(looped_copy_kernel)[(1,)](src, dst)
+
+ np.testing.assert_array_equal(dst, src)
+ kernel_loop = _line_of(looped_copy_kernel, "range(3)")
+ helper_loop = _line_of(copy_pair, "range(2)")
+ tuple_loop = _line_of(looped_copy_kernel, "tuple(range(4))")
+ assert set(profiler.loop_info) == {kernel_loop, helper_loop, tuple_loop}
+ assert profiler.loop_info[kernel_loop].length == 3
+ assert profiler.loop_info[helper_loop].length == 2
+ assert profiler.loop_info[tuple_loop].length is None
+ assert profiler.loop_info[kernel_loop].range_type == "python_range"
+ assert profiler.loop_info[helper_loop].range_type == "python_range"
+ assert profiler.loop_info[tuple_loop].range_type == "unknown"
+ # Rewritten helpers are only swapped in during traced runs.
+ assert "_tilelens_loop_iter_wrapper" not in inspect.signature(copy_pair).parameters
+
+
+def test_profiler_reports_loops_in_closures_and_tile_functions(_isolate_profiler_cfg):
+ cfg.profiler_enable_block_sampling = False
+ cfg.profiler_enable_load_store_skipping = False
+ steps = 2
+
+ @ct.function
+ def copy_steps(src, dst):
+ for step in range(steps):
+ ct.store(dst, (step,), ct.load(src, (step,), (2,)))
+
+ # Reached only at call time, through cuTile's tile-function dispatch.
+ helpers = {"copy": copy_steps}
+
+ def kernel(src, dst):
+ helpers["copy"](src, dst)
+
+ src = np.arange(1, 5, dtype=np.float32)
+ dst = np.zeros(4, dtype=np.float32)
+ profiler = Profiler()
+ tilelens.trace(profiler, frontend="cutile")(kernel)[(1,)](src, dst)
+
+ np.testing.assert_array_equal(dst, src)
+ helper_loop = _line_of(copy_steps, "range(steps)")
+ assert set(profiler.loop_info) == {helper_loop}
+ assert profiler.loop_info[helper_loop].length == 2
+
+
+def test_profiler_runs_kernels_without_source(_isolate_profiler_cfg):
+ cfg.profiler_enable_block_sampling = False
+ cfg.profiler_enable_load_store_skipping = False
+ namespace = {"ct": ct}
+ exec(
+ "def kernel(src, dst):\n"
+ " for i in range(2):\n"
+ " ct.store(dst, (i,), ct.load(src, (i,), (2,)))\n",
+ namespace,
+ )
+ src = np.arange(1, 5, dtype=np.float32)
+ dst = np.zeros(4, dtype=np.float32)
+ profiler = Profiler()
+ tilelens.trace(profiler, frontend="cutile")(namespace["kernel"])[(1,)](src, dst)
+
+ # Without source there is nothing to rewrite, so loops go unreported.
+ np.testing.assert_array_equal(dst, src)
+ assert profiler.loop_info == {}
+
+
+def nested_copy_kernel(src, dst):
+ for row in range(2):
+ for col in range(1, 4):
+ tile = ct.load(src, index=(row, col - 1), shape=(2, 2))
+ ct.store(dst, index=(row, col - 1), tile=tile)
+
+
+def test_profiler_reports_nested_range_loops(_isolate_profiler_cfg):
+ cfg.profiler_enable_block_sampling = False
+ cfg.profiler_enable_load_store_skipping = False
+ src = np.arange(24, dtype=np.float32).reshape(4, 6)
+ dst = np.zeros((4, 6), dtype=np.float32)
+ profiler = Profiler()
+ tilelens.trace(profiler, frontend="cutile")(nested_copy_kernel)[(1,)](src, dst)
+
+ np.testing.assert_array_equal(dst, src)
+ outer_loop = _line_of(nested_copy_kernel, "range(2)")
+ inner_loop = _line_of(nested_copy_kernel, "range(1, 4)")
+ # The inner loop runs once per outer iteration but is one loop site.
+ assert set(profiler.loop_info) == {outer_loop, inner_loop}
+ assert profiler.loop_info[outer_loop].length == 2
+ assert profiler.loop_info[inner_loop].length == 3
+ # All 2 x 3 tile copies are counted.
+ assert profiler.load_mask_total_count == 6 * 4
+
+
+def test_profiler_block_sampling_skips_unsampled_blocks(_isolate_profiler_cfg):
+ cfg.profiler_enable_block_sampling = True
+ cfg.profiler_enable_load_store_skipping = False
+ src = np.arange(1, 17, dtype=np.float32)
+ dst = np.zeros(16, dtype=np.float32)
+ profiler = Profiler(k=2)
+ tilelens.trace(profiler, frontend="cutile")(copy_kernel)[(4,)](src, dst)
+
+ written_blocks = {
+ block for block in range(4) if np.any(dst[block * 4 : block * 4 + 4])
+ }
+ assert profiler.sampled_blocks is not None
+ assert written_blocks == {idx[0] for idx in profiler.sampled_blocks}
+ assert _bytes_records()["load"].total_bytes_true == 2 * 4 * 4
+
+
+CLI_COPY_KERNEL = """
+import cuda.tile as ct
+import numpy as np
+
+
+@ct.kernel
+def copy_kernel(src, dst):
+ for step in range(2):
+ tile = ct.load(
+ src, index=(step,), shape=(4,), padding_mode=ct.PaddingMode.ZERO
+ )
+ ct.store(dst, index=(step,), tile=tile)
+"""
+
+
+def _run_profiler_cli(tmp_path: Path, launch_code: str, command=PROFILER_COMMAND):
+ exe = shutil.which(command)
+ assert exe is not None, f"{command} command not found"
+ script = tmp_path / "cutile_program.py"
+ script.write_text(CLI_COPY_KERNEL + textwrap.dedent(launch_code), encoding="utf-8")
+ env = os.environ.copy()
+ env["PROFILER_ENABLE_LOAD_STORE_SKIPPING"] = "0"
+ return subprocess.run(
+ [exe, str(script)],
+ cwd=str(tmp_path),
+ env=env,
+ capture_output=True,
+ text=True,
+ )
+
+
+def test_tile_profiler_cli_runs_cutile_launches(tmp_path: Path):
+ proc = _run_profiler_cli(
+ tmp_path,
+ """
+ src = np.arange(1, 7, dtype=np.float32)
+ dst = np.zeros(6, dtype=np.float32)
+ ct.launch(None, (1,), copy_kernel, (src, dst))
+ print("DST", dst.tolist())
+ """,
+ )
+
+ assert proc.returncode == 0, proc.stderr
+ assert "DST [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]" in proc.stdout
+ assert "Total steps: 2" in proc.stdout
+ assert "Masked percentage: 25.00%" in proc.stdout
+
+
+@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
+def test_tile_profiler_cli_runs_device_tensor_launches(tmp_path: Path):
+ proc = _run_profiler_cli(
+ tmp_path,
+ """
+ import torch
+
+ src = torch.arange(1, 7, dtype=torch.float32, device="cuda")
+ dst = torch.zeros(6, dtype=torch.float32, device="cuda")
+ ct.launch(torch.cuda.current_stream(), (1,), copy_kernel, (src, dst))
+ print("DST", dst.tolist())
+ """,
+ )
+
+ assert proc.returncode == 0, proc.stderr
+ assert "DST [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]" in proc.stdout
+
+
+def test_tile_profiler_cli_rejects_interpreted_launches(tmp_path: Path):
+ proc = _run_profiler_cli(
+ tmp_path,
+ """
+ from tilelens.core.frontend.cutile import interpreted_launches
+
+ with interpreted_launches():
+ pass
+ """,
+ )
+
+ assert proc.returncode != 0
+ assert "cannot be used together with CLI wrapper" in proc.stderr
+
+
+def test_tile_profiler_cli_rejects_traced_kernels(tmp_path: Path):
+ proc = _run_profiler_cli(
+ tmp_path,
+ """
+ import tilelens
+
+ traced = tilelens.trace("tracer", frontend="cutile")(copy_kernel)
+ src = np.zeros(4, dtype=np.float32)
+ ct.launch(None, (1,), traced, (src, src))
+ """,
+ )
+
+ assert proc.returncode != 0
+ assert "cannot be used together with CLI wrapper" in proc.stderr
+
+
+def test_tile_profiler_cli_accumulates_across_launches(tmp_path: Path):
+ proc = _run_profiler_cli(
+ tmp_path,
+ """
+ src = np.arange(1, 7, dtype=np.float32)
+ dst = np.zeros(6, dtype=np.float32)
+ ct.launch(None, (1,), copy_kernel, (src, dst))
+ ct.launch(None, (1,), copy_kernel, (src, dst))
+ """,
+ )
+
+ assert proc.returncode == 0, proc.stderr
+ # Like the Triton CLI, one profiler per kernel reports after every launch.
+ assert proc.stdout.count("Profiler Issues Summary Ends") == 2
+ assert "Total mask elements: 8\n" in proc.stdout
+ assert "Total mask elements: 16\n" in proc.stdout
+
+
+def test_other_clis_keep_nested_interpreted_launches(tmp_path: Path):
+ proc = _run_profiler_cli(
+ tmp_path,
+ """
+ from tilelens.core.frontend.cutile import interpreted_launches
+
+ src = np.arange(1, 7, dtype=np.float32)
+ dst = np.zeros(6, dtype=np.float32)
+ with interpreted_launches(), interpreted_launches():
+ ct.launch(None, (1,), copy_kernel, (src, dst))
+ print("DST", dst.tolist())
+ """,
+ command=SANITIZER_COMMAND,
+ )
+
+ assert proc.returncode == 0, proc.stderr
+ assert "DST [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]" in proc.stdout
+
+
+def test_profiler_skipping_keeps_atomics(_isolate_profiler_cfg):
+ cfg.profiler_enable_block_sampling = False
+ cfg.profiler_enable_load_store_skipping = True
+
+ @ct.kernel
+ def atomic_kernel(counter, old):
+ previous = ct.atomic_add(counter, ct.full((4,), 0, ct.int32), 1)
+ ct.store(old, (0,), previous)
+
+ counter = np.array([10], np.int32)
+ old = np.full(4, -1, np.int32)
+ tilelens.trace("profiler", frontend="cutile")(atomic_kernel)[(1,)](counter, old)
+
+ # Like Triton, skipping drops plain stores but still applies atomics.
+ np.testing.assert_array_equal(counter, [14])
+ np.testing.assert_array_equal(old, -1)
diff --git a/tests/cutile/test_cutile_tracer.py b/tests/cutile/test_cutile_tracer.py
new file mode 100644
index 000000000..b80ce3aeb
--- /dev/null
+++ b/tests/cutile/test_cutile_tracer.py
@@ -0,0 +1,317 @@
+"""Tests for cuTile tracing and visualization."""
+# ruff: noqa: E402
+
+import importlib.util
+import math
+from pathlib import Path
+
+import numpy as np
+import pytest
+import torch
+
+ct = pytest.importorskip("cuda.tile")
+
+import tilelens
+from tilelens.clients import Tracer
+from tilelens.core.data import Dot, Grid, Load, Store
+from tilelens.core.simulation.cutile import cutile_builder
+from tilelens.core.trace import launches
+
+example_path = Path(__file__).resolve().parents[2] / "examples" / "cutile" / "matmul.py"
+spec = importlib.util.spec_from_file_location("cutile_matmul_example", example_path)
+assert spec is not None
+assert spec.loader is not None
+matmul_example = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(matmul_example)
+matmul_kernel = matmul_example.matmul_kernel
+TILE_M, TILE_N = matmul_example.TILE_M, matmul_example.TILE_N
+
+
+@pytest.fixture(autouse=True)
+def clear_traces():
+ tilelens.clear()
+ yield
+ tilelens.clear()
+
+
+@pytest.mark.parametrize("shape", [(4, 8, 16), (3, 5, 9)])
+def test_matmul_records_and_visualization(shape, tmp_path):
+ m, k, n = shape
+ lhs = np.arange(m * k, dtype=np.float32).reshape(m, k)
+ rhs = np.arange(k * n, dtype=np.float32).reshape(k, n)
+ out = np.zeros((m, n), dtype=np.float32)
+ grid = (math.ceil(m / TILE_M), math.ceil(n / TILE_N))
+
+ traced = tilelens.trace("tracer", frontend="cutile")(matmul_kernel)
+ traced[grid](lhs, rhs, out)
+
+ np.testing.assert_allclose(out, lhs @ rhs)
+ records = launches[-1].records
+ assert sum(isinstance(r, Grid) for r in records) == math.prod(grid)
+ assert sum(isinstance(r, Dot) for r in records) == math.prod(grid) * math.ceil(
+ k / 4
+ )
+ assert sum(isinstance(r, Store) for r in records) == math.prod(grid)
+ loads = [r for r in records if isinstance(r, Load)]
+ assert len(loads) == math.prod(grid) * math.ceil(k / 4) * 2
+ assert all(r.call_path for r in loads)
+ if m == 3:
+ assert any(not r.masks.all() for r in loads)
+
+ from tilelens.visualizer import interface
+
+ def check_visualization():
+ interface.update_global_data(force=True)
+ response = interface.app.test_client().get("/api/data")
+ assert response.status_code == 200
+ assert response.get_json()["ops"]["visualization_data"]
+ dots = {
+ key: v for key, v in interface.raw_tensor_data.items() if "input_data" in v
+ }
+ assert len(dots) == math.prod(grid) * math.ceil(k / 4)
+ for key, dot in dots.items():
+ response = interface.app.test_client().post(
+ "/api/getMatmulC", json={"uuid": key}
+ )
+ assert response.status_code == 200
+ np.testing.assert_allclose(
+ response.get_json()["values"], dot["input_data"] @ dot["other_data"]
+ )
+ assert interface.app.test_client().get("/").status_code == 200
+
+ check_visualization()
+ path = tmp_path / "matmul.tvz"
+ tilelens.save(path)
+ tilelens.clear()
+ tilelens.load(path)
+ check_visualization()
+
+
+def copy_kernel(src, dst):
+ block = ct.bid(0)
+ tile = ct.load(src, index=(block,), shape=(4,), padding_mode=ct.PaddingMode.ZERO)
+ ct.store(dst, index=(block,), tile=tile)
+
+
+def test_indexed_views_and_mma_use_shared_records():
+ @ct.kernel
+ def indexed_kernel(src, dst):
+ view = src.slice(0, 1, 4)
+ indices = ct.arange(4, dtype=ct.int32) - 1
+ values = ct.gather(view, indices, padding_value=0)
+ product = ct.mma(
+ ct.reshape(values, (2, 2)),
+ ct.ones((2, 2), ct.float32),
+ ct.zeros((2, 2), ct.float32),
+ )
+ ct.scatter(dst, ct.arange(4, dtype=ct.int32), ct.reshape(product, (4,)))
+
+ src = np.array([10, 20, 30, 40], np.float32)
+ dst = np.zeros(4, np.float32)
+ tilelens.trace("tracer", frontend="cutile")(indexed_kernel)[(1,)](src, dst)
+ np.testing.assert_array_equal(dst, [20, 20, 70, 70])
+ records = launches[-1].records
+ loads = [r for r in records if isinstance(r, Load)]
+ stores = [r for r in records if isinstance(r, Store)]
+ assert len(loads) == len(stores) == 1
+ np.testing.assert_array_equal(loads[0].masks, [False, True, True, True])
+ np.testing.assert_array_equal(loads[0].offsets[loads[0].masks], [4, 8, 12])
+ assert sum(isinstance(r, Dot) for r in records) == 1
+
+
+def test_atomic_updates_trace_memory_and_return_old_values():
+ @ct.kernel
+ def atomic_kernel(values, old):
+ previous = ct.atomic_add(values, ct.full((2,), 0, ct.int32), 1)
+ ct.store(old, (0,), previous)
+
+ values = np.array([10], np.int32)
+ old = np.empty(2, np.int32)
+ tilelens.trace("tracer", frontend="cutile")(atomic_kernel)[(1,)](values, old)
+ np.testing.assert_array_equal(values, [12])
+ np.testing.assert_array_equal(old, [10, 11])
+ records = launches[-1].records
+ assert sum(isinstance(r, Load) for r in records) == 1
+ assert sum(isinstance(r, Store) for r in records) == 2
+
+
+def test_sampling_and_strided_offsets():
+ src = np.arange(24, dtype=np.float32)[::2]
+ dst = np.zeros(24, dtype=np.float32)[::2]
+ traced = tilelens.trace(Tracer(grid_idx=1), frontend="cutile")(copy_kernel)
+ traced.run(src=src, dst=dst, grid=(3,))
+ np.testing.assert_array_equal(dst, src)
+ records = launches[-1].records
+ assert [type(r) for r in records] == [Grid, Grid, Load, Store, Grid]
+ np.testing.assert_array_equal(records[2].offsets, np.arange(4, 8) * 8)
+ assert launches[-1].grid == (3, 1, 1)
+
+
+@pytest.mark.parametrize("traced", [False, True])
+def test_failure_restores_patches(traced):
+ from tilelens.core.simulation.cutile import CuTileInterpretedFunction
+
+ original_load = ct.load
+ original_builder_load = cutile_builder.load
+
+ @ct.kernel
+ def failing_kernel(src):
+ ct.load(src, (0,), (4,))
+ raise RuntimeError("intentional failure")
+
+ runner = (
+ tilelens.trace("tracer", frontend="cutile")(failing_kernel)
+ if traced
+ else CuTileInterpretedFunction(failing_kernel)
+ )
+ with pytest.raises(RuntimeError, match="intentional failure"):
+ runner.run(np.arange(4, dtype=np.float32), grid=(1,))
+ assert ct.load is original_load
+ assert cutile_builder.load == original_builder_load
+ assert not launches
+
+
+@pytest.mark.parametrize("traced", [False, True])
+def test_frontend_owns_language_patch(monkeypatch, traced):
+ from tilelens.core.frontend.cutile import frontend
+ from tilelens.core.simulation.cutile import CuTileInterpretedFunction
+
+ original_load = ct.load
+ patch_lang = frontend.patch_lang
+ calls = []
+
+ def record_patch(fn, client_manager=None):
+ calls.append(client_manager)
+ return patch_lang(fn, client_manager)
+
+ monkeypatch.setattr(frontend, "patch_lang", record_patch)
+ runner = (
+ tilelens.trace(frontend="cutile")(copy_kernel)
+ if traced
+ else CuTileInterpretedFunction(copy_kernel)
+ )
+ src = np.arange(6, dtype=np.float32)
+ dst = np.zeros_like(src)
+ runner.run(src, dst, grid=(2,))
+ np.testing.assert_array_equal(dst, src)
+ assert len(calls) == 1
+ assert (calls[0] is not None) == traced
+ assert ct.load is original_load
+ if traced:
+ assert [type(r) for r in launches[-1].records] == [Grid, Load, Store] * 2
+
+
+def test_reduction_and_interpreter_wrapper():
+ from tilelens.core.data import ReduceSum
+ from tilelens.core.simulation.cutile import CuTileInterpretedFunction
+
+ def reduce_kernel(src, dst):
+ tile = ct.load(src, (0,), (4,))
+ ct.store(dst, (0,), ct.sum(tile, axis=0))
+
+ traced = tilelens.trace(frontend="cutile")(CuTileInterpretedFunction(reduce_kernel))
+ dst = np.zeros(1, dtype=np.float32)
+ traced(np.arange(4, dtype=np.float32), dst)
+ np.testing.assert_array_equal(dst, [6])
+ assert [type(r) for r in launches[-1].records] == [Grid, Load, ReduceSum, Store]
+
+
+@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
+@pytest.mark.parametrize("trace", [False, True])
+def test_device_tensors_run_on_host_copies(trace):
+ from tilelens.core.simulation.cutile import CuTileInterpretedFunction
+
+ def kernel(src, dst):
+ block = ct.bid(0)
+ tile = ct.load(src, (block,), (2,))
+ ct.store(dst, (block,), tile + 1)
+
+ buffer = torch.zeros(8, dtype=torch.bfloat16, device="cuda")
+ buffer[:4] = torch.arange(4, device="cuda")
+ runner = (
+ tilelens.trace(frontend="cutile")(kernel)
+ if trace
+ else CuTileInterpretedFunction(kernel)
+ )
+ # Aliased views share one host copy, and writes return to the device.
+ runner.run(buffer[:4], buffer[4:], grid=(2,))
+ assert buffer.device.type == "cuda"
+ torch.testing.assert_close(
+ buffer.cpu(), torch.tensor([0, 1, 2, 3, 1, 2, 3, 4], dtype=torch.bfloat16)
+ )
+
+
+@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
+def test_device_tensors_are_restored_after_early_stop():
+ class StopAfterFirstBlock(Tracer):
+ def post_run_callback(self, fn):
+ return False
+
+ dst = torch.zeros(4, dtype=torch.float32, device="cuda")
+ tilelens.trace(StopAfterFirstBlock(), frontend="cutile")(copy_kernel).run(
+ torch.ones(8, dtype=torch.float32, device="cuda"), dst, grid=(2,)
+ )
+ torch.testing.assert_close(dst.cpu(), torch.ones(4))
+
+
+@pytest.mark.parametrize("grid", [2, (2,), (2, 2), (2, 2, 2)])
+@pytest.mark.parametrize("trace", [False, True])
+def test_grid_axes(grid, trace):
+ from tilelens.core.simulation.cutile import CuTileInterpretedFunction
+
+ def kernel(dst):
+ x, y, z = ct.bid(0), ct.bid(1), ct.bid(2)
+ value = ct.full((1, 1, 1), 100 * x + 10 * y + z, ct.int32)
+ ct.store(dst, (x, y, z), value)
+
+ shape = (grid,) if isinstance(grid, int) else grid
+ shape += (1,) * (3 - len(shape))
+ dst = np.full(shape, -1, dtype=np.int32)
+ runner = (
+ tilelens.trace(frontend="cutile")(kernel)
+ if trace
+ else CuTileInterpretedFunction(kernel)
+ )
+ runner.run(dst, grid=grid)
+ x, y, z = np.indices(shape)
+ np.testing.assert_array_equal(dst, 100 * x + 10 * y + z)
+
+
+def test_unsupported_client_is_rejected():
+ with pytest.raises(ValueError, match="only the tracer and profiler"):
+ tilelens.trace("sanitizer", frontend="cutile")(copy_kernel)
+
+
+def test_trace_tiled_views(tmp_path):
+ tilelens.clear()
+
+ @tilelens.trace(frontend="cutile")
+ def kernel(src, dst):
+ src_view = src.slice(0, 1, 4).slice(1, 2, 7)
+ dst_view = dst.slice(0, 1, 4).slice(1, 2, 7)
+ tiled = src_view.tiled_view((2, 4), padding_mode=ct.PaddingMode.ZERO)
+ output = dst_view.tiled_view((2, 4))
+ for i in range(tiled.num_tiles(0)):
+ for j in range(tiled.num_tiles(1)):
+ output.store((i, j), tiled.load((i, j)) + 1)
+
+ src = np.arange(32, dtype=np.float32).reshape(4, 8)
+ dst = np.zeros_like(src)
+ try:
+ kernel(src, dst)
+ np.testing.assert_array_equal(dst[1:4, 2:7], src[1:4, 2:7] + 1)
+ records = [r for r in launches[-1].records if isinstance(r, (Load, Store))]
+ assert len(records) == 8
+ assert {r.ptr for r in records} == {src.ctypes.data, dst.ctypes.data}
+ np.testing.assert_array_equal(
+ records[0].offsets, np.array([[10, 11, 12, 13], [18, 19, 20, 21]]) * 4
+ )
+ assert records[-1].masks.sum() == 1
+ tilelens.save(tmp_path / "views.tvz")
+ tilelens.load(tmp_path / "views.tvz")
+ from tilelens.visualizer.interface import app, update_global_data
+
+ update_global_data(force=True)
+ assert app.test_client().get("/api/data").status_code == 200
+ finally:
+ tilelens.clear()
diff --git a/tests/end_to_end/test_cutile.py b/tests/end_to_end/test_cutile.py
new file mode 100644
index 000000000..062ad454a
--- /dev/null
+++ b/tests/end_to_end/test_cutile.py
@@ -0,0 +1,283 @@
+# ruff: noqa: E402
+
+import importlib.util
+from io import BytesIO
+from pathlib import Path
+
+import numpy as np
+import pytest
+
+ct = pytest.importorskip("cuda.tile")
+
+import tilelens
+from tilelens.core.simulation.cutile import CuTileInterpretedFunction, DTYPES
+from tilelens.core.trace import launches
+from tilelens.visualizer import interface
+
+
+@pytest.fixture(autouse=True)
+def clear_traces():
+ tilelens.clear()
+ yield
+ tilelens.clear()
+
+
+@ct.kernel
+def copy_kernel(src, dst):
+ tile = ct.load(src, (0,), (4,))
+ ct.store(dst, (0,), tile)
+
+
+@ct.kernel
+def matmul_kernel(lhs, rhs, dst):
+ x = ct.load(lhs, (0, 0), (2, 4))
+ y = ct.load(rhs, (0, 0), (4, 2))
+ ct.store(dst, (0, 0), ct.matmul(x, y))
+
+
+@ct.kernel
+def reduction_kernel(src, total, scan):
+ tile = ct.load(src, (0,), (1024,))
+ ct.store(total, (0,), ct.sum(tile))
+ ct.store(scan, (0,), ct.cumsum(tile, axis=0))
+
+
+@ct.kernel
+def boolean_kernel(src, total, dst):
+ tile = ct.load(src, (0,), (4,))
+ ct.store(total, (0,), ct.sum(tile))
+ ct.store(dst, (0,), tile + 2)
+
+
+@ct.kernel
+def indexed_kernel(src, dst):
+ view = src.slice(0, 1, 4)
+ indices = ct.arange(4, dtype=ct.int32) - 1
+ values = ct.gather(view, indices, padding_value=0)
+ product = ct.mma(
+ ct.reshape(values, (2, 2)),
+ ct.ones((2, 2), ct.float32),
+ ct.zeros((2, 2), ct.float32),
+ )
+ ct.scatter(dst, ct.arange(4, dtype=ct.int32), ct.reshape(product, (4,)))
+
+
+def test_indexed_kernel():
+ src = np.array([10, 20, 30, 40], np.float32)
+ dst = np.zeros(4, np.float32)
+ tilelens.trace("tracer", frontend="cutile")(indexed_kernel)[(1,)](src, dst)
+ np.testing.assert_array_equal(dst, [20, 20, 70, 70])
+ check_visualizer()
+
+
+def load_example():
+ path = Path(__file__).resolve().parents[2] / "examples" / "cutile" / "matmul.py"
+ spec = importlib.util.spec_from_file_location("cutile_matmul_e2e", path)
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def check_visualizer():
+ interface.update_global_data(force=True)
+ client = interface.app.test_client()
+ response = client.get("/api/data")
+ assert response.status_code == 200
+ assert response.get_json()["ops"]["visualization_data"]
+ for key, record in interface.raw_tensor_data.items():
+ if "global_tensor" in record:
+ response = client.post("/api/getLoadTensor", json={"uuid": key})
+ assert response.status_code == 200
+ payload = response.get_json()
+ assert payload["shape"] == list(record["global_tensor"].shape)
+ assert np.asarray(payload["values"]).size > 0
+ np.testing.assert_array_equal(payload["values"], record["global_tensor"])
+ response = client.post(
+ "/api/getLoadValue", json={"uuid": key, "x": 0, "y": 0, "z": 0}
+ )
+ assert response.status_code == 200
+ assert response.get_json()["value"] == float(
+ record["global_tensor"].flat[0]
+ )
+ elif "input_data" in record:
+ response = client.post("/api/getMatmulC", json={"uuid": key})
+ assert response.status_code == 200
+ np.testing.assert_allclose(
+ response.get_json()["values"],
+ record["input_data"] @ record["other_data"],
+ )
+
+
+@pytest.mark.parametrize("dtype", [ct.bfloat16, ct.float8_e4m3fn, ct.float8_e5m2])
+@pytest.mark.parametrize("matmul", [False, True])
+def test_low_precision_trace(dtype, matmul, tmp_path):
+ storage = DTYPES[dtype]
+ if matmul:
+ lhs = np.ones((2, 4), dtype=storage)
+ rhs = np.full((4, 2), 2, dtype=storage)
+ dst = np.zeros((2, 2), dtype=storage)
+ tilelens.trace("tracer", frontend="cutile")(matmul_kernel)[(1,)](lhs, rhs, dst)
+ np.testing.assert_array_equal(dst.astype(np.float32), np.full((2, 2), 8))
+ else:
+ src = np.arange(4).astype(storage)
+ dst = np.zeros_like(src)
+ tilelens.trace("tracer", frontend="cutile")(copy_kernel)[(1,)](src, dst)
+ np.testing.assert_array_equal(dst, src)
+ assert dst.dtype == storage
+ check_visualizer()
+ path = tmp_path / "low_precision.tvz"
+ tilelens.save(path)
+ tilelens.clear()
+ tilelens.load(path)
+ check_visualizer()
+ assert any(t.element_size() == storage.itemsize for t in launches[-1].tensors)
+ assert any(t.dtype == str(dtype) for t in launches[-1].tensors)
+
+
+def test_reduction_kernels():
+ src = np.ones(1024, dtype=DTYPES[ct.bfloat16])
+ total, scan = np.zeros(1, dtype=src.dtype), np.zeros_like(src)
+ tilelens.trace("tracer", frontend="cutile")(reduction_kernel)[(1,)](
+ src, total, scan
+ )
+ np.testing.assert_array_equal(total.astype(np.float32), [1024])
+ np.testing.assert_array_equal(scan, np.arange(1, 1025).astype(src.dtype))
+ tilelens.clear()
+ mask = np.array([True, False, True, True])
+ count, output = np.zeros(1, np.int32), np.zeros(4, np.int32)
+ tilelens.trace("tracer", frontend="cutile")(boolean_kernel)[(1,)](
+ mask, count, output
+ )
+ np.testing.assert_array_equal(count, [3])
+ np.testing.assert_array_equal(output, [3, 2, 3, 3])
+
+
+def test_example_kernel(tmp_path):
+ example = load_example()
+ lhs = np.arange(15, dtype=np.float32).reshape(3, 5)
+ rhs = np.arange(45, dtype=np.float32).reshape(5, 9)
+ dst = np.zeros((3, 9), np.float32)
+ tilelens.trace("tracer", frontend="cutile")(example.matmul_kernel)[(2, 2)](
+ lhs, rhs, dst
+ )
+ np.testing.assert_array_equal(dst, lhs @ rhs)
+ check_visualizer()
+ tilelens.save(tmp_path / "matmul.tvz")
+
+
+def test_float64_reduction_kernel():
+ src = np.zeros(1024, np.float64)
+ src[0] = 1e300
+ total, scan = np.zeros(1, np.float64), np.zeros_like(src)
+ tilelens.trace("tracer", frontend="cutile")(reduction_kernel)[(1,)](
+ src, total, scan
+ )
+ np.testing.assert_array_equal(total, [1e300])
+ np.testing.assert_array_equal(scan, np.full(1024, 1e300))
+
+
+def test_kernels_compile():
+ compilation = pytest.importorskip("cuda.tile.compilation")
+ cases = [
+ (
+ load_example().matmul_kernel,
+ [(ct.float32, (3, 5)), (ct.float32, (5, 9)), (ct.float32, (3, 9))],
+ ),
+ (indexed_kernel, [(ct.float32, (4,))] * 2),
+ (boolean_kernel, [(ct.bool_, (4,)), (ct.int32, (1,)), (ct.int32, (4,))]),
+ (
+ reduction_kernel,
+ [(ct.bfloat16, (1024,)), (ct.bfloat16, (1,)), (ct.bfloat16, (1024,))],
+ ),
+ (
+ matmul_kernel,
+ [(ct.bfloat16, (2, 4)), (ct.bfloat16, (4, 2)), (ct.bfloat16, (2, 2))],
+ ),
+ (
+ reduction_kernel,
+ [(ct.float64, (1024,)), (ct.float64, (1,)), (ct.float64, (1024,))],
+ ),
+ ]
+ for kernel, arrays in cases:
+ parameters = [
+ compilation.ArrayConstraint(
+ dtype,
+ len(shape),
+ index_dtype=ct.int32,
+ stride_lower_bound_incl=0,
+ alias_groups=(),
+ may_alias_internally=False,
+ shape_constant=shape,
+ )
+ for dtype, shape in arrays
+ ]
+ signature = compilation.KernelSignature(
+ parameters, compilation.CallingConvention.cutile_python_v2()
+ )
+ buffer = BytesIO()
+ compilation.export_kernel(
+ kernel,
+ [signature],
+ buffer,
+ gpu_code="sm_100",
+ output_format="tileir_bytecode",
+ bytecode_version="13.1",
+ )
+ assert buffer.getvalue()
+
+
+def test_interpreted_kernel():
+ @ct.kernel
+ def add_kernel(a, b, out):
+ block = ct.bid(0)
+ x = ct.load(a, (block,), (4,), padding_mode=ct.PaddingMode.ZERO)
+ y = ct.load(b, (block,), (4,), padding_mode=ct.PaddingMode.ZERO)
+ ct.store(out, (block,), x + y)
+
+ a = np.arange(10, dtype=np.int32)
+ b = np.arange(10, dtype=np.int32) * 2
+ output = np.empty_like(a)
+ original_load = ct.load
+
+ CuTileInterpretedFunction(add_kernel).run(a, b, output, grid=(3,))
+
+ np.testing.assert_array_equal(output, a + b)
+ assert ct.load is original_load
+
+
+def test_softmax_kernel_and_builtin_max_restore():
+ @ct.kernel
+ def softmax(src, dst):
+ x = ct.load(src, (ct.bid(0), 0), (1, 8), padding_mode=ct.PaddingMode.NEG_INF)
+ m = max(ct.full((), -float("inf"), ct.float32), ct.max(x))
+ probabilities = ct.exp(x - m)
+ ct.store(dst, (ct.bid(0), 0), probabilities / ct.sum(probabilities))
+
+ data = np.array([[100, 101, 102, 103, 104], [-3, -2, -1, 0, 1]], np.float32)
+ result = np.zeros_like(data)
+ original_exp = ct.exp
+ CuTileInterpretedFunction(softmax).run(data, result, grid=(2,))
+ expected = np.exp(data - data.max(1, keepdims=True))
+ expected /= expected.sum(1, keepdims=True)
+ np.testing.assert_allclose(result, expected, rtol=1e-6)
+ assert ct.exp is original_exp
+
+
+def test_kernel_preserves_shadowed_builtins_and_keyword_defaults(monkeypatch):
+ calls = []
+
+ def helper(x, y):
+ calls.append(True)
+ return x + y
+
+ def kernel(src, dst, *, increment=2):
+ values = ct.load(src, (0,), (4,))
+ ct.store(dst, (0,), max(values, increment))
+
+ monkeypatch.setitem(kernel.__globals__, "max", helper)
+ src = np.arange(4, dtype=np.float32)
+ dst = np.zeros_like(src)
+ CuTileInterpretedFunction(kernel).run(src, dst)
+ np.testing.assert_array_equal(dst, src + 2)
+ assert calls == [True]
diff --git a/tests/unit/test_cutile.py b/tests/unit/test_cutile.py
new file mode 100644
index 000000000..63351b48a
--- /dev/null
+++ b/tests/unit/test_cutile.py
@@ -0,0 +1,357 @@
+"""Tests for cuTile values and operations."""
+
+import operator
+
+import numpy as np
+import pytest
+
+ct = pytest.importorskip("cuda.tile")
+
+from tilelens.core.simulation.cutile import ( # noqa: E402
+ Array,
+ Tile,
+ cutile_builder,
+)
+
+
+def test_tile_creation():
+ data = np.array([[1, 2], [3, 4]], dtype=np.int32)
+ tile = Tile(data)
+
+ assert tile.shape == (2, 2)
+ assert tile.dtype == ct.int32
+ np.testing.assert_array_equal(tile.data, data)
+
+ # Test data ownership and immutability.
+ data[0, 0] = 99
+ assert tile.data[0, 0] == 1
+ with pytest.raises(ValueError):
+ tile.data[0, 0] = 99
+
+ assert Tile(3).dtype == ct.int32
+ assert Tile(3.0).dtype == ct.float32
+
+
+def test_arithmetic():
+ x = Tile(np.array([8, 4], dtype=np.int32))
+ y = Tile(np.array([2, 2], dtype=np.int32))
+
+ np.testing.assert_array_equal((x + y).data, [10, 6])
+ np.testing.assert_array_equal((x - y).data, [6, 2])
+ np.testing.assert_array_equal((10 - x).data, [2, 6])
+ np.testing.assert_array_equal((x * y).data, [16, 8])
+ np.testing.assert_array_equal((x / y).data, [4.0, 2.0])
+ np.testing.assert_array_equal((16 / x).data, [2.0, 4.0])
+ np.testing.assert_array_equal((x < y).data, [False, False])
+ np.testing.assert_array_equal((x > y).data, [True, True])
+ np.testing.assert_array_equal((x <= y).data, [False, False])
+ np.testing.assert_array_equal((x >= y).data, [True, True])
+ np.testing.assert_array_equal((x & y).data, [0, 0])
+ np.testing.assert_array_equal((x | y).data, [10, 6])
+ assert (x / y).dtype == ct.float32
+ assert (x < y).dtype == ct.bool_
+
+ # Test mixed int32/float32 promotion.
+ mixed = Tile(np.array([1, 2], np.int32)) + Tile(np.array([0.5, 1.5], np.float32))
+ assert mixed.dtype == ct.float32
+
+
+def test_tile_operations():
+ full = cutile_builder.full((2, 2), 3, ct.int32)
+ reshaped = cutile_builder.reshape(full, (4,))
+ converted = cutile_builder.astype(reshaped, ct.float32)
+ total = cutile_builder.sum(full)
+
+ lhs = Tile(np.array([[1, 2], [3, 4]], dtype=np.float32))
+ rhs = Tile(np.array([[2, 0], [1, 2]], dtype=np.float32))
+ product = cutile_builder.matmul(lhs, rhs)
+
+ np.testing.assert_array_equal(full.data, [[3, 3], [3, 3]])
+ np.testing.assert_array_equal(reshaped.data, [3, 3, 3, 3])
+ assert converted.dtype == ct.float32
+ assert total.data == 12
+ np.testing.assert_array_equal(product.data, [[4, 4], [10, 8]])
+
+
+def test_load_and_store():
+ source = Array(np.arange(10, dtype=np.int32))
+ first = cutile_builder.load(source, (0,), (4,))
+ tail = cutile_builder.load(source, (2,), (4,), padding_mode=ct.PaddingMode.ZERO)
+
+ output = np.full(10, -1, dtype=np.int32)
+ cutile_builder.store(Array(output), (0,), first)
+ cutile_builder.store(Array(output), (2,), tail)
+
+ np.testing.assert_array_equal(first.data, [0, 1, 2, 3])
+ np.testing.assert_array_equal(tail.data, [8, 9, 0, 0])
+ np.testing.assert_array_equal(output, [0, 1, 2, 3, -1, -1, -1, -1, 8, 9])
+
+
+def test_tile_shape_operations():
+ tile = cutile_builder.arange(16, dtype=ct.int32).reshape((4, -1))
+ np.testing.assert_array_equal(tile.transpose().data, tile.data.T)
+ np.testing.assert_array_equal(tile.permute((1, 0)).data, tile.data.T)
+ np.testing.assert_array_equal(tile.extract((1, 0), (2, 2)).data, [[8, 9], [12, 13]])
+ assert tile[:, None, ...].shape == (4, 1, 4)
+ assert cutile_builder.expand_dims(tile, -1).shape == (4, 4, 1)
+ assert cutile_builder.broadcast_to(
+ cutile_builder.arange(4, dtype=ct.int32), (2, 4)
+ ).shape == (2, 4)
+ assert tile.astype(ct.float32).dtype == ct.float32
+ assert operator.index(cutile_builder.full((1,), 3, ct.int32).item()) == 3
+ with pytest.raises(TypeError, match="extract"):
+ tile[1:3]
+ with pytest.raises(ValueError):
+ cutile_builder.full((3,), 0, ct.float32)
+ with pytest.raises(ValueError):
+ tile.extract((2, 0), (2, 2))
+
+
+@pytest.mark.parametrize(
+ "view",
+ [
+ lambda a: a.T,
+ lambda a: a[:, ::2],
+ lambda a: a[::-1, ::-1],
+ lambda a: np.broadcast_to(a[:1, :], (4, 8)),
+ ],
+)
+def test_host_strides_and_order(view):
+ data = view(np.arange(32, dtype=np.float32).reshape(4, 8))
+ array = Array(data)
+ assert array.strides == tuple(s // data.itemsize for s in data.strides)
+ for order in ("C", "F", (1, 0)):
+ expected = data if order == "C" else data.T
+ tile = cutile_builder.load(array, (0, 0), (2, 4), order=order)
+ np.testing.assert_array_equal(tile.data, expected[:2, :4])
+
+
+def test_views_alias_storage_and_traversal():
+ storage = np.arange(32, dtype=np.float32).reshape(4, 8)
+ array = Array(storage)
+ view = array.slice(0, 1, 4).slice(-1, Tile(2), Tile(7))
+ assert view.shape == (3, 5)
+ assert np.shares_memory(view.data, storage)
+ tiled = view.tiled_view(
+ (2, 4), padding_mode=ct.PaddingMode.ZERO, traversal_steps=(1, 2)
+ )
+ assert (tiled.num_tiles(0), tiled.num_tiles(1)) == (3, 3)
+ np.testing.assert_array_equal(
+ tiled.load((1, 1)).data, [[20, 21, 22, 0], [28, 29, 30, 0]]
+ )
+ tiled.store((2, 2), 99.0)
+ assert storage[3, 6] == 99
+ assert storage[3, 7] == 31
+ with pytest.raises(ValueError):
+ array.slice(0, -1, 2)
+ with pytest.raises(ValueError):
+ array.tiled_view((2,))
+ with pytest.raises(ValueError):
+ array.tiled_view((2, 4), traversal_steps=(0, 4))
+
+
+def test_permuted_store_and_scalar_access():
+ data = np.zeros((4, 8), np.float32)
+ cutile_builder.store(
+ Array(data), (1, 0), cutile_builder.full((4, 2), 7, ct.float32), order="F"
+ )
+ np.testing.assert_array_equal(data[:2, 4:], 7)
+ assert not data[2:, :].any()
+ cutile_builder.store(Array(data), (3, 7), Tile(11))
+ assert cutile_builder.load(Array(data), (3, 7), ()).data == 11
+ with pytest.raises(ValueError):
+ cutile_builder.load(Array(data), (0,), (4,))
+
+
+@pytest.mark.parametrize(
+ "mode,expected",
+ [
+ (ct.PaddingMode.ZERO, 0),
+ (ct.PaddingMode.NEG_ZERO, -0.0),
+ (ct.PaddingMode.NAN, np.nan),
+ (ct.PaddingMode.POS_INF, np.inf),
+ (ct.PaddingMode.NEG_INF, -np.inf),
+ ],
+)
+def test_padding_modes(mode, expected):
+ value = cutile_builder.load(
+ Array(np.arange(3, dtype=np.float32)), 0, 4, padding_mode=mode
+ )
+ np.testing.assert_equal(value.data[-1], expected)
+ if mode == ct.PaddingMode.NEG_ZERO:
+ assert np.signbit(value.data[-1])
+
+
+def test_indexed_memory_bounds_masks_and_broadcast():
+ data = np.arange(12, dtype=np.float32).reshape(3, 4)
+ rows = Tile(np.array([[-1], [2]], np.int32))
+ cols = Tile(np.array([[0, 4, 1, 3]], np.int32))
+ gathered = cutile_builder.gather(Array(data), (rows, cols), padding_value=-9)
+ np.testing.assert_array_equal(gathered.data, [[-9, -9, -9, -9], [8, -9, 9, 11]])
+ out = np.zeros_like(data)
+ cutile_builder.scatter(
+ Array(out), (rows, cols), 7, mask=Tile(np.array([[True, True, False, True]]))
+ )
+ np.testing.assert_array_equal(out, [[0, 0, 0, 0], [0, 0, 0, 0], [7, 0, 0, 7]])
+ with pytest.raises(IndexError, match="check_bounds=False"):
+ cutile_builder.gather(Array(data), (rows, cols), check_bounds=False)
+ # The mask excludes invalid indices when bounds checking is disabled.
+ np.testing.assert_array_equal(
+ cutile_builder.gather(
+ Array(data), (rows, cols), mask=False, check_bounds=False
+ ).data,
+ np.zeros((2, 4)),
+ )
+ with pytest.raises(TypeError, match="integer"):
+ cutile_builder.gather(Array(data), (Tile(1.0), 0))
+
+
+def test_atomic_add_repeated_indices_and_old_values():
+ data = np.array([10, 20], np.int32)
+ indices = Tile(np.array([0, 0, 1, -1], np.int32))
+ old = cutile_builder.atomic_add(
+ Array(data), indices, Tile(np.array([1, 2, 3, 99], np.int32))
+ )
+ np.testing.assert_array_equal(data, [13, 23])
+ np.testing.assert_array_equal(old.data[:3], [10, 11, 20])
+
+
+@pytest.mark.parametrize(
+ "dtype",
+ [
+ ct.int8,
+ ct.uint8,
+ ct.int16,
+ ct.int32,
+ ct.int64,
+ ct.float16,
+ ct.bfloat16,
+ ct.float32,
+ ],
+)
+def test_dtype_storage_roundtrip_and_scalar_arithmetic(dtype):
+ tile = cutile_builder.full((4,), 2, dtype)
+ assert tile.dtype == dtype
+ assert (tile + 1).dtype == dtype
+ np.testing.assert_array_equal((tile * 2).data.astype(np.float32), [4] * 4)
+ assert cutile_builder.astype(tile, ct.float32).dtype == ct.float32
+
+
+def test_mma_accumulation_widens_int8_and_preserves_accumulator():
+ x = Tile(np.full((2, 4), 100, np.int8))
+ y = Tile(np.full((4, 2), 2, np.int8))
+ result = cutile_builder.mma(x, y, cutile_builder.full((2, 2), 10, ct.int32))
+ assert result.dtype == ct.int32
+ np.testing.assert_array_equal(result.data, np.full((2, 2), 810))
+ float_result = cutile_builder.mma(
+ cutile_builder.astype(x, ct.float16),
+ cutile_builder.astype(y, ct.float16),
+ cutile_builder.zeros((2, 2), ct.float32),
+ )
+ assert float_result.dtype == ct.float32
+ np.testing.assert_array_equal(float_result.data, np.full((2, 2), 800))
+
+
+def test_reductions_scan_and_concat():
+ x = Tile(np.array([[1, 3, 3, -1], [4, 2, 1, 0]], np.float32))
+ np.testing.assert_array_equal(
+ cutile_builder.max(x, 1, keepdims=True).data, [[3], [4]]
+ )
+ np.testing.assert_array_equal(cutile_builder.argmax(x, 1).data, [1, 0])
+ assert cutile_builder.argmax(x).dtype == ct.int32
+ np.testing.assert_array_equal(
+ cutile_builder.cumsum(x, 1, reverse=True).data, [[6, 5, 2, -1], [7, 3, 1, 0]]
+ )
+ assert cutile_builder.cat((x, x), 0).shape == (4, 4)
+ with pytest.raises(ValueError, match="same shape"):
+ cutile_builder.cat((x, x.reshape((8,))), 0)
+
+
+def test_integer_operators_and_scalar_control_flow():
+ x = Tile(np.array([1, 2, 3, 4], np.int64))
+ np.testing.assert_array_equal((x // 2).data, [0, 1, 1, 2])
+ np.testing.assert_array_equal((x % 2).data, [1, 0, 1, 0])
+ np.testing.assert_array_equal((x ^ 1).data, [0, 3, 2, 5])
+ np.testing.assert_array_equal((x << 2).data, [4, 8, 12, 16])
+ np.testing.assert_array_equal((x >> 1).data, [0, 1, 1, 2])
+ np.testing.assert_array_equal((x != 2).data, [True, False, True, True])
+ np.testing.assert_array_equal((-x).data, [-1, -2, -3, -4])
+ assert bool(Tile(1))
+ with pytest.raises(TypeError, match="scalar"):
+ bool(x)
+
+
+def test_transcendentals_selection_and_fp16_rounding():
+ x = Tile(np.array([1, 2, 4, 8], np.float32))
+ np.testing.assert_allclose(cutile_builder.rsqrt(x).data, 1 / np.sqrt(x.data))
+ np.testing.assert_allclose(
+ cutile_builder.exp2(cutile_builder.log(x)).data,
+ np.exp2(np.log(x.data)),
+ rtol=1e-6,
+ )
+ np.testing.assert_array_equal(
+ cutile_builder.where(x > 2, x, -1).data, [-1, -1, 4, 8]
+ )
+ assert cutile_builder.exp(cutile_builder.astype(x, ct.float16)).dtype == ct.float16
+
+
+def test_mixed_float_tiles_do_not_narrow_float64():
+ precise = Tile(np.array([1.0 + 2**-40], np.float64))
+ zero = Tile(np.zeros(1, np.float32))
+ result = precise + zero
+ assert result.dtype == ct.float64
+ np.testing.assert_array_equal(result.data, precise.data)
+ np.testing.assert_array_equal((precise > Tile(np.ones(1, np.float32))).data, [True])
+
+
+@pytest.mark.parametrize("fill", [1.0, 0.1])
+def test_bfloat16_reductions(fill):
+ tile = cutile_builder.full((1024,), fill, ct.bfloat16)
+ expected = tile.data.astype(np.float32)
+ total = cutile_builder.sum(tile)
+ scan = cutile_builder.cumsum(tile)
+ reverse = cutile_builder.cumsum(tile, reverse=True)
+ assert total.dtype == scan.dtype == reverse.dtype == ct.bfloat16
+ np.testing.assert_array_equal(
+ total.data, np.asarray(expected.sum(), dtype=tile.data.dtype)
+ )
+ np.testing.assert_array_equal(scan.data, expected.cumsum().astype(tile.data.dtype))
+ np.testing.assert_array_equal(
+ reverse.data, expected[::-1].cumsum()[::-1].astype(tile.data.dtype)
+ )
+
+
+def test_boolean_results():
+ tile = Tile(np.array([True, False, True, True]))
+ assert cutile_builder.sum(tile).dtype == ct.int32
+ assert cutile_builder.sum(tile).data == 3
+ scan = cutile_builder.cumsum(tile)
+ assert scan.dtype == ct.int32
+ np.testing.assert_array_equal(scan.data, [1, 1, 2, 3])
+ assert cutile_builder.max(tile).dtype == ct.int32
+ assert (tile + 2).dtype == (2 + tile).dtype == ct.int32
+ np.testing.assert_array_equal((tile + 2).data, [3, 2, 3, 3])
+ np.testing.assert_array_equal(
+ (tile + Tile(np.full(4, 2, np.int32))).data, [3, 2, 3, 3]
+ )
+ with pytest.raises(TypeError, match="Boolean arithmetic"):
+ tile + tile
+
+
+def test_scalar_float64_results():
+ tile = Tile(np.array([1e300, 1, 1, 1], np.float64))
+ for result in (
+ cutile_builder.sum(tile),
+ cutile_builder.max(tile),
+ Tile(np.float64(1e300)),
+ ):
+ assert result.dtype == ct.float64
+ assert result.data == 1e300
+ scalar = Tile(np.array(1e-300, np.float64))
+ assert (scalar + scalar).dtype == ct.float64
+ assert (scalar + scalar).data == 2e-300
+
+
+def test_arange_requires_dtype():
+ with pytest.raises(TypeError, match="dtype"):
+ cutile_builder.arange(4)
diff --git a/tilelens/clients/profiler/profiler.py b/tilelens/clients/profiler/profiler.py
index e95723549..3b2f4648f 100644
--- a/tilelens/clients/profiler/profiler.py
+++ b/tilelens/clients/profiler/profiler.py
@@ -15,6 +15,13 @@
from dataclasses import dataclass, replace
+def _element_size(ptr) -> int:
+ if isinstance(ptr, TensorHandle):
+ return _get_np_dtype(ptr.get_element_ty()).itemsize
+ # Non-Triton frontends (e.g. cuTile) pass arrays backed by NumPy data.
+ return ptr.data.dtype.itemsize
+
+
@dataclass(frozen=False)
class LoopInfo:
length: int | None = None
@@ -93,6 +100,9 @@ def __init__(
# Config has enable_load_store_skipping, but profiler uses disable_load_store_skipping
self.disable_load_store_skipping = not cfg.profiler_enable_load_store_skipping
+ # Frontend whose op signatures the skipping overriders follow
+ self.frontend_name = "triton"
+
def pre_run_callback(self, fn: Callable) -> bool:
# If block sampling is enabled, check if current block is selected
if self.block_sampling and self.sampled_blocks is not None:
@@ -159,12 +169,11 @@ def grid_callback(self, grid: tuple[int, ...]):
def _report_load_store_bytes(
self, type, ptr: TensorHandle, mask: TensorHandle
): # internal methods assumed to be called under the lock
- dtype_tt = ptr.get_element_ty()
- dtype_np: np.dtype = _get_np_dtype(dtype_tt)
+ itemsize = _element_size(ptr)
mask_true = np.count_nonzero(mask.data)
mask_false = np.count_nonzero(np.logical_not(mask.data))
- total_bytes_true = mask_true * dtype_np.itemsize
- total_bytes_attempted = (mask_true + mask_false) * dtype_np.itemsize
+ total_bytes_true = mask_true * itemsize
+ total_bytes_attempted = (mask_true + mask_false) * itemsize
if type == "load":
self.load_bytes.total_bytes_attempted += total_bytes_attempted
self.load_bytes.total_bytes_true += total_bytes_true
@@ -305,25 +314,43 @@ def pre_addptr_callback(ptr, offset):
if not self.disable_buffer_load_check:
self._check_32bit_range(byte_offset, element_bytewidth, offset_data)
+ overriders: dict[type[Op], Callable] = {
+ Load: load_overrider,
+ Store: store_overrider,
+ Dot: dot_overrider,
+ }
+ if self.frontend_name == "cutile":
+ from ...core.frontend.cutile import (
+ cutile_skip_store,
+ cutile_zero_dot,
+ cutile_zero_load,
+ )
+
+ overriders = {
+ Load: self.lock_fn(cutile_zero_load),
+ Store: self.lock_fn(cutile_skip_store),
+ Dot: self.lock_fn(cutile_zero_dot),
+ }
+
if op_type is Load:
if self.disable_load_store_skipping:
return OpCallbacks(before_callback=pre_load_callback)
else:
return OpCallbacks(
- before_callback=pre_load_callback, op_overrider=load_overrider
+ before_callback=pre_load_callback, op_overrider=overriders[Load]
)
elif op_type is Store:
if self.disable_load_store_skipping:
return OpCallbacks(before_callback=pre_store_callback)
else:
return OpCallbacks(
- before_callback=pre_store_callback, op_overrider=store_overrider
+ before_callback=pre_store_callback, op_overrider=overriders[Store]
)
elif op_type is Dot:
if self.disable_load_store_skipping:
return OpCallbacks()
else:
- return OpCallbacks(op_overrider=dot_overrider)
+ return OpCallbacks(op_overrider=overriders[Dot])
elif op_type is AddPtr:
return OpCallbacks(before_callback=pre_addptr_callback)
diff --git a/tilelens/core/frontend/cutile.py b/tilelens/core/frontend/cutile.py
new file mode 100644
index 000000000..a8e55514e
--- /dev/null
+++ b/tilelens/core/frontend/cutile.py
@@ -0,0 +1,358 @@
+"""Adapt cuTile interpreter operations to the shared tracing callbacks."""
+
+from collections.abc import Callable
+from contextlib import contextmanager
+import sys
+from threading import Lock
+from typing import Any
+
+import numpy as np
+
+from tilelens.core.data import Dot, Load, Op, ProgramId, ReduceSum, Store
+
+from ..patch import LoopSite, loop_file_token
+from .base import AdapterResult, Frontend, _LangPatchScope, register_frontend
+
+
+HAS_CUTILE = False
+cutile_builder: Any = None
+try:
+ from tilelens.core.simulation.cutile import (
+ Array,
+ Tile,
+ _indexed_access,
+ _numpy_dtype,
+ _promotion_type,
+ _tile_access,
+ _tile_value,
+ cutile_builder,
+ )
+
+ HAS_CUTILE = True
+except ModuleNotFoundError:
+ pass
+
+
+def _cutile_memory_adapter(
+ array: Any,
+ index: Any,
+ shape: Any,
+ order: Any = "C",
+ traversal_steps: Any = None,
+) -> AdapterResult:
+ assert HAS_CUTILE
+ _, axes, access_shape, starts = _tile_access(
+ array, index, shape, order, traversal_steps
+ )
+ root = array
+ while root._parent is not None:
+ root = root._parent
+ keys: list[Any] = [None] * array.ndim
+ mask = np.ones(access_shape, dtype=bool)
+ for axis, (start, size, array_axis) in enumerate(zip(starts, access_shape, axes)):
+ coordinates = start + np.arange(size)
+ broadcast_shape = [1] * array.ndim
+ broadcast_shape[axis] = size
+ coordinates = coordinates.reshape(broadcast_shape)
+ keys[array_axis] = Tile(coordinates + array._origin[array_axis])
+ mask &= (coordinates >= 0) & (coordinates < array.shape[array_axis])
+ return AdapterResult(root, Tile(mask), tuple(keys))
+
+
+def _cutile_load_adapter(
+ array: Any,
+ index: Any,
+ shape: Any = None,
+ *,
+ order: Any = "C",
+ traversal_steps: Any = None,
+ **kwargs: Any,
+) -> AdapterResult:
+ if shape is None:
+ return _cutile_indexed_adapter(
+ array, index, kwargs.get("mask"), kwargs.get("check_bounds", True)
+ )
+ return _cutile_memory_adapter(array, index, shape, order, traversal_steps)
+
+
+def _cutile_store_adapter(
+ array: Any,
+ index: Any,
+ tile: Any = None,
+ *,
+ order: Any = "C",
+ traversal_steps: Any = None,
+ **kwargs: Any,
+) -> AdapterResult:
+ assert HAS_CUTILE
+ # Scatter uses the Store callback with indexed coordinates.
+ if kwargs.get("_indexed", False):
+ return _cutile_indexed_adapter(
+ array, index, kwargs.get("mask"), kwargs.get("check_bounds", True)
+ )
+ return _cutile_memory_adapter(
+ array, index, _tile_value(tile).shape, order, traversal_steps
+ )
+
+
+def _cutile_indexed_adapter(
+ array: Any,
+ indices: Any,
+ mask: Any = None,
+ check_bounds: bool = True,
+) -> AdapterResult:
+ keys, valid = _indexed_access(array, indices, mask, check_bounds)
+ # Memory callbacks expect arrays, even for scalar indices.
+ if valid.ndim == 0:
+ keys = tuple(key.reshape(1) for key in keys)
+ valid = valid.reshape(1)
+ root = array
+ while root._parent is not None:
+ root = root._parent
+ return AdapterResult(
+ root,
+ Tile(valid),
+ tuple(Tile(key + origin) for key, origin in zip(keys, array._origin)),
+ )
+
+
+def _cutile_dot_adapter(x: Any, y: Any, *_args: Any, **_kwargs: Any) -> AdapterResult:
+ assert HAS_CUTILE
+ # Copy read-only tiles before the visualizer converts them to Torch tensors.
+ # mma takes (acc,); mma_scaled takes (x_scale, y, y_scale[, acc]) with acc= allowed.
+ if len(_args) >= 2:
+ lhs_data, rhs_data = cutile_builder._scaled_operands(x, y, _args[0], _args[1])
+ return AdapterResult(Array(lhs_data), Array(rhs_data))
+ lhs, rhs = Array(x.data), Array(y.data)
+ if lhs.data.dtype.kind in "iu":
+ lhs, rhs = (
+ Array(lhs.data.astype(np.float32)),
+ Array(rhs.data.astype(np.float32)),
+ )
+ return AdapterResult(Array(lhs.numpy().copy()), Array(rhs.numpy().copy()))
+
+
+def _cutile_reduce_sum_adapter(
+ input_tensor: Any,
+ axis: Any = None,
+ *,
+ keepdims: bool = False,
+ **kwargs: Any,
+) -> AdapterResult:
+ return AdapterResult(input_tensor, axis, keepdims)
+
+
+def cutile_zero_load(
+ array: Any,
+ index: Any,
+ shape: Any = None,
+ *,
+ order: Any = "C",
+ traversal_steps: Any = None,
+ **kwargs: Any,
+) -> Any:
+ """Return zeros shaped like ct.load or ct.gather without reading memory."""
+ assert HAS_CUTILE
+ if shape is None:
+ _, valid = _indexed_access(
+ array, index, kwargs.get("mask"), kwargs.get("check_bounds", True)
+ )
+ return Tile(np.zeros(valid.shape, dtype=array.data.dtype))
+ shape, *_ = _tile_access(array, index, shape, order, traversal_steps)
+ return Tile(np.zeros(shape, dtype=array.data.dtype))
+
+
+def cutile_skip_store(*_args: Any, **_kwargs: Any) -> None:
+ """Drop ct.store and ct.scatter writes."""
+ return None
+
+
+def cutile_zero_dot(x: Any, y: Any, *args: Any, **kwargs: Any) -> Any:
+ """Return zeros shaped like matmul, mma, or mma_scaled without computing."""
+ assert HAS_CUTILE
+ # mma takes (acc,); mma_scaled takes (y, y_scale[, acc]) with acc= allowed.
+ acc = kwargs.get("acc", args[-1] if args else None)
+ if acc is not None:
+ return Tile(np.zeros(acc.shape, dtype=_tile_value(acc).dtype))
+
+ from cuda.tile._ir.ops_utils import promote_dtypes
+
+ common = promote_dtypes(_promotion_type(x), _promotion_type(y))
+ lhs, rhs = _tile_value(x), _tile_value(y)
+ # An empty contraction axis yields matmul's output shape with no arithmetic.
+ lhs = np.zeros(lhs.shape[:-1] + (0,))
+ rhs = np.zeros(rhs.shape[:-2] + (0,) + rhs.shape[-1:] if rhs.ndim > 1 else (0,))
+ return Tile(np.matmul(lhs, rhs).astype(_numpy_dtype(common)), common)
+
+
+CUTILE_ADAPTERS: dict[type[Op], Callable[..., AdapterResult]] = {}
+CUTILE_NAMESPACES: dict[Any, dict[str, type[Op]]] = {}
+if HAS_CUTILE:
+ assert cutile_builder is not None
+
+ CUTILE_NAMESPACES = {
+ cutile_builder: {
+ "bid": ProgramId,
+ "load": Load,
+ "store": Store,
+ "matmul": Dot,
+ "mma": Dot,
+ "mma_scaled": Dot,
+ "sum": ReduceSum,
+ }
+ }
+
+ CUTILE_ADAPTERS = {
+ ProgramId: lambda axis, *_args, **_kwargs: AdapterResult(axis),
+ Load: _cutile_load_adapter,
+ Store: _cutile_store_adapter,
+ Dot: _cutile_dot_adapter,
+ ReduceSum: _cutile_reduce_sum_adapter,
+ }
+
+
+class CuTileFrontend(Frontend):
+ def __init__(self) -> None:
+ definition = Frontend.from_namespaces(
+ name="cutile",
+ builder=cutile_builder,
+ namespaces=CUTILE_NAMESPACES,
+ adapters=CUTILE_ADAPTERS,
+ )
+ super().__init__(
+ name=definition.name,
+ builder=definition.builder,
+ original_ops=definition.original_ops,
+ adapters=definition.adapters,
+ namespaces=definition.namespaces,
+ )
+ self._loop_patched = False
+ self._current_client_manager: Any = None
+
+ def run_op_overrider(
+ self,
+ op: Callable,
+ op_type: type[Op],
+ op_overrider: Callable,
+ args: tuple[Any, ...],
+ kwargs: dict[str, Any],
+ ) -> Any:
+ # Atomics access memory through load and store. Triton keeps atomics as
+ # separate ops that overriders never replace, so run them unchanged.
+ if kwargs.get("_atomic", False):
+ return op(*args, **kwargs)
+ return op_overrider(*args, **kwargs)
+
+ def patch_for_loop(self) -> None:
+ self._loop_patched = True
+
+ def unpatch_for_loop(self) -> None:
+ self._loop_patched = False
+
+ def loop_iter_wrapper(
+ self,
+ iterable_callable: Callable,
+ iter_args: Any,
+ iter_kwargs: Any,
+ lineno: int,
+ range_type: str,
+ ) -> Any:
+ """Report a rewritten for-loop to clients, like Triton's loop wrapper."""
+ client_manager = self._current_client_manager
+ if client_manager is None:
+ # A rewritten helper can outlive its traced launch.
+ return iterable_callable(*iter_args, **iter_kwargs)
+ caller_file = sys._getframe(1).f_code.co_filename
+ loop_site = LoopSite(lineno, loop_file_token(caller_file))
+ return client_manager.loop_iter_wrapper(
+ iterable_callable, iter_args, iter_kwargs, loop_site, range_type
+ )
+
+ def rewrite_loops(self, fn: Any) -> Any:
+ """Return fn with its for-loops routed through loop_iter_wrapper."""
+ from .cutile_transform import rewrite_loops
+
+ return rewrite_loops(fn, self.loop_iter_wrapper)
+
+ def patch_lang(self, fn, client_manager: Any = None) -> _LangPatchScope:
+ from tilelens.core.simulation import cutile as cutile_simulation
+
+ scope = _LangPatchScope()
+ cutile_simulation.cutile_patch_lang(scope)
+ # Like Triton and NKI, traced runs execute kernels and helpers with
+ # their for-loops rewritten; standalone runs execute the originals.
+ if self._loop_patched and client_manager is not None:
+ scope.set_attr(self, "_current_client_manager", client_manager)
+ scope.set_attr(cutile_simulation, "_rewrite_loops", self.rewrite_loops)
+ return scope
+
+
+frontend = register_frontend(CuTileFrontend())
+
+
+_launch_scope_lock = Lock()
+_launch_scope = None
+_launch_options = None
+_launch_users = 0
+_launch_cli = False
+
+
+@contextmanager
+def interpreted_launches(client="tracer", *, cli=False):
+ """Run ct.launch on CPU; overlapping scopes must use identical settings.
+
+ CLI wrappers pass cli=True. Like the Triton CLI, that scope traces each
+ kernel once so client state accumulates across launches, and it rejects
+ user-traced kernels and nested scopes.
+ """
+ global _launch_scope, _launch_options, _launch_users, _launch_cli
+
+ import cuda.tile as ct
+ import tilelens
+ from tilelens.core.trace import CuTileTrace
+
+ traces: dict[Any, CuTileTrace] = {}
+
+ def launch(stream, grid, kernel, args):
+ if cli:
+ # tilelens.trace() rejects already-traced kernels under the CLI.
+ if kernel not in traces:
+ traces[kernel] = tilelens.trace(client, frontend="cutile")(kernel)
+ runner = traces[kernel]
+ elif isinstance(kernel, CuTileTrace):
+ runner = kernel
+ else:
+ runner = tilelens.trace(client, frontend="cutile")(kernel)
+ return runner.run(*args, grid=grid)
+
+ # The global entry point can be shared by worker threads. Hold this guard
+ # only while changing ownership; each runner serializes its own execution.
+ with _launch_scope_lock:
+ options = client
+ if _launch_users and (cli or _launch_cli):
+ raise RuntimeError(
+ "interpreted_launches() cannot be used together with CLI wrapper "
+ "(e.g., tile-profiler). Please remove interpreted_launches() from "
+ "your code when using CLI tools."
+ )
+ if _launch_users and options != _launch_options:
+ raise RuntimeError(
+ "Overlapping interpreted_launches contexts must use the same "
+ "client settings"
+ )
+ if not _launch_users:
+ _launch_scope = _LangPatchScope()
+ _launch_scope.set_attr(ct, "launch", launch)
+ _launch_options = options
+ _launch_cli = cli
+ _launch_users += 1
+ try:
+ yield
+ finally:
+ with _launch_scope_lock:
+ _launch_users -= 1
+ if not _launch_users:
+ _launch_scope.restore()
+ _launch_scope = None
+ _launch_options = None
+ _launch_cli = False
diff --git a/tilelens/core/frontend/cutile_transform.py b/tilelens/core/frontend/cutile_transform.py
new file mode 100644
index 000000000..aedefa8f3
--- /dev/null
+++ b/tilelens/core/frontend/cutile_transform.py
@@ -0,0 +1,209 @@
+"""Rewrite cuTile kernel and helper for-loops to report loop iterations."""
+
+import ast
+import inspect
+import os
+from pathlib import Path
+import sysconfig
+import textwrap
+import types
+from collections.abc import Callable
+from typing import Any, cast
+from weakref import WeakKeyDictionary
+
+LOOP_WRAPPER_ARG = "_tilelens_loop_iter_wrapper"
+_FACTORY_NAME = "_tilelens_loop_factory"
+
+
+class CuTileLoopTransformer(ast.NodeTransformer):
+ """
+ AST transformer for cuTile loop tracing, matching Triton's loop rewrite.
+
+ Transformations:
+ - `for x in f(*args, **kwargs)` -> `for x in wrapper(f, args, kwargs, lineno, range_type)`
+ - `for x in expr` -> `for x in wrapper(lambda: expr, (), {}, lineno, range_type)`
+ - adds the wrapper as a hidden keyword-only argument of every function
+ """
+
+ def visit_For(self, node: ast.For) -> ast.AST:
+ self.generic_visit(node)
+
+ # Preserve which spelling the user wrote so clients can tell loop kinds apart.
+ range_type = "unknown"
+ if isinstance(node.iter, ast.Call):
+ func = node.iter.func
+ if isinstance(func, ast.Name) and func.id == "range":
+ range_type = "python_range"
+
+ # Pass the callable and its arguments separately so range-wrapper
+ # clients can replace the iterable before it is created.
+ if isinstance(node.iter, ast.Call):
+ iter_callable = node.iter.func
+ iter_args = ast.Tuple(elts=node.iter.args, ctx=ast.Load())
+ kw_keys: list[ast.expr | None] = []
+ kw_vals: list[ast.expr] = []
+ for kw in node.iter.keywords:
+ if kw.arg is None:
+ continue
+ kw_keys.append(ast.Constant(value=kw.arg))
+ kw_vals.append(kw.value)
+ iter_kwargs = ast.Dict(keys=kw_keys, values=kw_vals)
+ else:
+ iter_callable = ast.Lambda(
+ args=ast.arguments(
+ posonlyargs=[],
+ args=[],
+ kwonlyargs=[],
+ kw_defaults=[],
+ defaults=[],
+ ),
+ body=node.iter,
+ )
+ iter_args = ast.Tuple(elts=[], ctx=ast.Load())
+ iter_kwargs = ast.Dict(keys=[], values=[])
+
+ loop = ast.For(
+ target=node.target,
+ iter=ast.Call(
+ func=ast.Name(id=LOOP_WRAPPER_ARG, ctx=ast.Load()),
+ args=[
+ iter_callable,
+ iter_args,
+ iter_kwargs,
+ ast.Constant(value=node.lineno),
+ ast.Constant(value=range_type),
+ ],
+ keywords=[],
+ ),
+ body=node.body,
+ orelse=node.orelse,
+ type_comment=node.type_comment,
+ )
+ return ast.fix_missing_locations(ast.copy_location(loop, node))
+
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.AST:
+ node = cast(ast.FunctionDef, self.generic_visit(node))
+ # A defaulted keyword-only argument lets rewritten loops call the
+ # wrapper without adding a name to the user's module globals.
+ if LOOP_WRAPPER_ARG in {
+ arg.arg
+ for arg in (node.args.posonlyargs + node.args.args + node.args.kwonlyargs)
+ }:
+ return node
+ node.args.kwonlyargs.append(ast.arg(arg=LOOP_WRAPPER_ARG))
+ node.args.kw_defaults.append(ast.Name(id=LOOP_WRAPPER_ARG, ctx=ast.Load()))
+ return ast.fix_missing_locations(node)
+
+
+# Like Triton rewriting only @jit functions, leave library code untouched.
+_LIBRARY_DIRS = tuple(
+ os.path.join(os.path.realpath(path), "")
+ for key in ("stdlib", "platstdlib", "purelib", "platlib")
+ if (path := sysconfig.get_paths().get(key))
+) + (os.path.join(str(Path(__file__).resolve().parents[2]), ""),)
+
+
+def _is_library_code(fn: types.FunctionType) -> bool:
+ return os.path.realpath(fn.__code__.co_filename).startswith(_LIBRARY_DIRS)
+
+
+# Rewritten functions keyed by original function; None marks functions that
+# are left unchanged (no for-loops or no available source).
+_REWRITTEN: WeakKeyDictionary[Callable, Callable | None] = WeakKeyDictionary()
+
+
+def _function_node(fn: types.FunctionType) -> ast.FunctionDef | None:
+ if fn.__code__.co_name == "