tritonparse icon indicating copy to clipboard operation
tritonparse copied to clipboard

Support cuTile and cuteDSL

Open FindHao opened this issue 11 months ago • 8 comments

FindHao avatar Jan 01 '26 03:01 FindHao

https://docs.nvidia.com/cutlass/latest/media/docs/pythonDSL/cute_dsl_general/dsl_jit_compilation_options.html#cute-compile-compilation-options-as-strings

FindHao avatar Jan 31 '26 01:01 FindHao

TritonParse Integration with CuTeDSL

Background

TritonParse captures Triton kernel compilation and launch traces via structured_logging for visualization and debugging. The goal is to extend tritonparse to also support CuTeDSL. The simplest approach is to add hooks in CuTeDSL similar to Triton's knobs module.


1. How TritonParse structured_logging Works

1.1 Three Hook Points

TritonParse relies on three hook slots provided by Triton's knobs module (tritonparse/structured_logging.py):

Hook Purpose Registration Location
knobs.compilation.listener Callback after compilation, receives all IR artifacts, metadata, and timing line 1756
knobs.runtime.jit_post_compile_hook Injects a custom launch_metadata function after JIT compilation line 1627
knobs.runtime.launch_enter_hook Callback at kernel launch, collects grid, arguments, and metadata line 1628

1.2 Compilation Trace Data Flow

Triton compilation completes
  -> knobs.compilation.listener
    -> maybe_trace_triton()  (line 1254)
      -> extract_file_content()       # Extract IR (TTIR/TTGIR/LLIR/PTX/CUBIN)
      -> extract_python_source_info() # Extract kernel Python source code
      -> extract_metadata_from_src()  # Extract env, attrs, constants
      -> trace_structured_triton("compilation", ...)
      -> Write to .ndjson

Callback signature of maybe_trace_triton:

def maybe_trace_triton(
    src,                      # ASTSource or IRSource - kernel source
    metadata: Dict[str, Any], # Compilation metadata (hash, arch, num_warps, num_stages, etc.)
    metadata_group: Dict[str, str],  # filename -> filepath (all IR artifact files)
    times: Any,               # CompileTimes object
    event_type: str = "compilation",
    cache_hit: bool = False,
)

1.3 Launch Trace Data Flow

Launch tracing uses two hooks in coordination:

Triton kernel launch
  -> jit_post_compile_hook (JITHookImpl, line 1464)
      Injects fn.launch_metadata = add_launch_metadata
  -> Triton internally calls launch_metadata
      -> add_launch_metadata() (line 1430)
        Collects grid, metadata, extracted_args, inductor_args
  -> launch_enter_hook (LaunchHookImpl, line 1528)
      -> trace_structured_triton("launch", ...)
      -> Write to .ndjson

1.4 Collected Data Structures

Compilation event:

{
  "event_type": "compilation",
  "pid": 152358,
  "stack": [{"line": 72, "name": "<module>", "filename": "test.py"}],
  "timestamp": "...",
  "payload": {
    "metadata": {
      "cache_hit": false,
      "arch": "sm75",
      "hash": "...",
      "name": "add_kernel",
      "num_warps": 4,
      "times": {}
    },
    "file_content": {
      "kernel.ttir": "...",
      "kernel.ttgir": "...",
      "kernel.ptx": "..."
    },
    "python_source": {
      "file_path": "/path/to/source.py",
      "start_line": 30,
      "code": "@triton.jit\ndef add_kernel(...):\n    ..."
    }
  }
}

Launch event:

{
  "event_type": "launch",
  "name": "add_kernel",
  "grid": [4, 1, 1],
  "stream": 0,
  "compilation_metadata": {"num_warps": 4},
  "extracted_args": {
    "x_ptr": {"type": "tensor", "shape": [512, 512], "dtype": "torch.float32"}
  }
}

2. CuTeDSL Compilation and Launch Architecture

2.1 Compilation Pipeline

CuTeDSL has no dependency on Triton and uses its own independent MLIR compilation stack:

Python -> AST rewriting -> MLIR tracing -> MLIR passes (cute-to-nvvm) -> PTX -> CUBIN

Key code paths (under python/CuTeDSL/cutlass/):

Stage Method File:Line
Entry point @cute.jit / @cute.kernel base_dsl/dsl.py:473-487
AST rewriting run_preprocessor() base_dsl/dsl.py:1422
IR generation generate_original_ir() base_dsl/dsl.py:1102
Compilation dispatch generate_mlir() base_dsl/dsl.py:1329
Compile + cache compile_and_cache() base_dsl/dsl.py:1165
Pass execution Compiler.compile() base_dsl/compiler.py:136
JIT engine Compiler.jit() base_dsl/compiler.py:166

