tritonparse icon indicating copy to clipboard operation
tritonparse copied to clipboard

Flexible backend support

Open FindHao opened this issue 8 months ago • 12 comments

Hi @zhudada0120, I noticed you forked tritonparse and made some great improvements for supporting flexible backends. I'm really excited to see this work!

Would you be interested in contributing these changes back to our main repo via pull requests when they're ready? We'd love to have your improvements upstream.

(PS: I'm opening this issue here because your fork doesn't have Issues enabled, so I couldn't reach out there directly. Hope that's okay!)

FindHao avatar Apr 01 '26 16:04 FindHao

Yes, I'm working on enabling multi-backend support for tritonparse. I'm currently designing the solution and drafting the RFC, while also validating the feasibility of the approach on the CUDA backend. Once completed, I'll share the proposal with you first for your feedback. Thank you! @FindHao

zhudada0120 avatar Apr 07 '26 12:04 zhudada0120

TritonParse Flexible Backend Support RFC

Author: @zhudada0120

Summary

This RFC proposes a unified extension model for multi-backend support in TritonParse. The goal is to let TritonParse support different backends without repeatedly adding backend-specific logic to shared core code.

The main point is not a single feature. The main point is to move backend-specific rules into one clear and stable layer. The goals are:

  1. Let TritonParse support the backends that Triton already supports today, and the ones it may support next.
  2. Move backend-specific branching logic out of shared core code and into backend adapters.
  3. Let trace, parse, reproducer, and frontend work against one shared backend interface.
  4. Make it easier to add new built-in backends later.

Motivation

Triton is moving from a single-backend model toward multi-backend support. As a companion tool in the Triton ecosystem, TritonParse needs to evolve in the same direction.

If TritonParse keeps organizing runtime, parse, diff, reproducer, and frontend logic around a single backend view, then every new backend will require new special cases across shared code. That does not scale well, and it keeps raising the maintenance cost.

To support multiple backends in a stable way, backend-specific semantics need a single home. They should not stay scattered across shared logic.

Proposal Overview

The target architecture looks like this:

graph LR
    RT[Runtime facts] --> RG[Backend registry]
    RG --> AD[Backend adapter]
    AD --> MD[Trace metadata]
    MD --> PR[Parse and analysis]
    MD --> RP[Reproducer]
    MD --> FE[Frontend]

If we expand that a bit, the key object relationships look like this:

classDiagram
    direction TB

    class structured_logging {
        <<module>>
        +resolve_backend()
        +emit_trace_metadata()
    }
    class trace_processor {
        <<module>>
        +load_trace_metadata()
        +iterate_stages()
    }
    class diff_and_frontend_loaders {
        <<module>>
        +load_stage_descriptors()
        +render_display_stages()
    }
    class ir_analysis {
        <<module>>
        +schedule_analysis_passes()
        +run_stage_analysis()
    }
    class reproducer {
        <<module>>
        +normalize_device()
        +build_sync_snippet()
    }

    class BackendAdapterRegistry {
        +register(adapter)
        +resolve(runtime_backend)
    }
    class TritonParseBackendAdapter {
        <<abstract>>
        +adapter_name : str
        +runtime_backend : str
        +pytorch_module : str
        +get_ir_stages()
        +classify_artifact(artifact_name)
        +normalize_device_string(device)
        +build_synchronize_snippet()
    }
    class IRStageDescriptor {
        +name : str
        +extension : str
        +kind : str
        +display_order : int
        +is_text : bool
        +parser_id : str
    }
    class DerivedArtifactDescriptor {
        +source_extension : str
        +output_stage_name : str
        +output_extension : str
        +tool_name : str
    }
    class AnalysisPassDescriptor {
        +name : str
        +required_stages : tuple
        +optional : bool
    }
    class NvidiaAdapter {
        <<concrete>>
    }
    class AmdAdapter {
        <<concrete>>
    }
    class AscendAdapter {
        <<concrete>>
    }

    structured_logging ..> BackendAdapterRegistry : lookup
    trace_processor ..> BackendAdapterRegistry : lookup
    diff_and_frontend_loaders ..> BackendAdapterRegistry : lookup
    ir_analysis ..> BackendAdapterRegistry : lookup
    reproducer ..> BackendAdapterRegistry : lookup

    BackendAdapterRegistry o-- TritonParseBackendAdapter : registered adapters

    TritonParseBackendAdapter *-- IRStageDescriptor : defines stages
    TritonParseBackendAdapter *-- DerivedArtifactDescriptor : defines derived artifacts
    TritonParseBackendAdapter *-- AnalysisPassDescriptor : defines analysis passes

    TritonParseBackendAdapter <|-- NvidiaAdapter
    TritonParseBackendAdapter <|-- AmdAdapter
    TritonParseBackendAdapter <|-- AscendAdapter

The main classes in this diagram have the following roles:

  1. BackendAdapterRegistry registers and resolves adapters. It maps runtime backend information to a concrete backend implementation.
  2. TritonParseBackendAdapter is the abstract base class for backend adapters. It defines the shared interface for stages, artifacts, device handling, and synchronization.
  3. IRStageDescriptor describes one stage, including its type, display order, text/binary status, source mapping support, and parser.
  4. DerivedArtifactDescriptor describes derived outputs, for example when one runtime artifact can produce an extra stage.
  5. AnalysisPassDescriptor describes optional backend-specific analysis passes and the stages they depend on.

Below is a simple CUDA example for DerivedArtifactDescriptor and AnalysisPassDescriptor.

cuda_derived_artifact = {
    "source_extension": ".cubin",
    "output_stage_name": "sass",
    "output_extension": ".sass",
    "tool_name": "nvdisasm",
}

