옵션
집집 Skill 개발자 도구 tilegym-adding-cutile-kernel

tilegym-adding-cutile-kernel

NVIDIA/skills NVIDIA/skills

TileGym에 새로운 cuTile GPU 커널 연산자를 추가하고, 디스패치 등록, 백엔드 구현, 익스포트, 테스트 및 벤치마크를 다룹니다.

...모든 것을 확장하십시오
0
업데이트 된 시간 2026년 9월 27일

TileGym에 cuTile 커널 추가하기

cuTile 백엔드를 사용하여 새로운 연산자(예: my_op)를 추가하는 종단 간 워크플로우.

실행 규칙

다음 규칙을 반드시 엄격히 준수해야 합니다:

  1. 코드를 작성하기 전에 TodoWrite를 사용하여 아래 체크리스트를 작성해야 합니다
  2. 단계를 순서대로 실행하십시오 — 단계를 건너뛰거나 병합해서는 안 됩니다
  3. 각 할 일 항목은 완료 후 ‘완료 ’로, 시작 시 ‘진행 중’으로 표시하십시오
  4. 해당 단계가 적용되지 않는 경우(예: cuTile 구현 없음), 메모와 함께 ‘완료’로 표시하고, 아무런 표시 없이 건너뛰지 마십시오
  5. 각 단계는 반드시 파일 쓰기 또는 명시적인 건너뛰기 결정으로 이어져야 하며, 아무런 표시 없이 생략해서는 안 됩니다

지침

시작 시 반드시 이 체크리스트를 TodoWrite에 복사해야 합니다:

- [ ] 1단계: ops.py에 디스패치 인터페이스 등록
- [ ] 2단계: cuTile 백엔드 구현
- [ ] 단계 3: __init__.py에 등록 (cutile)
- [ ] 단계 4: 테스트 추가
- [ ] 단계 5: tests/benchmark에 벤치마크 추가
- [ ] 단계 6: 검증 (pytest + lint 실행)

1단계: 디스패치 인터페이스 등록

파일: src/tilegym/ops/ops.py

@dispatch 함수를 추가합니다. 이 함수는 모든 백엔드의 단일 진입점입니다.

@dispatch(
    "my_op",
)
def my_op(
    input: torch.Tensor,
    out: Optional[torch.Tensor] = None,
    **kwargs: Any,
):
    """
    my_op에 대한 설명.

    인수:
        input: 입력 텐서
        out: 미리 할당된 선택적 출력 텐서
        **kwargs: 백엔드별 구성을 위한 추가 인수

    반환값:
        torch.Tensor
    """
    raise NotImplementedError(f"{get_current_backend()}에서는 my_op가 구현되지 않았습니다")

주요 규칙:

  • 함수 본문에서는 NotImplementedError만 발생시킵니다
  • 백엔드별 매개변수를 지정하려면 **kwargs를 포함해야 합니다

참조: src/tilegym/ops/ops.py에 있는 기존 연산(예: silu_and_mul, softmax)을 참조하십시오

2단계: cuTile 백엔드 구현

파일: src/tilegym/ops/cutile/my_op.py

파일 구조는 다음 템플릿을 따릅니다:

import torch
import cuda.tile as ct

from tilegym.backend import register_impl


@ct.kernel
def my_op_kernel_ct(x, output, n_elements: ct.Constant[int], BLOCK_SIZE: ct.Constant[int]):
    bid = ct.bid(0)
    indices = bid * BLOCK_SIZE + ct.arange(0, BLOCK_SIZE)
    x_val = ct.gather(x, indices)
    # ... 계산 ...
    ct.scatter(output, indices, result)