2.2 Launch Path

JitCompiledFunction.__call__()   (jit_executor.py:805)
  -> generate_execution_args()    # Pack arguments
  -> run_compiled_program()       (jit_executor.py:787)
    -> capi_func(packed_args)     # Call the compiled host function
    -> Host function internally calls cudaLaunchKernelEx

2.3 Existing Hook Capabilities

  • Compiler._post_compile_hook -- post-compile hook (compiler.py:103), used internally for TVM FFI
  • No compilation listener, launch hook, or pre-compile hook
  • IR dump capability exists (CUTE_DSL_KEEP_IR/KEEP_PTX/KEEP_CUBIN environment variables)
  • JitFunctionArtifacts dataclass (jit_executor.py:810) stores PTX/CUBIN/MLIR content

3. Proposal: Adding Hooks to CuTeDSL

3.1 Hook 1: Compilation Listener

Injection point: After the compile_and_cache call in BaseDSL.generate_mlir() (dsl.py:1329) and in the cache hit branch

Note: The hook should NOT be placed inside compile_and_cache(), because generate_mlir() has two cache layers:

  • In-memory cache (line 1378-1408): On hit, uses cached_jit_func directly without calling compile_and_cache()
  • File cache (inside compile_and_cache(), line 1200-1205)

Placing the hook in generate_mlir() captures both compilation events and cache hit events (distinguished by the cache_hit parameter).

After compilation/cache hit in generate_mlir(), the following are available:

  • jit_function -- the compiled JitCompiledFunction, containing JitFunctionArtifacts (PTX, CUBIN, MLIR)
  • module_hash -- cache key
  • function_name -- kernel name
  • funcBody -- the original Python function (can use inspect.getsource() to extract source code)
  • Cache hit/miss status

Proposed callback signature:

def compilation_listener(
    function_name: str,
    module_hash: str,
    cache_hit: bool,
    artifacts: JitFunctionArtifacts,  # PTX, CUBIN, MLIR
    compile_options: dict,            # Compilation options such as arch
    python_source: dict,              # {"file_path": ..., "start_line": ..., "code": ...}
    timing: dict,                     # Per-stage timing (when profiling is enabled)
):

Specific changes (dsl.py, after compilation/cache hit in generate_mlir(), approximately after line 1408):

# compile_and_cache branch (cache miss)
jit_function = self.compile_and_cache(...)
_cache_hit = False

# or cache hit branch
jit_function = cached_jit_func
_cache_hit = True

# Unified listener call after both branches
for listener in _compilation_listeners:
    listener(
        function_name=function_name,
        module_hash=module_hash,
        cache_hit=_cache_hit,
        artifacts=jit_function.artifacts,
        compile_options={...},
        python_source=_extract_python_source(funcBody),
        timing={...},
    )

3.2 Hook 2: Launch Listener

Injection point: Entry of JitCompiledFunction.run_compiled_program() (jit_executor.py:787)

This location covers both the immediate-execution-after-compilation path inside generate_mlir() (line 1418) and the direct JitCompiledFunction.__call__() (line 805) path.

def run_compiled_program(self, exe_args):
    for listener in _launch_listeners:
        listener(
            function_name=self.function_name,
            kernel_info=self.kernel_info,  # Contains grid/block configuration
            args=exe_args,
            stream=...,  # CUDA stream (if available)
        )
    # ... existing logic

3.3 Hook Registration API

Create a new cutedsl_knobs.py or add global hook slots to an existing module:

# CuTeDSL knobs (similar to Triton's knobs module)
# Use lists to support multiple listeners (consistent with newer Triton versions)
_compilation_listeners: List[Callable] = []
_launch_listeners: List[Callable] = []

def add_compilation_listener(listener):
    _compilation_listeners.append(listener)

def remove_compilation_listener(listener):
    _compilation_listeners.remove(listener)

def add_launch_listener(listener):
    _launch_listeners.append(listener)

def remove_launch_listener(listener):
    _launch_listeners.remove(listener)

Design rationale: Using List[Callable] instead of a single listener because:

  1. Triton's knobs.compilation.listener already supports listener lists in newer versions
  2. Prevents multiple tools (e.g., tritonparse + other profiling tools) from overwriting each other
  3. When no listeners are registered, for listener in [] has zero overhead, equivalent to if listener is not None

4. Considerations

4.1 Python Source Extraction