This example means that on the CUDA backend, a .cubin runtime artifact can produce a .sass stage.

cuda_analysis_pass = {
    "name": "sass_instruction_summary",
    "required_stages": ("sass",),
    "optional": True,
}

This example means there is an optional SASS analysis pass named sass_instruction_summary. The scheduler only needs to know that it depends on the sass stage. It does not need to know the backend-specific analysis details.

The core idea is to use one backend adapter as the single entry point for backend semantics.

Put more simply, questions like “how should this backend work?” should be answered in the adapter, not spread across shared TritonParse flow code.

The responsibilities are split like this:

  1. Triton runtime provides runtime facts such as the target backend, device information, and artifact list.
  2. The backend adapter translates those facts into metadata that TritonParse can use.
  3. The runtime writer writes that metadata into trace metadata.
  4. Parse, reproducer, diff, and frontend consume that metadata directly instead of inferring backend behavior from hardcoded rules.

Shared code drives the flow. The adapter defines backend-specific rules.

To make this boundary clear, we can use a small adapter contract and a unified stage descriptor. A simplified shape is shown below:

class TritonParseBackendAdapter(ABC):
    @property
    @abstractmethod
    def adapter_name(self) -> str: ...

    @property
    @abstractmethod
    def runtime_backend(self) -> str: ...

    @property
    @abstractmethod
    def pytorch_module(self) -> str: ...

    @abstractmethod
    def get_ir_stages(self) -> list[IRStageDescriptor]: ...

    @abstractmethod
    def classify_artifact(self, artifact_name: str) -> IRStageDescriptor | None: ...

    @abstractmethod
    def normalize_device_string(self, device: str) -> str: ...

    @abstractmethod
    def build_synchronize_snippet(self) -> str: ...
@dataclass(frozen=True)
class IRStageDescriptor:
    name: str
    extension: str
    kind: str
    display_name: str
    display_order: int
    is_primary: bool
    is_text: bool
    supports_source_mapping: bool
    parser_id: str
    syntax_id: str

IRStageDescriptor is the key object here. It describes a stage in one place: identity, ordering, text/binary status, source mapping support, and parser choice. This keeps those rules out of shared modules.

From a responsibility point of view, the fields in IRStageDescriptor roughly fall into three groups:

  1. Fields used by both backend and frontend: name, extension, kind
  2. Fields mainly used or defined on the backend side: supports_source_mapping, parser_id
  3. Fields mainly consumed by the frontend: display_name, display_order, is_primary, is_text, syntax_id

This is not strict ownership. It is only a simple way to show which side mainly uses each field.

  • name, extension, and kind define the basic identity of a stage. Both backend and frontend use them.
  • supports_source_mapping and parser_id are more parse-facing. They decide whether a stage supports source mapping and which parser should handle it.
  • display_name, display_order, is_primary, is_text, and syntax_id are more frontend-facing. They control ordering, default selection, visibility, and syntax highlighting.

Below is another simplified CUDA example to show what these two objects carry.

TritonParseBackendAdapter expresses “which backend is this, and what stage model does it define?”

cuda_adapter = {
    "adapter_name": "nvidia",
    "runtime_backend": "cuda",
    "pytorch_module": "torch.cuda",
    "stages": [
        "ttir",
        "ttgir",
        "llir",
        "ptx",
        "cubin",
        "sass",
    ],
}

IRStageDescriptor expresses the semantics of one concrete stage. For example, a PTX stage on CUDA could look like this:

ptx_stage = {
    "name": "ptx",
    "extension": ".ptx",
    "kind": "asm",
    "display_name": "PTX",
    "display_order": 40,
    "is_primary": False,
    "is_text": True,
    "supports_source_mapping": True,
    "parser_id": "ptx_loc",
    "syntax_id": "ptx",
}

Likewise, a CUBIN stage on CUDA could look like this:

cubin_stage = {
    "name": "cubin",
    "extension": ".cubin",
    "kind": "binary",
    "display_name": "CUBIN",
    "display_order": 50,
    "is_primary": False,
    "is_text": False,
    "supports_source_mapping": False,
    "parser_id": "none",
    "syntax_id": "plaintext",
}

This example shows the split clearly: the adapter defines which stages a backend has, and IRStageDescriptor defines what each stage means and how it should be handled.

Around this boundary, an adapter should at least answer the following questions:

  1. What is the basic identity of the current backend?
  2. Which artifacts should be treated as formal stages?
  3. What are the type, order, display name, and basic capabilities of each stage?
  4. Which stages support source mapping, and which parser should handle them?
  5. Does this backend have derived artifacts or extra analysis passes?
  6. In the reproducer path, how should device strings be normalized and how should synchronization be done?
  7. How should the frontend render and order these stages?

Backend semantics should no longer be defined separately in each shared module. They should be exposed through the adapter interface.

Design Principles

This proposal follows a few simple principles:

  1. Shared code should not contain hardcoded logic based on backend names or stage names.
  2. Backend capabilities should be exposed through the adapter interface, not spread across helpers and local rules.
  3. The frontend should only read metadata from the trace. Frontend display fields for IR should also come from the trace.
  4. The first phase should focus on a clean boundary for built-in backends, not on external plugin support.

Implementation Plan

The implementation should stay incremental and focused. We should not try to rewrite every layer at once.

1. Make Runtime the Source of Backend Metadata

The first step is to produce all backend-related metadata during runtime.

This means:

  1. The runtime writer identifies the current backend while collecting data.
  2. The trace explicitly records which backend is in use, which stages exist, and the basic information for each stage.
  3. Artifact classification, stage definitions, and derived output rules should be handled in the adapter as much as possible.

Once the writer produces this contract in a stable way, readers no longer need to guess. They can follow the metadata already stored in the trace.

