Files
composable_kernel/dispatcher/scripts/generate_profiler_kernels.py
Ville Pietilä 60b276647b [rocm-libraries] ROCm/rocm-libraries#8157 (commit b0d9d39)
[CK Tile] Rule-based configuration generation in CK
 Dispatcher codegen (#8157)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

## Motivation

The CK Tile Dispatcher code generation for CK Tile Profiler relies on
flat JSON files to list the generated configurations. This approach has
the following problems

- The JSON files are verbose
- The JSON files get easily out of sync with the CK Builder .config
files from which they were generated from.
- The JSON file based configuration make it hard to list explicitly the
rules that govern the instance generation.

## Technical Details

Replaced the JSON files with a rule based configuration. To preserve the
existing functionality, the `profiler` and the `tests` instance sets are
generated directly from the CK Builder config files. The JSON config
files are removed from source control, and the "on-the-fly" generation
guarantees that the Dispatcher codegen uses up to date configurations.

This is PR introduces six different rule sets for the CK Tile Dispatcher
code generation

1. `profiler`: matches with the old JSON set of profiler configurations.
2. `tests`: matches with the old JSON set of tests configurations.
3. `full`: full configuration set created from a rule-based config
selection
4. `full-tests`: a subset of `full` for generating configurations for
convolution integration tests.
5. `tiny`: a subset of `full-tests` to produce the minimal set of
configurations to test the Dispatcher codegen.
6. `default`: the default rules, which corresponds to the existing
heuristic rules for configuration selection. This ensures that ML based
kernel selection doesn't get broken.

The main use of the `full` rule set is to define a reasonable solution
space for the possible implicit GEMM configurations. We start from the
configurations that allowed by the device architecture. The `full` rule
set defines the relevant tile sizes for each convolution direction. From
the tile size we have a curated mapping to the number of waves over the
different GEMM axes, i.e., we describe how many waves each GEMM
dimensions corresponds to. The GEMM-K wave tile dimension can be
computed from the other parameters and does not need to be listed
explicitly.

An orthogonal axis to the tiling strategy is the vectorization strategy.
This mainly defined by the data type and hardware as in general, we want
to use the maximum possible load widths. The maximum sizes for each
convolution direction variant are defined by the implicit GEMM matrix
dimensions. For cases where have a low number of channels per
convolution group, we need smaller vector load sizes. These are captured
by the `VecStrategy` enumeration in the codegen rules.

The problem with the rule based configuration selection is that we "over
generate" configurations. The old JSON configurations compose
approximately 25% of all configuration that the `full` rule set creates.
The additional configurations are valid, but they many not provide any
performance benefits. Hence, we keep the `profiler` and `tests` rule set
for now to avoid building an excessive amount configurations by default.
The `full` rule set can be taken into use by specifying CMake
configuration flag `-D DISPATCHER_RULE_SET=full`. By default, the
`tests` rule set is used, i.e., we don't change the existing bahaviour.

## Test Plan

Added a new stage in the CI/CD pipeline that ensures the Dispatcher
codegen rules are up to date. Otherwise the functionality is covered by
the existing CI/CD tests. There are no functional changes to the
convolution kernels. Only how the different instances are generated.

## Test Result

If the CK Tile conv instances build without errors, the Dispatcher
codegen is generating valid code. If all tests in CI/CD pipeline are
passing, the Dispatcher codegen generates valid instances.

## Submission Checklist

- [x] Look over the contributing guidelines at
https://github.com/ROCm/ROCm/blob/develop/CONTRIBUTING.md#pull-requests.
2026-06-18 01:22:50 +00:00

173 lines
6.3 KiB
Python
Executable File

#!/usr/bin/env python3
# Copyright (c) Advanced Micro Devices, Inc., or its affiliates.
# SPDX-License-Identifier: MIT
#
# Generates dispatcher-based kernels for the CK Profiler (all directions).
#
# This script:
# 1. Generates GEMM + depthwise configs from tile_math rules via get_default_configs()
# 2. Calls UnifiedGroupedConvCodegen.generate_all() to emit C++ kernel headers
# 3. Generates include_all_grouped_conv_<variant>_kernels.hpp
# 4. Generates chunked register_*_chunk_N.cpp files + register_all_grouped_conv_kernels.cpp
#
# Usage:
# python3 generate_profiler_kernels.py \
# --variant {fwd,bwd_data,bwd_weight} \
# --output-dir <generated-kernel-output-dir> \
# --arch gfx950 \
# [--mode tests|profiler]
import argparse
import sys
from pathlib import Path
from registration_codegen import generate_chunked_registration
VARIANT_CONFIG = {
"fwd": {
"glob_pattern": "grouped_conv_fwd_*.hpp",
"include_all_header": "include_all_grouped_conv_fwd_kernels.hpp",
"description": "forward",
"op_enum": "GroupedConvOp::Forward",
"run_fn_maker": "backends::make_conv_fwd_run_fn",
"is_supported_fn_maker": "backends::make_conv_fwd_is_supported_fn",
"register_fn_name": "register_all_grouped_conv_fwd_kernels",
},
"bwd_data": {
"glob_pattern": "grouped_conv_bwd_data_*.hpp",
"include_all_header": "include_all_grouped_conv_bwd_data_kernels.hpp",
"description": "backward data",
"op_enum": "GroupedConvOp::BackwardData",
"run_fn_maker": "backends::make_conv_bwd_data_run_fn",
"is_supported_fn_maker": "backends::make_conv_bwd_data_is_supported_fn",
"register_fn_name": "register_all_grouped_conv_bwd_data_kernels",
},
"bwd_weight": {
"glob_pattern": "grouped_conv_bwd_weight_*.hpp",
"include_all_header": "include_all_grouped_conv_bwd_weight_kernels.hpp",
"description": "backward weight",
"op_enum": "GroupedConvOp::BackwardWeight",
"run_fn_maker": "backends::make_conv_bwd_weight_run_fn",
"is_supported_fn_maker": "backends::make_conv_bwd_weight_is_supported_fn",
"register_fn_name": "register_all_grouped_conv_bwd_weight_kernels",
},
}
VARIANT_MAP = {
"fwd": "FORWARD",
"bwd_data": "BACKWARD_DATA",
"bwd_weight": "BACKWARD_WEIGHT",
}
def _ensure_codegen_importable():
"""Ensure the codegen directory is on sys.path."""
codegen_dir = str(Path(__file__).resolve().parent.parent / "codegen")
if codegen_dir not in sys.path:
sys.path.insert(0, codegen_dir)
def collect_kernel_headers(output_dir, glob_pattern):
"""Collect all generated .hpp kernel headers matching the variant pattern."""
headers = sorted(Path(output_dir).glob(glob_pattern))
return headers
def generate_include_all_header(headers, output_dir, header_filename, description):
"""Generate include_all_grouped_conv_<variant>_kernels.hpp."""
lines = [
"// Auto-generated \u2014 do not edit",
f"// Includes all generated {description} kernel headers.",
"#pragma once",
"",
]
for h in headers:
lines.append(f'#include "{h.name}"')
lines.append("")
path = Path(output_dir) / header_filename
path.write_text("\n".join(lines))
print(f"Generated {path} ({len(headers)} includes)")
return path
def main():
parser = argparse.ArgumentParser(
description="Generate dispatcher-based kernels for CK Profiler."
)
parser.add_argument("--variant", required=True, choices=list(VARIANT_CONFIG.keys()))
parser.add_argument("--output-dir", required=True)
parser.add_argument("--arch", default="gfx950")
parser.add_argument("--rule-set", default="tests",
choices=["profiler", "tests", "full", "full-tests", "tiny", "default"],
help="Rule set: 'profiler'/'tests' (CK Builder "
"profiler/tests instance sets generated in memory "
"from the .conf configs), 'full' (full rule-derived "
"per-(variant,ndim,datatype) set), 'full-tests' "
"(~20% stratified subset of 'full'), 'tiny' "
"(minimal >=10-config subset of 'full-tests'), or "
"'default' (original hand-curated heuristics)")
args = parser.parse_args()
cfg = VARIANT_CONFIG[args.variant]
output_dir = Path(args.output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
_ensure_codegen_importable()
from unified_grouped_conv_codegen import (
UnifiedGroupedConvCodegen,
GroupedConvVariant,
get_default_configs,
)
variant_enum = GroupedConvVariant[VARIANT_MAP[args.variant]]
datatypes = ["fp16", "bf16", "fp32"]
# --- Step 1: Generate configs from rules ---
print(f"Generating configs from rules (variant={args.variant}, "
f"arch={args.arch}, rule_set={args.rule_set})...")
configs = get_default_configs(
arch=args.arch,
variants=[variant_enum],
ndims=[2, 3],
datatypes=datatypes,
rule_set=args.rule_set,
)
print(f"Generated {len(configs)} configs from rules")
if not configs:
print("ERROR: No configs generated from rules", file=sys.stderr)
sys.exit(1)
# --- Step 2: Generate kernel headers ---
codegen = UnifiedGroupedConvCodegen(
output_dir=output_dir, gpu_target=args.arch, enable_arch_filter=False,
)
codegen.generate_all(configs, datatypes=datatypes)
# --- Step 3: Collect headers and generate registration ---
headers = collect_kernel_headers(output_dir, cfg["glob_pattern"])
print(f"Found {len(headers)} generated kernel headers")
if not headers:
print("ERROR: No kernel headers generated", file=sys.stderr)
sys.exit(1)
generate_include_all_header(headers, output_dir, cfg["include_all_header"], cfg["description"])
generate_chunked_registration(
headers, output_dir,
variant=args.variant,
op_enum=cfg["op_enum"],
run_fn_maker=cfg["run_fn_maker"],
is_supported_fn_maker=cfg["is_supported_fn_maker"],
register_fn_name=cfg["register_fn_name"],
)
print(f"\nDone. {len(headers)} kernels ready in {output_dir}")
if __name__ == "__main__":
main()