CuTeDSL's _func() already has funcBody (the original Python function), and funcBody is already passed as a parameter to compile_and_cache() (dsl.py:1399, parameter defined at line 1181) and generate_mlir(). Source code can be extracted using inspect.getsource(funcBody) and inspect.getsourcefile(funcBody) without additional plumbing.

4.2 IR Artifacts Extraction

CuTeDSL currently only saves files and populates JitFunctionArtifacts when CUTE_DSL_KEEP_PTX=1 / CUTE_DSL_KEEP_CUBIN=1 / CUTE_DSL_KEEP_IR=1 are set.

Note on MLIR IR timing: keep_ir saves the pre-compilation original IR (written via save_ir() in build_module() at line 1068-1074), not the final IR after cute-to-nvvm passes. This is the correct behavior for tritonparse -- users care about the original CuTe dialect IR.

Two options:

Option Approach Pros/Cons
A Automatically enable KeepPTX/KeepCUBIN/KeepIR when in tritonparse mode Simple and straightforward, but affects compilation behavior (writes files, disables cache)
B Extract IR string directly from MLIR module (str(module)) in the hook, get PTX/CUBIN from compilation pass output Doesn't alter compilation logic, but need to ensure pass output is accessible

Recommended: Option A -- Automatically set CUTE_DSL_KEEP_IR=1 + CUTE_DSL_KEEP_PTX=1 + CUTE_DSL_KEEP_CUBIN=1 during tritonparse initialization. Although this disables caching, tritonparse is a debugging/analysis tool, so disabling cache is acceptable.

4.3 Tritonparse-Side Adaptation

Tritonparse's trace_processor.py and frontend visualization currently assume IR formats are TTIR/TTGIR/LLIR/PTX and need to be extended to support MLIR (CuTe dialect).

However, the core NDJSON log format, stack trace mechanism, and frontend source mapping framework are generic and reusable.

4.4 Performance Impact

  • Hook check is an empty list iteration (for listener in []), zero overhead when no listeners are registered
  • Data collection overhead when registered is similar to Triton's tritonparse (mainly IR serialization and file writing)

4.5 Cache Layers and Hook Coverage

CuTeDSL has two cache layers, and the hook must cover all paths:

Cache Layer Location Hook Coverage
In-memory cache generate_mlir() line 1378-1408 Call listener in the cache hit branch of generate_mlir() (cache_hit=True)
File cache compile_and_cache() line 1200-1205 Called from generate_mlir() after compile_and_cache() returns
No cache (actual compilation) compile_and_cache() line 1210-1257 Same as above (cache_hit=False)

Note: When keep_ptx/keep_cubin is enabled, caching is automatically disabled (_func() line 1634-1639). Every invocation goes through the actual compilation path. Automatically setting these environment variables during tritonparse init (Option A) produces the same behavior, which is acceptable for debugging scenarios.


5. Implementation Plan

5.1 File-Level Change Overview

CuTeDSL Side (minimal changes, 2-3 files)

  1. New file base_dsl/knobs.py -- Define global hook lists (_compilation_listeners, _launch_listeners) and registration functions (add_compilation_listener, add_launch_listener, etc.)
  2. Modify base_dsl/dsl.py -- Call compilation listeners after both compilation and cache hit branches in generate_mlir()
  3. Modify base_dsl/jit_executor.py -- Call launch listeners at the entry of run_compiled_program()

Tritonparse Side

  1. New file cutedsl_logging.py -- Register with CuTeDSL hooks, format output as tritonparse NDJSON
  2. Modify trace_processor.py -- Support MLIR IR type parsing
  3. Modify frontend -- Support MLIR IR syntax highlighting and source mapping

5.2 PR Split Plan

Since this involves two independent repositories (cutlass, tritonparse), the work is split into 4 PRs by dependency:

PR 1 -- CuTeDSL: Add knobs hook infrastructure

  • Repository: cutlass
  • Dependencies: None
  • Estimated size: Small (~150 lines added)
  • Files:
    • New: python/CuTeDSL/cutlass/base_dsl/knobs.py
    • Modify: python/CuTeDSL/cutlass/base_dsl/dsl.py -- Call compilation listeners in generate_mlir()
    • Modify: python/CuTeDSL/cutlass/base_dsl/jit_executor.py -- Call launch listeners in run_compiled_program()
  • Notes: These three files are tightly coupled and form an atomic change. Zero overhead when no hooks are registered, no impact on existing functionality. This PR is a prerequisite for all subsequent work.