2. Move Readers to the Trace Contract

The second step is to make parse, diff, and reproducer work from trace metadata instead of relying on file names, suffixes, or local guesses.

This means:

  1. Parse walks and processes stages through stage descriptors.
  2. Parser selection comes from the parser field on the stage descriptor, not from hardcoded string dispatch.
  3. Diff, source mapping, and reproducer gradually switch to these stage descriptors instead of fixed rules.

3. Reduce the Frontend to a Metadata Consumer

The third step is to keep the frontend focused on consuming stage metadata from the trace.

It should only depend on:

  1. stage display order
  2. stage display name
  3. syntax id
  4. is_primary
  5. is_text
  6. source mapping capability

If a rule can be expressed by a stage descriptor, the frontend should not hardcode it again.

4. Migrate the Remaining Backend-Specific Enhancements

The last step is to move the remaining backend-specific capabilities into the adapter layer over time, for example:

  1. analysis passes
  2. derived artifacts
  3. reproducer device normalization
  4. synchronization snippets

The rule stays the same: shared code drives the flow, and adapters provide backend-specific rules.

Expected Outcome

If this direction works out, adding a new backend should mostly mean:

  1. implementing one adapter
  2. defining its stage descriptors and parser choices
  3. defining derived artifacts and analysis passes when needed

It should no longer require repeated invasive changes across shared runtime, parse, reproducer, diff, and frontend modules.

zhudada0120 avatar Apr 09 '26 03:04 zhudada0120

Hi @FindHao ! I’ve completed the RFC for tritonparse's multi-backend support and welcome any feedback. Would you mind reviewing it when convenient?

zhudada0120 avatar Apr 09 '26 03:04 zhudada0120

Hi @FindHao ! I’ve completed the RFC for tritonparse's multi-backend support and welcome any feedback. Would you mind reviewing it when convenient?

Thanks for your work, will take a look!

FindHao avatar Apr 09 '26 21:04 FindHao

Thanks for the thorough RFC, @zhudada0120! The problem diagnosis is right: backend-specific logic is currently scattered across structured_logging.py, ir_parser.py, trace_processor.py, ir_analysis.py, tools/disasm.py, the reproducer path, and the frontend. Centralizing that behind an adapter plus IRStageDescriptor is the right direction.

The main thing I would push on is implementation order and compatibility.

1. Trace schema changes need an explicit additive-only guarantee

The RFC's first implementation step ("Make Runtime the Source of Backend Metadata") touches the trace collection path, which is the most compatibility-sensitive part of the system.

A few constraints are worth making explicit:

  • The input side is not ours to change. Trace data comes from Triton's compilation hooks (knobs.compilation.listener), whose input shape is effectively src, metadata, metadata_group, and times.
  • The existing trace schema is already consumed by parse, diff, reproducer, and frontend. Today they all rely on fields like payload.file_content, payload.file_path, and payload.metadata.

Because of that, I think the RFC should explicitly commit to an additive-only schema evolution strategy:

  • New backend/stage metadata should be added as optional fields, not replace existing ones.
  • Old traces without the new metadata must continue to work.
  • Reader-side code should keep a fallback path that infers stages/backend from filenames/extensions when the new metadata is absent.
  • No Triton hook interface changes should be required.

Without that commitment, the migration path is underspecified and the rollout risk is too high.

2. The highest-value first phase is on the reader side

Given the constraints above, I think the most practical first milestone is not writer-side enrichment, but reader-side cleanup.

That part is fully under TritonParse control and is also where a lot of the current hardcoding lives. For example:

  • source mapping dispatch is currently keyed off fixed IR types
  • IR analysis discovers stages by suffix
  • the frontend types are compile-time enums of known stages

So I'd suggest reordering the implementation plan:

  1. Phase 1 (reader-side): define the adapter/stage-descriptor contract and migrate trace_processor.py, ir_parser.py, ir_analysis.py, diff/reproducer consumers, and the frontend to use it. Old traces should still work via suffix-based fallback.
  2. Phase 2 (writer-side): emit backend/stage metadata into newly written traces as an additive enhancement.
  3. Phase 3 (multi-DSL generalization): since we are already exploring support for other DSL/compiler pipelines such as CuteDSL, the abstraction should be generalized early enough that we do not lock ourselves into a Triton-only naming/model boundary.

I think this ordering gives us most of the architectural value immediately, without making the writer path the critical path.

3. A few design details should be tightened

  • Parser dispatch: parser_id is a reasonable handle, but the RFC should define how it maps to actual parser implementations. PTX .loc, AMDGCN .loc, SASS //## File, and MLIR #loc are not one parser with minor config differences.
  • DerivedArtifactDescriptor: the RFC should say who is responsible for executing the derivation tool, resolving tool paths, and surfacing failures. For CUDA, nvdisasm resolution/error handling is part of the backend-specific behavior.
  • IRStageDescriptor mixes semantic and presentation concerns: fields like name, extension, kind, supports_source_mapping, and parser binding feel like core stage semantics, while display_name, display_order, is_primary, and syntax_id are frontend presentation. The RFC does not necessarily need two objects, but it should acknowledge this split clearly.
  • Frontend migration cost: the current frontend source-mapping/data types are statically shaped around ttir / ttgir / llir / ptx / amdgcn / sass. Moving to descriptor-driven stages is doable, but it is not a zero-cost change and should be called out as such.
  • Registry scope: for built-in backends only, a simple built-in mapping may be enough initially. A more extensible registry model can come later if external backend/plugin registration becomes a real requirement.

4. One important design point: backend vs pipeline/DSL

I do think the RFC is currently a bit too backend-centric for where we may need to go next.

