Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions python/CuTeDSL/cutlass/cute/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -5506,11 +5506,30 @@ def local_tile(
result = cute.local_tile(tensor, tiler=tiler, coord=coord, proj=proj)
"""

tiler_val = _pack_tile(tiler, loc=loc, ip=ip)
coord_val = _pack_coord(coord, loc=loc, ip=ip)
if proj is not None:
if not isinstance(proj, tuple):
raise TypeError(f"Expected tuple for proj, but got {type(proj)}")
# A flat projection over a tuple tiler and coord is applied here, so
# that the op is emitted without `proj`: both forms select the same
# tile, but the compiler aborts on a copy from a tile whose projection
# dropped a mode of a rank-2 tensor (NVIDIA/cutlass#3957). `coord` may
# have more modes than `proj`; those are kept as they are.
if (
all(p is None or is_integer(p) for p in proj)
and isinstance(tiler, tuple)
and len(tiler) == len(proj)
and isinstance(coord, tuple)
and len(coord) >= len(proj)
):
kept = [i for i, p in enumerate(proj) if p is not None]
if kept:
tiler = tuple(tiler[i] for i in kept)
coord = tuple(coord[i] for i in kept) + coord[len(proj) :]
proj = None

tiler_val = _pack_tile(tiler, loc=loc, ip=ip)
coord_val = _pack_coord(coord, loc=loc, ip=ip)
if proj is not None:
proj_val = _pack_coord(proj, loc=loc, ip=ip)
proj = proj_val.type.attribute

Expand Down
142 changes: 142 additions & 0 deletions test/python/CuTeDSL/test_local_tile_proj_copy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
# SPDX-FileCopyrightText: Copyright (c) 2025 - 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: LicenseRef-NvidiaProprietary
#
# Use of this software is governed by the terms and conditions of the
# NVIDIA End User License Agreement (EULA), available at:
# https://docs.nvidia.com/cutlass/latest/media/docs/pythonDSL/license.html
#
# Any use, reproduction, disclosure, or distribution of this software
# and related documentation outside the scope permitted by the EULA
# is strictly prohibited.

"""
``cute.local_tile(..., proj=...)`` must give a tile that ``cute_ext.copy`` can
copy from and to.

With rank-2 tensors and a projection that drops a mode, such as
``cute.local_tile(t, (128, 64, 1), (m, n, None), proj=(1, 1, None))``, the
compilation aborted the process without a diagnostic (NVIDIA/cutlass#3957).
The projected call selects the same tile as
``cute.local_tile(t, (128, 64), (m, n))``.

Each case runs in a subprocess, since a regression kills the process. Needs a
GPU and PyTorch.
"""

import os
import subprocess
import sys
import tempfile
import textwrap
import unittest

try:
import torch

_HAS_CUDA = torch.cuda.is_available()
except Exception: # pragma: no cover - PyTorch is optional for this suite
_HAS_CUDA = False

_SCENARIO = """
import sys

import torch

import cutlass
from cutlass import cute
from cutlass.cute import experimental as cute_ext

RANK, PROJ = int(sys.argv[1]), sys.argv[2]


def tile(t, cta_m, cta_n, cta_l):
rest = (cta_l,) if cutlass.const_expr(RANK == 3) else ()
if cutlass.const_expr(PROJ == "last"):
return cute.local_tile(
t, (128, 64, 1), (cta_m, cta_n, None) + rest, proj=(1, 1, None)
)
if cutlass.const_expr(PROJ == "middle"):
return cute.local_tile(
t, (128, 1, 64), (cta_m, None, cta_n) + rest, proj=(1, None, 1)
)
if cutlass.const_expr(PROJ == "identity"):
return cute.local_tile(t, (128, 64), (cta_m, cta_n) + rest, proj=(1, 1))
return cute.local_tile(t, (128, 64), (cta_m, cta_n) + rest)


@cute.kernel
def kernel(mA: cute.Tensor, mD: cute.Tensor):
cta_m, cta_n, cta_l = cute.arch.block_idx()
tid, _, _ = cute.arch.thread_idx()
gA, gD = tile(mA, cta_m, cta_n, cta_l), tile(mD, cta_m, cta_n, cta_l)
buf = cute_ext.allocate(
cute.Float16,
cutlass.AddressSpace.rmem,
cute.make_layout(((8, 1), (1, 8)), stride=((1, 8), (1, 8))),
alignment=16,
)
tv = cute.make_layout(((16, 8), (8, 1)), stride=((8, 128), (1, 1024)))
tl = cute.core._pack_tile((128, 8))
atom = cute.make_copy_atom(
cute.nvgpu.CopyUniversalOp(), cute.Float16, num_bits_per_copy=128
)
cute_ext.copy(
cute_ext.partition(gA, tid, layout_tv=tv, tiler=tl), buf, copy_atom=atom
)
cute_ext.copy(
buf, cute_ext.partition(gD, tid, layout_tv=tv, tiler=tl), copy_atom=atom
)


@cute.jit
def host(a: cute.Tensor, d: cute.Tensor):
kernel(a, d).launch(grid=(2, 2, 1), block=(128, 1, 1))


# Column major (256, 128) tensors, 2 x 2 tiles of (128, 64).
if RANK == 3:
src = torch.randn(1, 128, 256, dtype=torch.float16, device="cuda").permute(2, 1, 0)
else:
src = torch.randn(128, 256, dtype=torch.float16, device="cuda").T
dst = torch.zeros_like(src)
host(
cute.runtime.from_dlpack(src, assumed_align=16),
cute.runtime.from_dlpack(dst, assumed_align=16),
)
torch.cuda.synchronize()
ok = torch.equal(src, dst)
print("PASS" if ok else "MISMATCH", flush=True)
sys.exit(0 if ok else 1)
"""


def _run(rank: int, proj: str) -> subprocess.CompletedProcess:
# The DSL compiles from source, so the scenario has to live in a file.
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "scenario.py")
with open(path, "w") as f:
f.write(textwrap.dedent(_SCENARIO))
return subprocess.run(
[sys.executable, path, str(rank), proj],
capture_output=True,
text=True,
timeout=300,
)


@unittest.skipUnless(_HAS_CUDA, "needs a GPU and PyTorch")
class TestLocalTileProjCopy(unittest.TestCase):
def test_copy_from_projected_tile(self) -> None:
for rank in (2, 3):
for proj in ("none", "identity", "last", "middle"):
with self.subTest(rank=rank, proj=proj):
result = _run(rank, proj)
self.assertEqual(
result.returncode,
0,
msg=(result.stdout + result.stderr)[-2000:],
)


if __name__ == "__main__":
unittest.main()