@register_impl("my_op", backend="cutile")
def my_op(input: torch.Tensor, out: torch.Tensor = None, **kwargs) -> torch.Tensor:
    n = input.numel()
    if out is None:
        out = torch.empty_like(input)
    grid = ((n + 1023) // 1024,)
    ct.launch(stream, grid, kernel, (some args, ...))
    return out

참조: src/tilegym/ops/cutile/silu_and_mul.py

3단계: __init__.py 에 등록하기 (매우 중요)

이 단계를 생략하면 cuTile 백엔드 구현이 절대 로드되지 않습니다.

파일: src/tilegym/ops/cutile/__init__.py

if is_backend_available("cutile"): 블록 내부에 다음을 추가합니다(알파벳 순서대로):

from . import my_op

그리고 함수 임포트 섹션에 다음을 추가하십시오:

from .my_op import my_op

그리고 __all__에 "my_op" 를 추가합니다.

4단계: 테스트 추가

파일: tests/ops/test_my_op.py

중요: 항상 tilegym.ops에서 임포트해야 하며, 절대로 tilegym.ops.cutile.my_op에서 임포트해서는 안 됩니다.

import pytest
import torch

from tilegym.backend import is_backend_available, set_backend
from .. import common

_backends = ["cutile"]


class Test_MY_OP(common.PyTestCase):
    @staticmethod
    def reference(input):
        """PyTorch를 사용한 참조 구현."""
        return torch.some_reference(input)

    @pytest.mark.parametrize("shape, dtype", [
        ((1024,), torch.float16),
        ((1024, 512), torch.float32),
        ((64, 64, 64), torch.bfloat16),
    ])
    @pytest.mark.parametrize("backend", _backends)
    def test_op(self, shape, dtype, backend, arch):
        if backend == "cutile" and not is_backend_available("cutile"):
            pytest.skip("Cutile 백엔드를 사용할 수 없습니다")
        try:
            set_backend(backend)
        except Exception as e:
            pytest.skip(f"백엔드가 지원되지 않습니다: {e}")

        self.setUp()

        from tilegym.ops import my_op

        A = torch.randn(*shape, dtype=dtype, device="cuda")
        self.assertCorrectness(
            my_op, self.reference, {"input": A},
            atol=1e-3, rtol=1e-3,
        )

주요 패턴:

  • _backends = ["cutile"]
  • test_op: try-except 블록 내에서 set_backend(backend)를 사용하고, self.setUp()을 호출

참조: tests/ops/test_silu_and_mul.py

다음은 흔히 발생하는 오류입니다.

1. _backends 리스트 누락 (클래스 내부)
2. test_op / test_op_xxx — @pytest.mark.parametrize("backend", _backends)가 누락되었거나, backend 매개변수가 없거나, tilegym.is_backend_available / tilegym.set_backend 구문이 누락됨

5단계: tests/benchmark에 벤치마크 추가

파일: tests/benchmark/bench_my_op.py

benchmark_rules.md의 주요 규칙:

  • tilegym.ops.my_op(a, b, ..., backend=backend) 를 통해 연산 호출 — set_backend는 사용하지 마십시오.
  • ALL_BACKENDS를 정의하고(최소 cutile 및 torch 포함), get_supported_backends()를 사용하여 필터링합니다.
  • reference_my_op(...)를 구현하고 다음을 통해 등록하십시오: register_impl("my_op", "torch")(reference_my_op).
  • create_benchmark_config() 를 사용하여 triton.testing.Benchmark 구성을 생성합니다(예: shape/dtype 기준).
  • bench_my_op(...)에서 @triton.testing.perf_report([...])를 사용하십시오. 벤치 함수 내부에서: torch.testing.assert_close(fn(), ref(), ...)를 사용하여 정확성을 확인한 후, ms = triton.testing.do_bench(fn) (또는 do_bench_cudagraph)를 실행하여 GB/s 또는 TFLOPS를 계산하고, 해당 메트릭을 반환합니다.
  • 입력점: if __name__ == "__main__": bench_my_op.run(print_data=True).

템플릿 구조:

import torch
import triton
import triton.testing

import tilegym
from tilegym.backend import is_backend_available, register_impl

ALL_BACKENDS = [
    ("cutile", "cuTile", ("orange", "-")) if is_backend_available("cutile") else None,
    ("torch", "PyTorch", ("green", "-")),
]

def get_supported_backends():
    return [p for p in ALL_BACKENDS if p is not None]

def reference_my_op(input: torch.Tensor, out: torch.Tensor = None, **kwargs):
    """PyTorch를 사용한 참조 구현."""
    ...

register_impl("my_op", "torch")(reference_my_op)

def create_benchmark_config(datatype, ...):
    available_backends = get_supported_backends()
    if not available_backends:
        return None
    backends, names, styles = zip(*available_backends)
    return triton.testing.Benchmark(
        x_names=["M"],  # 또는 다른 차원 이름
        x_vals=[...],
        line_arg="backend",
        line_vals=list(backends),
        line_names=list(names),
        styles=list(styles),
        ylabel="GB/s",  # 또는 TFLOPS
        plot_name="my-op-...",
        args={"datatype": datatype, ...},
    )

@triton.testing.perf_report([
    create_benchmark_config(datatype, ...)
    for datatype in [torch.float16, torch.float32]
    for ... in [...]
])
def bench_my_op(M, backend, datatype, ..., device="cuda"):
    x = torch.randn(..., dtype=datatype, device=device)

    fn = lambda: tilegym.ops.my_op(x, backend=backend)
    ref = lambda: reference_my_op(x)
    torch.testing.assert_close(fn(), ref(), rtol=1e-2, atol=1e-2)

    ms = triton.testing.do_bench(fn)  # 또는 do_bench_cudagraph(fn)
    # ms와 문제 규모를 바탕으로 메트릭(예: GB/s 또는 TFLOPS) 계산
    return metric

if __name__ == "__main__":
    bench_my_op.run(print_data=True)

벤치마크 플롯 이름: -TFLOPS 또는 -GBps 접미사를 반드시 포함해야 함

  • 예시: plot_name=f"persistent-layer-norm-M{num_rows}-{dtype_name}-GBps"

6단계: 검증

# 테스트 실행
pytest tests/ops/test_my_op.py -v

# 벤치마크 실행 (선택 사항)
python tests/benchmark/bench_my_op.py

# 린트
pre-commit run -a
GitHub에서 보기
---
name: tilegym-adding-cutile-kernel
description: Add a new cuTile GPU kernel operator to TileGym, covering dispatch registration, backend implementation, exports, tests, and benchmarks.
license: CC-BY-4.0 AND Apache-2.0
---

# Adding a cuTile Kernel to TileGym

End-to-end workflow for adding a new operator (e.g., `my_op`) with cuTile backend.

## Execution Rules

**MUST follow these rules strictly:**
1. Use TodoWrite to create the checklist below BEFORE writing any code
2. Execute steps **in order** — do NOT skip ahead or combine steps
3. Mark each todo as `completed` after finishing, `in_progress` when starting
4. If a step is not applicable (e.g., no cuTile impl), mark it `completed` with a note, do NOT silently skip
5. Each step MUST result in a file write or explicit skip decision — no silent omissions

## Instructions

MUST copy this checklist to TodoWrite at the start:

```
- [ ] Step 1: Register dispatch interface in ops.py
- [ ] Step 2: Implement cuTile backend
- [ ] Step 3: Register in __init__.py (cutile)
- [ ] Step 4: Add tests
- [ ] Step 5: Add benchmark to tests/benchmark
- [ ] Step 6: Verify (run pytest + lint)
```

## Step 1: Register dispatch interface

**File**: `src/tilegym/ops/ops.py`

Add a `@dispatch` function — this is the **single entry point** for all backends.

```python
@dispatch(
    "my_op",
)
def my_op(
    input: torch.Tensor,
    out: Optional[torch.Tensor] = None,
    **kwargs: Any,
):
    """
    Description of my_op.

    Args:
        input: Input tensor
        out: Optional preallocated output tensor
        **kwargs: Additional arguments for backend-specific configurations

    Returns:
        torch.Tensor
    """
    raise NotImplementedError(f"my_op is not implemented for {get_current_backend()}")
```

**Key rules:**
- Function body only raises `NotImplementedError`
- Include `**kwargs` for backend-specific parameters

**Reference**: See existing ops in `src/tilegym/ops/ops.py` (e.g., `silu_and_mul`, `softmax`)

## Step 2: Implement cuTile backend

**File**: `src/tilegym/ops/cutile/my_op.py`

The file structure follows this template:

```python
import torch
import cuda.tile as ct

from tilegym.backend import register_impl


@ct.kernel
def my_op_kernel_ct(x, output, n_elements: ct.Constant[int], BLOCK_SIZE: ct.Constant[int]):
    bid = ct.bid(0)
    indices = bid * BLOCK_SIZE + ct.arange(0, BLOCK_SIZE)
    x_val = ct.gather(x, indices)
    # ... compute ...
    ct.scatter(output, indices, result)


@register_impl("my_op", backend="cutile")
def my_op(input: torch.Tensor, out: torch.Tensor = None, **kwargs) -> torch.Tensor:
    n = input.numel()
    if out is None:
        out = torch.empty_like(input)
    grid = ((n + 1023) // 1024,)
    ct.launch(stream, grid, kernel, (some args, ...))
    return out
```

**Reference**: `src/tilegym/ops/cutile/silu_and_mul.py`

## Step 3: Register in `__init__.py` (CRITICAL)

Missing this step means the cuTile backend implementation never gets loaded.

**File**: `src/tilegym/ops/cutile/__init__.py`

Add inside `if is_backend_available("cutile"):` block (alphabetically):

```python
from . import my_op
```

And in the function import section:

```python
from .my_op import my_op
```

And add `"my_op"` to `__all__`.

## Step 4: Add tests

**File**: `tests/ops/test_my_op.py`

**CRITICAL**: Always import from `tilegym.ops`, NEVER from `tilegym.ops.cutile.my_op`.

```python
import pytest
import torch

from tilegym.backend import is_backend_available, set_backend
from .. import common

_backends = ["cutile"]


class Test_MY_OP(common.PyTestCase):
    @staticmethod
    def reference(input):
        """Reference implementation using PyTorch."""
        return torch.some_reference(input)

    @pytest.mark.parametrize("shape, dtype", [
        ((1024,), torch.float16),
        ((1024, 512), torch.float32),
        ((64, 64, 64), torch.bfloat16),
    ])
    @pytest.mark.parametrize("backend", _backends)
    def test_op(self, shape, dtype, backend, arch):
        if backend == "cutile" and not is_backend_available("cutile"):
            pytest.skip("Cutile backend not available")
        try:
            set_backend(backend)
        except Exception as e:
            pytest.skip(f"Backend is not supported: {e}")

        self.setUp()

        from tilegym.ops import my_op

        A = torch.randn(*shape, dtype=dtype, device="cuda")
        self.assertCorrectness(
            my_op, self.reference, {"input": A},
            atol=1e-3, rtol=1e-3,
        )
```

**Key patterns:**
- `_backends = ["cutile"]`
- `test_op`: use `set_backend(backend)` with try-except, call `self.setUp()`

**Reference**: `tests/ops/test_silu_and_mul.py`

Below is the common errors.
```
1. Missing _backends list (inside class)
2. test_op / test_op_xxx — missing @pytest.mark.parametrize("backend", _backends), backend parameter, and tilegym.is_backend_available / tilegym.set_backend pattern
```

## Step 5: Add benchmark to tests/benchmark

**File**: `tests/benchmark/bench_my_op.py`

**Key rules from benchmark_rules.md:**
- Call the op via `tilegym.ops.my_op(a, b, ..., backend=backend)` — do **not** use `set_backend`.
- Define `ALL_BACKENDS` (include at least `cutile` and `torch`), filter with `get_supported_backends()`.
- Implement `reference_my_op(...)` and register it: `register_impl("my_op", "torch")(reference_my_op)`.
- Use `create_benchmark_config()` to build `triton.testing.Benchmark` configs (e.g. by shape/dtype).
- Use `@triton.testing.perf_report([...])` on `bench_my_op(...)`; inside the bench function: correctness check with `torch.testing.assert_close(fn(), ref(), ...)`, then `ms = triton.testing.do_bench(fn)` (or `do_bench_cudagraph`), compute GB/s or TFLOPS, and return the metric.
- Entry point: `if __name__ == "__main__": bench_my_op.run(print_data=True)`.

Template structure:

```python
import torch
import triton
import triton.testing

import tilegym
from tilegym.backend import is_backend_available, register_impl

ALL_BACKENDS = [
    ("cutile", "cuTile", ("orange", "-")) if is_backend_available("cutile") else None,
    ("torch", "PyTorch", ("green", "-")),
]

def get_supported_backends():
    return [p for p in ALL_BACKENDS if p is not None]

def reference_my_op(input: torch.Tensor, out: torch.Tensor = None, **kwargs):
    """Reference implementation using PyTorch."""
    ...

register_impl("my_op", "torch")(reference_my_op)

def create_benchmark_config(datatype, ...):
    available_backends = get_supported_backends()
    if not available_backends:
        return None
    backends, names, styles = zip(*available_backends)
    return triton.testing.Benchmark(
        x_names=["M"],  # or other dimension names
        x_vals=[...],
        line_arg="backend",
        line_vals=list(backends),
        line_names=list(names),
        styles=list(styles),
        ylabel="GB/s",  # or TFLOPS
        plot_name="my-op-...",
        args={"datatype": datatype, ...},
    )

@triton.testing.perf_report([
    create_benchmark_config(datatype, ...)
    for datatype in [torch.float16, torch.float32]
    for ... in [...]
])
def bench_my_op(M, backend, datatype, ..., device="cuda"):
    x = torch.randn(..., dtype=datatype, device=device)

    fn = lambda: tilegym.ops.my_op(x, backend=backend)
    ref = lambda: reference_my_op(x)
    torch.testing.assert_close(fn(), ref(), rtol=1e-2, atol=1e-2)

    ms = triton.testing.do_bench(fn)  # or do_bench_cudagraph(fn)
    # Compute metric (e.g. GB/s or TFLOPS) from ms and problem size
    return metric

if __name__ == "__main__":
    bench_my_op.run(print_data=True)
```

**Benchmark Plot Names**: Must include `-TFLOPS` or `-GBps` suffix
  - Example: `plot_name=f"persistent-layer-norm-M{num_rows}-{dtype_name}-GBps"`

## Step 6: Verify

```bash
# Run tests
pytest tests/ops/test_my_op.py -v

# Run benchmark (optional)
python tests/benchmark/bench_my_op.py

# Lint
pre-commit run -a
```

tilegym-adding-cutile-kernel 설치

스킬 파일을 다운로드하여 .claude/skills/ 디렉터리에 압축을 풀어주세요.

ZIP 다운로드

저장소를 클론하고 스킬 파일을 프로젝트에 복사하세요.

git clone https://github.com/NVIDIA/skills/tree/main/skills/tilegym-adding-cutile-kernel # Copy SKILL.md to your .claude/skills/ directory

복사 복사
빠른 설정: 스킬 폴더를 .claude/skills/로 복사하세요. Claude가 해당 스킬을 자동으로 감지하여 사용할 것입니다.
저장소 NVIDIA/skills

관련 스킬

algorithmic-art
업데이트 된 시간 2026년 8월 27일
systematic-debugging
업데이트 된 시간 2026년 9월 3일
tech-debt-tracker
업데이트 된 시간 2026년 8월 29일
continual-learning
업데이트 된 시간 2026년 9월 10일
OR