We are already exploring support for other DSL/compiler pipelines beyond Triton, such as CuteDSL. Once that enters scope, the stage model is no longer just a backend question:

  • one dimension is the backend: CUDA, AMD, Ascend, ...
  • another dimension is the compiler pipeline / DSL: Triton, CuteDSL, ...

Those pipelines may have different stage graphs, artifact types, and source-mapping formats. So if we keep the abstraction named and shaped strictly as TritonParseBackendAdapter, we may end up baking in a Triton-specific assumption too early.

I do not think this RFC needs to solve the full multi-DSL design right now, but I do think it should acknowledge that direction explicitly and choose naming/layering that will not make CuteDSL support awkward later. Even a lightweight statement of the intended layering would help, e.g. a pipeline/compiler-level abstraction above backend-specific stage details.

Summary

So my view is:

  • the direction is right
  • the adapter/stage-descriptor split is worth doing
  • the RFC should make backward compatibility explicit
  • the migration plan should start with reader-side adoption, then add writer-side metadata

If those pieces are clarified, I think the proposal becomes much easier to execute incrementally and much safer to roll out.

FindHao avatar Apr 09 '26 23:04 FindHao

Hi @FindHao , A huge thank you for your detailed and valuable feedback on this RFC! Your insights will be really helpful for polishing the design and implementation. I’ll factor in all your points and refine the RFC thoroughly, and I truly appreciate you taking the time to share such comprehensive thoughts with us!

zhudada0120 avatar Apr 10 '26 02:04 zhudada0120

TritonParse Flexible Backend Support RFC

Author: @zhudada0120

Abstract

This RFC proposes a unified extension architecture for TritonParse. It is intended to support multiple backends, and eventually multiple DSL/compiler pipelines, without repeated changes to shared core code.

The focus is not on any single feature. It is on consolidating backend-related rules into a clear, stable layer. The core goals are:

  1. Enable TritonParse to reliably support the backends that Triton already supports, or is likely to support next, while preserving clear layering for future multi-DSL and multi-pipeline scenarios.
  2. Extract backend-specific conditional code from shared core code into individual backend adapters.
  3. Enable trace, parse, reproducer, and frontend to work together around the same backend interface.
  4. Provide a reusable extension path for adding new built-in backends.

Motivation

Triton is gradually moving from a single-backend execution model toward multi-backend support. As a companion tool in the Triton upstream ecosystem, TritonParse needs to evolve in the same direction.

At the same time, TritonParse should not evolve only around "the same DSL with different backends." As DSLs such as CuteDSL enter the discussion, stage graphs, artifact types, and source-mapping rules may all be shaped by both backend and pipeline.

If TritonParse continues to organize runtime, parse, diff, reproducer, and frontend logic with a single backend mindset, each new backend will require new backend-specific conditional code in shared code. This approach is not only hard to extend but also increases maintenance costs.

To give TritonParse stable multi-backend support, backend-related semantics need a single point of ownership rather than being scattered across shared logic.

Proposal Overview

Target Architecture

graph LR
    RT[Runtime facts] --> RG[Pipeline and backend registry]
    RG --> AD[Pipeline adapter]
    AD --> MD[Trace metadata]
    MD --> PR[Parse and analysis]
    MD --> RP[Reproducer]
    MD --> FE[Frontend]

Component Design

If further expanded, the key object relationships in this proposal can be represented as:

classDiagram
    direction TB

    class structured_logging {
        <<module>>
        +resolve_backend()
        +emit_trace_metadata()
    }
    class trace_processor {
        <<module>>
        +load_trace_metadata()
        +iterate_stages()
    }
    class diff_and_frontend_loaders {
        <<module>>
        +load_stage_descriptors()
        +render_display_stages()
    }
    class ir_analysis {
        <<module>>
        +schedule_analysis_passes()
        +run_stage_analysis()
    }
    class reproducer {
        <<module>>
        +normalize_device()
        +build_sync_snippet()
    }

    class PipelineAdapterRegistry {
        +register(adapter)
        +resolve(runtime_backend, pipeline_kind)
    }
    class CompilationPipelineAdapter {
        <<abstract>>
        +adapter_name : str
        +pipeline_kind : str
        +runtime_backend : str
        +pytorch_module : str
        +get_ir_stages()
        +classify_artifact(artifact_name)
        +normalize_device_string(device)
        +build_synchronize_snippet()
    }
    class IRStageDescriptor {
        +name : str
        +extension : str
        +kind : str
        +display_order : int
        +is_text : bool
        +parser_id : str
    }
    class DerivedArtifactDescriptor {
        +source_extension : str
        +output_stage_name : str
        +output_extension : str
        +tool_name : str
    }
    class AnalysisPassDescriptor {
        +name : str
        +required_stages : tuple
        +optional : bool
    }
    class NvidiaTritonAdapter {
        <<concrete>>
    }
    class AmdTritonAdapter {
        <<concrete>>
    }
    class AscendTritonAdapter {
        <<concrete>>
    }

    structured_logging ..> PipelineAdapterRegistry : lookup
    trace_processor ..> PipelineAdapterRegistry : lookup
    diff_and_frontend_loaders ..> PipelineAdapterRegistry : lookup
    ir_analysis ..> PipelineAdapterRegistry : lookup
    reproducer ..> PipelineAdapterRegistry : lookup

    PipelineAdapterRegistry o-- CompilationPipelineAdapter : registered adapters

    CompilationPipelineAdapter *-- IRStageDescriptor : defines stages
    CompilationPipelineAdapter *-- DerivedArtifactDescriptor : defines derived artifacts
    CompilationPipelineAdapter *-- AnalysisPassDescriptor : defines analysis passes

    CompilationPipelineAdapter <|-- NvidiaTritonAdapter
    CompilationPipelineAdapter <|-- AmdTritonAdapter
    CompilationPipelineAdapter <|-- AscendTritonAdapter