PR 2 -- Tritonparse: Add CuTeDSL compilation tracing

  • Repository: tritonparse
  • Dependencies: PR 1 merged
  • Estimated size: Medium (~400 lines)
  • Files:
    • New: tritonparse/cutedsl_logging.py -- Register compilation listener, output NDJSON
    • Modify: tritonparse/structured_logging.py init() -- Add CuTeDSL initialization path (detect if cutlass is importable, automatically set CUTE_DSL_KEEP_IR/PTX/CUBIN environment variables)
    • Modify: tritonparse/parse/trace_processor.py -- Recognize MLIR IR types (add .mlir extension support)
    • Modify: tritonparse/parse/ir_parser.py -- Add MLIR loc directive parsing (CuTe dialect's loc format is similar to but not identical to TTIR/TTGIR)
  • Notes: Compilation tracing is the highest-value component and is independently useful. Once complete, the tritonparse CLI can be used to inspect CuTeDSL kernel compilation IR and metadata.

PR 3 -- Tritonparse: Add CuTeDSL launch tracing

  • Repository: tritonparse
  • Dependencies: PR 1 merged (can be developed in parallel with PR 2)
  • Estimated size: Small (~200 lines)
  • Files:
    • Modify: tritonparse/cutedsl_logging.py -- Register launch listener, collect grid/block/args/stream
    • Modify: tritonparse/parse/trace_processor.py -- Handle CuTeDSL launch event grouping
    • Possibly modify: tritonparse/validation/schemas/ -- Add/extend launch schema
  • Notes: Launch tracing logic is independent from compilation tracing and can be reviewed and tested separately.

PR 4 -- Tritonparse: Frontend MLIR visualization support

  • Repository: tritonparse
  • Dependencies: PR 2 merged
  • Estimated size: Medium (~300 lines)
  • Files:
    • Modify: website/src/utils/irLanguage.ts -- Add CuTe MLIR syntax highlighting rules
    • Modify: website/src/components/TritonIRs.tsx -- Support MLIR tab display
    • Modify: tritonparse/parse/mapper.py -- Add bidirectional MLIR <-> PTX mapping
  • Notes: Frontend changes use a different tech stack (TypeScript vs Python) from backend changes, so reviewers may differ. Can wait until the backend is stable before proceeding.

5.3 Dependency Graph and Execution Path

PR 1 (cutlass: hook infrastructure)
  |
  |---> PR 2 (tritonparse: compilation tracing)
  |       |
  |       +---> PR 4 (tritonparse: frontend MLIR visualization)
  |
  +---> PR 3 (tritonparse: launch tracing)

Fastest path: PR 1 -> PR 2 + PR 3 in parallel -> PR 4, totaling 3 stages.

FindHao avatar May 19 '26 19:05 FindHao

@zhudada0120 The above plan is drafted around one month ago, so some information may be outdated.

FindHao avatar May 19 '26 19:05 FindHao

Hey @zhudada0120 , are you still interested in this?

FindHao avatar Sep 21 '26 17:09 FindHao

Hi @FindHao , I’m interested. However, I have limited spare time for personal development lately. If this feature isn’t particularly urgent, I’d be glad to spend some time each day to keep working on this task.

zhudada0120 avatar Sep 22 '26 02:09 zhudada0120

Hi @FindHao , I’m interested. However, I have limited spare time for personal development lately. If this feature isn’t particularly urgent, I’d be glad to spend some time each day to keep working on this task.

no worries at all! I can take it over then.

Thank you for your contributions! Our TritonParse paper has been accepted to ASPLOS 2027, and I'll be sure to include you in the acknowledgments section in our final version.

FindHao avatar Sep 22 '26 02:09 FindHao

Hi @FindHao , I’m interested. However, I have limited spare time for personal development lately. If this feature isn’t particularly urgent, I’d be glad to spend some time each day to keep working on this task.

no worries at all! I can take it over then.

Thank you for your contributions! Our TritonParse paper has been accepted to ASPLOS 2027, and I'll be sure to include you in the acknowledgments section in our final version.

Congratulations! I’m looking forward to the paper release and will keep following the TritonParse work closely. If I plan to make any contributions, I will check with you first.

zhudada0120 avatar Sep 22 '26 02:09 zhudada0120

https://github.com/NVIDIA/cutlass/pull/3697
https://github.com/NVIDIA/cutlass/pull/3703

compatibility update on tritonparse side is landed. we can update our code when the cutlass side PRs landed.

https://github.com/meta-pytorch/tritonparse/commit/96bd043c81fb966cd28d2cd5c84aa36b9449225e

FindHao avatar Nov 12 '26 01:11 FindHao