mirror of
https://github.com/ROCm/composable_kernel.git
synced 2026-06-28 10:47:00 +00:00
[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.
228 lines
8.4 KiB
Python
228 lines
8.4 KiB
Python
#!/usr/bin/env python3
|
||
|
||
# Copyright (c) Advanced Micro Devices, Inc., or its affiliates.
|
||
# SPDX-License-Identifier: MIT
|
||
|
||
"""
|
||
Unit tests for depthwise convolution rules in codegen/tile_math.py.
|
||
|
||
Ground truth: all 20 profiler depthwise configs extracted from
|
||
configs/grouped_conv/forward/profiler/ngchw_fp16.json (identical
|
||
across fp16/bf16/fp32).
|
||
|
||
Run:
|
||
cd projects/composablekernel/dispatcher
|
||
python3 -m unittest tests/test_depthwise_tile_math.py -v
|
||
"""
|
||
|
||
import sys
|
||
import unittest
|
||
from pathlib import Path
|
||
|
||
SCRIPT_DIR = Path(__file__).parent.resolve()
|
||
DISPATCHER_DIR = SCRIPT_DIR.parent
|
||
sys.path.insert(0, str(DISPATCHER_DIR / "codegen"))
|
||
|
||
from grouped_conv.tile_math import ( # noqa: E402
|
||
DepthwiseConfig,
|
||
is_valid_depthwise_config,
|
||
get_valid_depthwise_configs,
|
||
)
|
||
|
||
# =============================================================================
|
||
# Reference configs from JSON ground truth
|
||
# =============================================================================
|
||
# Tuple order: (tile_h, tile_w, filt, str_h, str_w, pad_h, pad_w,
|
||
# nbatch, sub_h, sub_w, in_vec, out_vec)
|
||
|
||
DEPTHWISE_PROFILER_CONFIGS = [
|
||
(8, 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, 1, 1, 2, 2, 1, 1, 1, 1, 1),
|
||
(32, 32, 5, 1, 1, 2, 2, 4, 4, 4, 8, 8),
|
||
]
|
||
|
||
# Tile/filter/stride space matching grouped_config_rules_default.py
|
||
TILE_SIZES = [(8, 8), (14, 28), (16, 16), (28, 28), (32, 32)]
|
||
FILTER_SIZES = [3, 5]
|
||
STRIDES = [(1, 1), (2, 2)]
|
||
|
||
|
||
def _tuple_to_cfg(t):
|
||
"""Convert a 12-tuple to a DepthwiseConfig."""
|
||
return DepthwiseConfig(*t)
|
||
|
||
|
||
def _cfg_to_tuple(c):
|
||
"""Convert a DepthwiseConfig to a 12-tuple."""
|
||
return (c.tile_h, c.tile_w, c.filt, c.str_h, c.str_w,
|
||
c.pad_h, c.pad_w, c.nbatch, c.sub_h, c.sub_w,
|
||
c.in_vec, c.out_vec)
|
||
|
||
|
||
# =============================================================================
|
||
# Tests
|
||
# =============================================================================
|
||
|
||
class TestIsValidDepthwiseConfig(unittest.TestCase):
|
||
"""Tests for is_valid_depthwise_config()."""
|
||
|
||
def test_all_reference_configs_valid(self):
|
||
"""Every JSON reference config must pass validation."""
|
||
for t in DEPTHWISE_PROFILER_CONFIGS:
|
||
cfg = _tuple_to_cfg(t)
|
||
self.assertTrue(
|
||
is_valid_depthwise_config(cfg),
|
||
f"Reference config should be valid: {t}",
|
||
)
|
||
|
||
def test_all_reference_configs_valid_fp32(self):
|
||
"""Reference configs must also be valid with fp32 dtype_size=4."""
|
||
for t in DEPTHWISE_PROFILER_CONFIGS:
|
||
cfg = _tuple_to_cfg(t)
|
||
self.assertTrue(is_valid_depthwise_config(cfg, dtype_size=4))
|
||
|
||
def test_odd_filter_required(self):
|
||
"""Even filter size must be rejected."""
|
||
cfg = DepthwiseConfig(8, 8, 4, 1, 1, 1, 1, 8, 2, 2, 2, 2)
|
||
self.assertFalse(is_valid_depthwise_config(cfg))
|
||
|
||
def test_pad_w_must_be_positive(self):
|
||
"""PadW=0 must be rejected."""
|
||
cfg = DepthwiseConfig(8, 8, 3, 1, 1, 1, 0, 8, 2, 2, 2, 2)
|
||
self.assertFalse(is_valid_depthwise_config(cfg))
|
||
|
||
def test_subtile_exceeds_tile(self):
|
||
"""sub_h > tile_h must be rejected."""
|
||
cfg = DepthwiseConfig(8, 8, 3, 1, 1, 1, 1, 8, 16, 2, 2, 2)
|
||
self.assertFalse(is_valid_depthwise_config(cfg))
|
||
|
||
def test_total_subtiles_exceeds_64(self):
|
||
"""Config with too many subtiles must be rejected."""
|
||
# sub_h=1, sub_w=1 on tile 16x16 → 256 subtiles > 64
|
||
cfg = DepthwiseConfig(16, 16, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1)
|
||
self.assertFalse(is_valid_depthwise_config(cfg))
|
||
|
||
def test_nbatch_divisibility(self):
|
||
"""nbatch must be divisible by tile_per_wave."""
|
||
# tile_h=8, tile_w=8, sub_h=2, sub_w=2 → 4×4=16 subtiles
|
||
# tile_per_wave = 64//16 = 4, so nbatch=3 is invalid
|
||
cfg = DepthwiseConfig(8, 8, 3, 1, 1, 1, 1, 3, 2, 2, 2, 2)
|
||
self.assertFalse(is_valid_depthwise_config(cfg))
|
||
|
||
def test_vec_not_power_of_2(self):
|
||
"""Non-power-of-2 vector size must be rejected."""
|
||
cfg = DepthwiseConfig(8, 8, 3, 1, 1, 1, 1, 8, 2, 2, 3, 2)
|
||
self.assertFalse(is_valid_depthwise_config(cfg))
|
||
|
||
def test_stride_w_constraint(self):
|
||
"""Odd StrideW != 1 must be rejected."""
|
||
cfg = DepthwiseConfig(8, 8, 3, 1, 3, 1, 1, 8, 2, 2, 2, 2)
|
||
self.assertFalse(is_valid_depthwise_config(cfg))
|
||
|
||
|
||
class TestGetValidDepthwiseConfigs(unittest.TestCase):
|
||
"""Tests for get_valid_depthwise_configs()."""
|
||
|
||
@classmethod
|
||
def setUpClass(cls):
|
||
"""Generate configs once for all tests."""
|
||
cls.generated = get_valid_depthwise_configs(
|
||
TILE_SIZES, FILTER_SIZES, STRIDES,
|
||
)
|
||
cls.generated_set = {_cfg_to_tuple(c) for c in cls.generated}
|
||
|
||
def test_no_false_negatives(self):
|
||
"""Every JSON profiler reference config must be generated by rules."""
|
||
missing = []
|
||
for ref in DEPTHWISE_PROFILER_CONFIGS:
|
||
if ref not in self.generated_set:
|
||
missing.append(ref)
|
||
if missing:
|
||
lines = [f" {m}" for m in missing]
|
||
self.fail(
|
||
f"{len(missing)}/20 profiler configs missing:\n"
|
||
+ "\n".join(lines)
|
||
)
|
||
|
||
def test_test_configs_are_subset(self):
|
||
"""Test configs must also be in the generated set."""
|
||
for ref in DEPTHWISE_TEST_CONFIGS:
|
||
self.assertIn(ref, self.generated_set,
|
||
f"Test config missing: {ref}")
|
||
|
||
def test_all_generated_are_valid(self):
|
||
"""Every generated config must pass all constraint checks."""
|
||
invalid = []
|
||
for cfg in self.generated:
|
||
if not is_valid_depthwise_config(cfg):
|
||
invalid.append(_cfg_to_tuple(cfg))
|
||
if invalid:
|
||
self.fail(f"{len(invalid)} generated configs are invalid")
|
||
|
||
def test_no_duplicates(self):
|
||
"""Generated list must not contain duplicates."""
|
||
self.assertEqual(
|
||
len(self.generated), len(self.generated_set),
|
||
"Duplicate configs found in generated list",
|
||
)
|
||
|
||
def test_generates_nonzero_configs(self):
|
||
"""Must generate at least the 20 reference configs."""
|
||
self.assertGreaterEqual(len(self.generated), 20)
|
||
|
||
def test_coverage_rate(self):
|
||
"""Log coverage statistics (informational)."""
|
||
n_ref = len(DEPTHWISE_PROFILER_CONFIGS)
|
||
n_covered = sum(1 for r in DEPTHWISE_PROFILER_CONFIGS
|
||
if r in self.generated_set)
|
||
n_total = len(self.generated)
|
||
print(f"\n[depthwise coverage] {n_covered}/{n_ref} reference covered, "
|
||
f"{n_total} total generated")
|
||
self.assertEqual(n_covered, n_ref,
|
||
f"Coverage {n_covered}/{n_ref} < 100%")
|
||
|
||
def test_empty_input(self):
|
||
"""Empty tile_sizes should return no configs."""
|
||
self.assertEqual(
|
||
get_valid_depthwise_configs([], [3], [(1, 1)]),
|
||
[],
|
||
)
|
||
|
||
def test_smem_constraint_rejects_huge_tile_fp32(self):
|
||
"""Very large tiles with fp32 should produce fewer configs due to SmemSize."""
|
||
# fp32 (dtype_size=4) doubles SmemSize, pruning more configs
|
||
fp16 = get_valid_depthwise_configs([(32, 32)], [5], [(1, 1)], dtype_size=2)
|
||
fp32 = get_valid_depthwise_configs([(32, 32)], [5], [(1, 1)], dtype_size=4)
|
||
self.assertLess(len(fp32), len(fp16),
|
||
"fp32 should produce fewer valid configs than fp16")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
unittest.main(verbosity=2)
|