The key classes in this diagram have the following responsibilities:

  1. PipelineAdapterRegistry: Registers and resolves adapters. Initially supports built-in mappings, resolving to specific implementation classes based on pipeline_kind + runtime_backend.
  2. CompilationPipelineAdapter: Abstract base class for compilation pipelines. The main focus is multi-backend convergence under Triton pipeline, but the abstraction is not limited to "backend adapter only."
  3. IRStageDescriptor: Describes basic information for a single stage, such as stage type, display order, text/binary, source mapping support, and parser selection.
  4. DerivedArtifactDescriptor: Describes artifact generation relationships, such as whether a runtime artifact can generate additional stages.
  5. AnalysisPassDescriptor: Describes optional analysis passes for a backend and which stages they depend on.

The core idea is to use a single adapter as the unified entry point for compilation-pipeline semantics.

More plainly, questions like "how should this backend be handled" should be answered by the adapter rather than scattered across shared code in the TritonParse main flow.

Responsibility division:

  1. Triton runtime provides runtime facts such as the target backend, device information, and artifact list.
  2. The adapter translates those facts into metadata or reader-side descriptor views that TritonParse needs.
  3. The runtime writer incrementally writes new metadata into the trace while maintaining compatibility.
  4. Parse, reproducer, diff, and frontend consume that metadata first; when it is missing, they fall back to the existing filename- and extension-based inference path.

Shared code in the TritonParse main flow orchestrates the pipeline, while adapters define backend-specific rules.

Pipeline Adapter Interface Design

To make this boundary clearer, use a concise adapter contract and unified stage descriptor to carry main semantics:

class CompilationPipelineAdapter(ABC):
    @property
    @abstractmethod
    def adapter_name(self) -> str: ...

    @property
    @abstractmethod
    def pipeline_kind(self) -> str: ...

    @property
    @abstractmethod
    def runtime_backend(self) -> str: ...

    @property
    @abstractmethod
    def pytorch_module(self) -> str: ...

    @abstractmethod
    def get_ir_stages(self) -> list[IRStageDescriptor]: ...

    @abstractmethod
    def classify_artifact(self, artifact_name: str) -> IRStageDescriptor | None: ...

    @abstractmethod
    def normalize_device_string(self, device: str) -> str: ...

    @abstractmethod
    def build_synchronize_snippet(self) -> str: ...

CompilationPipelineAdapter in this CUDA example expresses "who this compilation chain is and its stage semantics":

cuda_adapter = {
    "adapter_name": "triton_nvidia",
    "pipeline_kind": "triton",
    "runtime_backend": "cuda",
    "pytorch_module": "torch.cuda",
    "stages": [
        "ttir",
        "ttgir",
        "llir",
        "ptx",
        "cubin",
        "sass",
    ],
}

IRStageDescriptor Field Description

@dataclass(frozen=True)
class IRStageDescriptor:
    name: str
    extension: str
    kind: str
    display_name: str
    display_order: int
    is_primary: bool
    is_text: bool
    supports_source_mapping: bool
    parser_id: str
    syntax_id: str

IRStageDescriptor is the key object. It gives a uniform description of stage identity, display order, text attributes, source-mapping capability, and parser selection, so these rules no longer need to be scattered across shared modules.

Field responsibilities:

  1. Core stage semantics: name, extension, kind, supports_source_mapping, parser_id
  2. Display-related: display_name, display_order, is_primary, is_text, syntax_id
  • name, extension, and kind define the basic identity of a stage and are used on both the frontend and backend sides.
  • supports_source_mapping and parser_id are more parse-oriented: supports_source_mapping determines whether a stage can participate in source mapping, and parser_id is a stable key for resolving the parser implementation for that IR stage.
  • display_name, display_order, is_primary, is_text, and syntax_id are more frontend-oriented: they determine stage order, the default stage, which stages should be rendered, and which syntax highlighting should be used.

For CUDA, the PTX stage can be written as:

ptx_stage = {
    "name": "ptx",
    "extension": ".ptx",
    "kind": "asm",
    "display_name": "PTX",
    "display_order": 40,
    "is_primary": False,
    "is_text": True,
    "supports_source_mapping": True,
    "parser_id": "ptx_loc",
    "syntax_id": "ptx",
}

Similarly, the CUBIN stage under CUDA can be written as:

cubin_stage = {
    "name": "cubin",
    "extension": ".cubin",
    "kind": "binary",
    "display_name": "CUBIN",
    "display_order": 50,
    "is_primary": False,
    "is_text": False,
    "supports_source_mapping": False,
    "parser_id": "none",
    "syntax_id": "plaintext",
}

The adapter answers which stages a backend exposes, while IRStageDescriptor defines the basic information for each stage and how it should be handled.

Derived Artifacts

Some backend runtime artifacts can derive additional stages. For example, on the CUDA backend, .cubin files can be disassembled into .sass code by the nvdisasm tool.

Derived Artifact Declaration

Adapter declares supported derivation capabilities through DerivedArtifactDescriptor:

cuda_derived_artifact = {
    "source_extension": ".cubin",
    "output_stage_name": "sass",
    "output_extension": ".sass",
    "tool_name": "nvdisasm",
}

This example means that, on CUDA, a .sass stage can be derived from a .cubin runtime artifact.

Derivation Control Mechanism

Derivation control is divided into two layers:

1. User Configuration Layer

Users control whether to enable derivation capabilities through:

  • Environment variable (for CUDA SASS):

    export TRITONPARSE_DUMP_SASS=1
    
  • init function parameters:

    # Backward compatible: CUDA SASS specific parameter
    tritonparse.structured_logging.init(log_folder, enable_sass_dump=True)
    
    # General derivation capability control (new)
    tritonparse.structured_logging.init(
        log_folder,
        enable_derived_artifacts=True  # Enable all available derivations
    )
    
    # Specify specific derivation capabilities
    tritonparse.structured_logging.init(
        log_folder,
        enable_derived_artifacts=["sass", "amdgcn_disasm"]
    )
    

2. Adapter Capability Layer

Adapter provides derivation capability declaration and availability check:

class NvidiaBackendAdapter:
    def get_derived_artifacts(self):
        """Declare supported derivation capabilities"""
        return [
            DerivedArtifactDescriptor(
                source_extension=".cubin",
                output_stage_name="sass",
                output_extension=".sass",
                tool_name="nvdisasm",
            )
        ]

    def is_derivation_tool_available(self, desc: DerivedArtifactDescriptor):
        """Check if derivation tool is available"""
        if desc.output_stage_name == "sass":
            return self._check_nvdisasm()
        return False

    def collect_derived_artifact_contents(self, metadata_group: dict[str, str]):
        """Execute derivation operation, return derived content"""
        # Find cubin file
        cubin_path = None
        for artifact_name, artifact_path in metadata_group.items():
            if artifact_name.endswith(".cubin"):
                cubin_path = artifact_path
                break

        if not cubin_path:
            return {}

        # Call nvdisasm to perform conversion
        from tritonparse.tools.disasm import extract

        sass_content = extract(cubin_path)
        if not isinstance(sass_content, str):
            return {}

        # Return derivation result
        sass_filename = f"{Path(cubin_path).stem}.sass"
        return {sass_filename: sass_content}

Responsibilities

Derivation execution follows a simple split of responsibilities:

  • Shared layer: Determines which derivation capabilities are needed based on user configuration, checks tool availability, and calls the adapter to execute the derivation.
  • Adapter: Declares derivation capabilities, checks tool availability, executes the derivation operation, and handles errors.

For example, when user sets enable_derived_artifacts=["sass"]:

  1. Shared layer parses config, knows user enabled "sass" derivation
  2. Shared layer asks adapter: "Do you have sass derivation capability? Is tool available?"
  3. Adapter checks if nvdisasm is available, returns result
  4. If available, shared layer calls adapter to execute derivation
  5. Adapter handles calling nvdisasm, error details, etc.

Design benefits:

  • Backward compatible: Keeps the existing enable_sass_dump parameter.
  • Extensible: Adding a new derivation capability only requires declaring it in the adapter, with no shared-layer changes.
  • Flexible control: Lets users precisely control which derivation capabilities to enable.

Analysis Passes

Some backends may provide additional analysis passes for deeper IR inspection, specific pattern detection, or performance-related data extraction.

Analysis Pass Declaration

Adapter declares supported analysis capabilities through AnalysisPassDescriptor:

class AmdBackendAdapter:
    def get_analysis_passes(self):
        return [
            AnalysisPassDescriptor(
                name="amd_blockpingpong_detection",
                required_stages=("ttgir",),
                optional=True,
            ),
            AnalysisPassDescriptor(
                name="amd_bufferops_analysis",
                required_stages=("ttgir", "amdgcn"),
                optional=True,
            ),
        ]

Analysis Control Mechanism

User Configuration Layer: Control through init parameters

# Enable all analyses
init(log_folder, enable_analysis_passes=True)

# Enable specific analyses
init(log_folder, enable_analysis_passes=["amd_blockpingpong_detection"])

# Disable all analyses
init(log_folder, enable_analysis_passes=False)

Adapter Capability Layer: Provide declaration and execution interfaces

class AmdBackendAdapter:
    def get_analysis_passes(self):
        """Declare supported analysis capabilities"""
        return [...]
    
    def run_analysis_pass(self, pass_name, payload):
        """Execute specified analysis pass"""
        if pass_name == "amd_blockpingpong_detection":
            return self._detect_blockpingpong(payload)
        return {}

Existing Capability Migration

Current problem: AMD-specific analysis hardcoded in shared code

# Shared code has AMD-specific logic
if amdgcn_key and ttgir_key:
    io_counts = _analyze_buffer_ops(...)

After migration: AMD adapter manages AMD-specific analysis

class AmdBackendAdapter:
    def _detect_blockpingpong(self, payload):
        # AMD adapter loads its own config file
        config_path = "adapters/amd_procedure_checks.json"
        procedure_checks = load_procedure_checks_from_file(config_path)
        return find_procedures_with_patterns(procedure_checks, ...)

Responsibilities

Analysis execution follows a simple split of responsibilities:

  • Shared layer: Determines which analyses are needed, checks stage availability, and calls the adapter to execute them.
  • Adapter: Declares analysis capabilities, executes the backend-specific analysis logic, and returns the results.

Execution flow:

  1. User config enables which analysis capabilities (e.g., enable_analysis_passes=["amd_blockpingpong_detection"])
  2. Shared layer asks adapter: "Which analyses do you support? What stages do they depend on?"
  3. Adapter returns analysis capability list and dependencies
  4. Shared layer checks if dependent stages exist, matches user config
  5. Shared layer calls adapter to execute available analysis operations
  6. Adapter returns analysis results (detected BlockPingpong patterns, buffer operation stats, etc.)

Summary of Adapter Responsibilities

At this boundary, an adapter should at least answer the following questions:

  1. What is the basic information for this backend?
  2. Which artifacts constitute formal stages?
  3. What are the types, order, display names, and basic capabilities of each stage?
  4. Which stages support source mapping and which parser should handle them?
  5. Does this backend have derived artifacts or additional analysis capabilities?
  6. How should device be normalized in reproducer path and how to execute synchronization?
  7. How should frontend render and sort these stages?

Backend-related semantics are no longer defined separately by each shared module. Instead, they are exposed uniformly through the adapter interface.

Design Principles and Migration Boundaries

This proposal follows these boundaries in both design and implementation order:

  1. Shared code should not contain hardcoded logic keyed on backend names or stage names.
  2. Backend capabilities should be exposed uniformly through the adapter interface rather than scattered across helpers and local rules.
  3. Trace schema evolution follows an additive-only compatibility strategy: new metadata can only be attached as optional fields and must not replace existing fields.
  4. The existing trace schema remains compatible; fields already relied on by consumers, such as payload.file_content, payload.file_path, and payload.metadata, will not be replaced.
  5. Old traces must remain readable when new metadata is absent; reader-side code must keep the fallback path based on existing filenames, suffixes, and conventions.
  6. Before reader-side migration is complete, the old and new paths will coexist. New descriptor-driven logic should consume metadata first and fall back to suffix- or extension-based inference when metadata is missing.
  7. Writing new metadata is a writer-side enhancement, not a prerequisite for reader-side refactoring.
  8. This proposal does not require changes to the Triton compilation-hook input interface; writer-side code can only consume facts already provided by the hook, such as src, metadata, metadata_group, and times.
  9. The frontend should prefer descriptors from the trace, but this is an explicit migration cost rather than a zero-cost replacement.
  10. The registry initially only needs to cover built-in mappings; an external registration model can be added later.

Compatibility is most sensitive in the trace-collection path, so items 3 through 8 should be treated as explicit migration commitments of this RFC.

This means the benefits of this RFC can land first on TritonParse's fully controllable reader side. Writer-side enrichment can then be added later as a compatible enhancement.

Implementation Plan

The implementation should stay incremental and focused rather than attempting to transform every layer at once.

Phase 1. Reader-side Backend Convergence

The first phase prioritizes TritonParse's fully controllable reader side, where the hardcoded logic is currently most concentrated.

This means:

  1. Define multi-layer adapter architecture:

    • Pipeline layer: describes different DSL or compiler pipelines, such as Triton and future CuteDSL variants.
    • Backend layer: describes different backends under the same pipeline, such as CUDA, ROCm, and Ascend.
    • Support resolving pipeline_kind + runtime_backend as a two-dimensional key from the start.
  2. Define adapter/stage descriptor contract:

    • Provide unified entry points for parser binding, derived artifacts, and analysis passes.
    • Gradually migrate consumers such as trace_processor.py, ir_parser.py, ir_analysis.py, and diff/reproducer flows to work from descriptors.
  3. Preserve fallback path:

    • Keep the suffix-based fallback path on the reader side when new metadata is absent.
    • Ensure old traces remain readable.

Goal of this phase: Move stage interpretation out of scattered hardcoded logic and into a unified contract, while preserving clear extension layers for multi-DSL support.

Phase 2. Reader-side Frontend Migration

Frontend migration work:

  1. Data layer transformation:

    • Change hardcoded stage lists (ttir, ttgir, llir, ptx, amdgcn, sass, etc.) to read dynamically from stage descriptors in trace metadata.
    • Adjust frontend data type definitions so they can carry dynamic stage information for different backends.
  2. Logic layer transformation:

    • Update source-mapping logic from hardcoded stage names to the IRStageDescriptor.supports_source_mapping field.
    • Modify UI rendering logic to sort and display stages dynamically based on display_order and is_primary.
    • Update syntax-highlighting binding from a static mapping to syntax_id-based dynamic selection.
  3. Compatibility guarantee:

    • Ensure old traces without metadata still work through the filename- and extension-based fallback logic.
    • Thoroughly test both new and old trace formats to ensure that migration does not degrade the user experience.

Phase 3. Backend-Specific Capability Convergence

The third phase moves the remaining backend-specific capabilities into the adapter model, using the interfaces already reserved in the Phase 1 architecture.

This includes:

  1. Derivation capabilities: derived artifacts (e.g., CUBIN → SASS)
  2. Analysis capabilities: analysis passes (e.g., AMD BlockPingpong detection)
  3. Reproducer capabilities: device normalization, synchronization snippets
  4. Extension capabilities: reserve integration boundaries for future CuteDSL and other pipelines

Key design principles:

  • The adapter is pipeline-aware from the start.
  • One layer describes the pipeline or compiler graph, while another describes backend-specific stage semantics and tool behavior.
  • Even if CuteDSL or another pipeline is introduced later, the design should not force all differences into Triton-only naming boundaries.

Goal of this phase: Validate the available backend-specific capabilities on the reader side and lay the groundwork for the next phase of writer-side enhancement.

Phase 4. Writer-side Metadata Enhancement

The fourth phase addresses the runtime writer. The key requirement is to enrich metadata without breaking compatibility.

This means:

  1. The writer continues to support the existing trace schema and only attaches new optional metadata fields.
  2. Backend and stage metadata remain limited to the input facts already provided by the Triton hook; no change to the hook shape is required.
  3. Newly written traces can directly carry backend, pipeline, and stage-descriptor information, reducing the amount of inference required on the reader side.
  4. When new metadata is absent, the reader still follows the fallback path established in Phase 1.

Value of this phase: After Phase 3 validates backend capabilities on the reader side, writer-side enhancement can provide richer metadata. That reduces reader-side inference and improves both performance and user experience.

Expected Results

If this direction is fully implemented, adding a new backend should mainly require:

  1. Implement an adapter for the corresponding pipeline/backend.
  2. Define its stage descriptors and parser selection.
  3. Define its derived artifacts and analysis passes as needed.

It should no longer require repeated invasive modifications to shared runtime, parse, reproducer, diff, and frontend modules.

For new backends in the Triton ecosystem, this reduces the required work to a clear and enumerable adaptation surface. For future DSLs or compiler pipelines, this layering avoids mixing pipeline-level and backend-level differences into the same conditional logic.

zhudada0120 avatar Apr 14 '26 08:04 zhudada0120

Hi @FindHao , Thanks again for the very detailed feedback on the previous RFC. I revised the new version with those comments in mind, and I'd appreciate it if you could take another look when you have time.

This revision mainly focuses on a few points you called out:

  • Compatibility is now explicit: trace schema evolution is described as additive-only, old traces still need to work via fallback paths, existing fields are preserved, and no Triton hook interface changes are required.
  • Implementation plan is reordered: it now starts with reader-side convergence instead of making writer-side metadata the first step.
  • Abstraction is widened: from a backend-only view to a pipeline + backend layering, so we do not lock ourselves into Triton-only naming or assumptions too early.
  • Design details are tightened: including parser dispatch, responsibility boundaries for derived artifacts, the semantic vs. presentation split inside IRStageDescriptor, the frontend migration cost, and keeping the registry scope limited to built-in mappings for now.

The overall direction is still the same, but the incremental rollout path and compatibility constraints should now be much clearer. If you have time, I'd really appreciate another pass on this updated version.

zhudada0120 avatar Apr 14 '26 08:04 zhudada0120

Thanks for the updated RFC, @zhudada0120. This version is a big improvement.

The key concerns from my earlier review are well addressed:

  • The additive-only compatibility commitment is now explicit (principles 3–8), which is exactly what I was looking for.
  • The implementation order is reordered to start from the reader side — I think this is the right call.
  • The naming and layering now reflect the pipeline + backend two-dimensional model, which leaves room for future DSL support.
  • The DerivedArtifactDescriptor section now clearly defines the responsibility split and control mechanism.
  • The frontend migration cost is acknowledged as an explicit cost rather than a zero-cost change.

A few items that can be figured out during implementation rather than in the RFC:

  • How parser_id maps to actual parser implementations (e.g., registry lookup vs. factory pattern).
  • The exact shape of the payload / output contract for analysis passes.
  • A concrete example of how a non-Triton pipeline adapter would differ.

These don't need to block the RFC. They'll become clear as we work through the first few PRs.

I think this is ready to move forward. Looking forward to seeing the implementation!

FindHao avatar Apr 14 '26 23:04 FindHao

Overall progress of multi-backend transformation:

  • https://github.com/meta-pytorch/tritonparse/pull/387 (Reader-side infrastructure & generic parse logic)
  • https://github.com/meta-pytorch/tritonparse/pull/394 (Parser dispatch refactoring)
  • https://github.com/meta-pytorch/tritonparse/pull/401 (Analysis dispatch refactoring)
  • https://github.com/meta-pytorch/tritonparse/pull/403 (Derived artifact refactoring)
  • https://github.com/meta-pytorch/tritonparse/pull/404 (Reproducer refactoring)
  • https://github.com/meta-pytorch/tritonparse/pull/406 (backend trace enrichment)
  • https://github.com/meta-pytorch/tritonparse/pull/408 (Frontend Generalization)
  • https://github.com/meta-pytorch/tritonparse/pull/409 (Change Registries from Class-level Sharing to Instance-level Isolation)
  • https://github.com/meta-pytorch/tritonparse/pull/409 (Move Core Registries and Data Classes to backend.py to Eliminate Circular Dependencies)

Pending tasks:

  • [x] ir_analysis Frontend Generalization Transformation The hardcoding transformation of the ir_analysis frontend functions is currently incomplete, and a transformation scheme needs to be designed.

  • [x] Change Registries from Class-level Sharing to Instance-level Isolation Currently, ParserRegistry, AnalysisRegistry, and DerivedArtifactRegistry are all implemented as class-level variables, with all adapters sharing the same registries. This results in coupling between the parser and analyzer registrations for different backends (NVIDIA/AMD), making independent management impossible. They should be modified so that each adapter instance holds an independent registry to achieve complete isolation between backends.

  • [x] Move Core Registries and Data Classes to backend.py to Eliminate Circular Dependencies Migrate ParserRegistry, AnalysisRegistry, and AnalyzerInfo from ir_parser.py / ir_analysis.py to backend.py, aligning with the existing DerivedArtifactRegistry. Currently, the three modules (backend.py ↔ ir_analysis.py ↔ shared_vars.py) maintain the loading order through extensive lazy imports, forming fragile three-way circular dependencies. After the migration, the dependency direction will be unified: backend.py serves as the centralized registration hub, while ir_analysis.py and ir_parser.py are only responsible for specific implementations.

  • [x] Add integration guide and reference implementation for new backends Based on the finalized adapter architecture, compile integration documentation for new backend developers. It covers the standard procedures of inheriting CompilationPipelineAdapter, declaring stage descriptors, and registering parsers, derived artifacts and analysis passes. Meanwhile, provide a minimal runnable reference adapter implementation, enabling integrating parties to complete new backend adaptation without reading internal source code.

zhudada0120 avatar May 15 '26 02:05 zhudada0120

Hi @FindHao , the generalization of the backend has been completed, so this issue can be closed. I will start analyzing the implementation plan for cuTile and cuteDSL soon.

zhudada0120 avatar Jun 01 '26 12:06 zhudada0120

Hi @FindHao , the generalization of the backend has been completed, so this issue can be closed. I will start analyzing the implementation plan for cuTile and cuteDSL soon.

Thank you so much for all your contribution on this topic!

FindHao avatar Jun 01 '26 15:06 FindHao