diff --git a/dnn-providers/hip-kernel-provider/rocke/AGENTS.md b/dnn-providers/hip-kernel-provider/rocke/AGENTS.md index dcbbdbe8935e..ca5e542437cf 100644 --- a/dnn-providers/hip-kernel-provider/rocke/AGENTS.md +++ b/dnn-providers/hip-kernel-provider/rocke/AGENTS.md @@ -32,6 +32,7 @@ cd platform && export ROCKE=$(pwd) PYTHONPATH=$ROCKE/python ROCKE_LLVM_FLAVOR=llvm20 python tools/check_byte_identity.py # llvm20 ROCKE_LLVM_FLAVOR=llvm22 python tools/check_byte_identity.py # llvm22 ROCKE_LLVM_FLAVOR=llvm23 python tools/check_byte_identity.py # llvm23 +ROCKE_LLVM_FLAVOR=llvm24 python tools/check_byte_identity.py # llvm24 python tools/check_byte_identity.py --only gemm # scope to a family ``` diff --git a/dnn-providers/hip-kernel-provider/rocke/KERNEL_AUTHORING.md b/dnn-providers/hip-kernel-provider/rocke/KERNEL_AUTHORING.md index 2357f9c1dc39..448795ec4e8b 100644 --- a/dnn-providers/hip-kernel-provider/rocke/KERNEL_AUTHORING.md +++ b/dnn-providers/hip-kernel-provider/rocke/KERNEL_AUTHORING.md @@ -81,7 +81,7 @@ python dnn-providers/hip-kernel-provider/rocke/tools/run_checks.py It **auto-discovers** every `test_*.py` and every `_emit.{py,c}` parity pair — so adding a new test needs **no** edit to any script or checklist. It runs, -in order: relative-path guard → byte-identity gate (`llvm20`, `llvm22`, and `llvm23`) → +in order: relative-path guard → byte-identity gate (`llvm20`, `llvm22`, `llvm23`, and `llvm24`) → platform + library parity → pytest (both suites) → on-GPU numeric (auto-skips when no device). Scope while iterating with: @@ -212,8 +212,8 @@ device matching each required architecture. | Every affected `(spec, arch)` pair | Must be explicitly enumerated by the family emitters | Required for kernel behavior changed on that architecture; use a matching remote lane when local hardware is absent | | gfx950 baseline defaults | Covered only where the emitter defaults or pins gfx950 | Required for attention changes that affect gfx950 | -All supported LLVM flavors (`llvm20`, `llvm22`, and `llvm23`) are part of -"gate GREEN" — the runner does all three by default. If you lack a device for an +All supported LLVM flavors (`llvm20`, `llvm22`, `llvm23`, and `llvm24`) are part of +"gate GREEN" — the runner does all four by default. If you lack a device for an arch, use the remote GPU path rather than faking the lane or using CPU torch. @@ -430,6 +430,7 @@ export ROCKE=$(pwd) PYTHONPATH=$ROCKE/Python ROCKE_LLVM_FLAVOR=llvm20 python tools/check_byte_identity.py # llvm20, build engine + gate ROCKE_LLVM_FLAVOR=llvm22 python tools/check_byte_identity.py # llvm22 flavor ROCKE_LLVM_FLAVOR=llvm23 python tools/check_byte_identity.py # llvm23 flavor +ROCKE_LLVM_FLAVOR=llvm24 python tools/check_byte_identity.py # llvm24 flavor python tools/check_byte_identity.py --only attention # scope to a family ``` diff --git a/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/attention_dense_bwd_ir_sha256.json b/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/attention_dense_bwd_ir_sha256.json index f8c1d9d170f0..ad8a9ddc2aa6 100644 --- a/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/attention_dense_bwd_ir_sha256.json +++ b/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/attention_dense_bwd_ir_sha256.json @@ -1,4 +1,5 @@ { + "aliases": {"llvm24": "llvm23"}, "flavors": { "llvm20": { "cases": { diff --git a/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/attention_dense_gfx942_ir_sha256.json b/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/attention_dense_gfx942_ir_sha256.json index 823e1f2845f8..3bd882d10b2c 100644 --- a/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/attention_dense_gfx942_ir_sha256.json +++ b/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/attention_dense_gfx942_ir_sha256.json @@ -1,4 +1,5 @@ { + "aliases": {"llvm24": "llvm23"}, "flavors": { "llvm20": { "cases": { diff --git a/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/dsa_indexer_ir_sha256.json b/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/dsa_indexer_ir_sha256.json index 97bdbcbbddba..fb7897e49759 100644 --- a/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/dsa_indexer_ir_sha256.json +++ b/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/dsa_indexer_ir_sha256.json @@ -1,4 +1,5 @@ { + "aliases": {"llvm24": "llvm23"}, "arches": { "gfx942": { "flavors": { diff --git a/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/gdn_decode_gfx950_ir_sha256.json b/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/gdn_decode_gfx950_ir_sha256.json index 71600b3090af..8b74175b1771 100644 --- a/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/gdn_decode_gfx950_ir_sha256.json +++ b/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/gdn_decode_gfx950_ir_sha256.json @@ -1,4 +1,5 @@ { + "aliases": {"llvm24": "llvm23"}, "flavors": { "llvm20": { "cases": { diff --git a/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/kda_gfx942_ir_sha256.json b/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/kda_gfx942_ir_sha256.json index 814476b1bf1a..acb9cc9adc9e 100644 --- a/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/kda_gfx942_ir_sha256.json +++ b/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/kda_gfx942_ir_sha256.json @@ -1,4 +1,5 @@ { + "aliases": {"llvm24": "llvm23"}, "flavors": { "llvm20": { "cases": { diff --git a/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/kda_gfx950_ir_sha256.json b/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/kda_gfx950_ir_sha256.json index 912f3bb2c0c2..595bc838ea45 100644 --- a/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/kda_gfx950_ir_sha256.json +++ b/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/kda_gfx950_ir_sha256.json @@ -1,4 +1,5 @@ { + "aliases": {"llvm24": "llvm23"}, "flavors": { "llvm20": { "cases": { diff --git a/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/mla_prefill_gfx942_ir_sha256.json b/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/mla_prefill_gfx942_ir_sha256.json index 0e003e8ff36f..9e7a582a6d08 100644 --- a/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/mla_prefill_gfx942_ir_sha256.json +++ b/dnn-providers/hip-kernel-provider/rocke/library/tests/golden/mla_prefill_gfx942_ir_sha256.json @@ -1,4 +1,5 @@ { + "aliases": {"llvm24": "llvm23"}, "flavors": { "llvm20": { "cases": { diff --git a/dnn-providers/hip-kernel-provider/rocke/library/tests/test_attention_dense_bwd_ir.py b/dnn-providers/hip-kernel-provider/rocke/library/tests/test_attention_dense_bwd_ir.py index 0548485cc8f9..ca955cbd1864 100644 --- a/dnn-providers/hip-kernel-provider/rocke/library/tests/test_attention_dense_bwd_ir.py +++ b/dnn-providers/hip-kernel-provider/rocke/library/tests/test_attention_dense_bwd_ir.py @@ -41,6 +41,13 @@ from pathlib import Path import pytest +from rocke.core.ir_golden import ( + GOLDEN_ALIASES, + GOLDEN_FLAVORS, + GOLDEN_PROFILE_FLAVORS, + golden_subdocument, +) + from ._attention_bwd_test_utils import kernel_signature _TESTS = Path(__file__).resolve().parent @@ -49,7 +56,7 @@ sys.path.insert(0, _LIB_ROOT) _GOLDEN = _TESTS / "golden" / "attention_dense_bwd_ir_sha256.json" -_FLAVORS = ("llvm20", "llvm22", "llvm23") +_FLAVORS = GOLDEN_FLAVORS _ARCHS = ("gfx942", "gfx950") @@ -383,8 +390,12 @@ def _current_flavor(): def _build_doc(): - doc = {"schema": "attention_dense_bwd.ir_golden_sha256/v1", "flavors": {}} - for flavor in _FLAVORS: + doc = { + "schema": "attention_dense_bwd.ir_golden_sha256/v1", + "aliases": GOLDEN_ALIASES, + "flavors": {}, + } + for flavor in GOLDEN_PROFILE_FLAVORS: cases = {} for arch in _ARCHS: for key, over, dq in _golden_rows(arch): @@ -402,7 +413,7 @@ def test_dense_bwd_ir_matches_golden(arch, flavor): if not _GOLDEN.exists(): pytest.fail("dense backward golden fixture missing; generate with --write") golden = json.loads(_GOLDEN.read_text()) - gflav = golden.get("flavors", {}).get(flavor) + gflav = golden_subdocument(golden, flavor) if not gflav: pytest.fail(f"no dense backward golden recorded for llvm flavor {flavor!r}") drift = [] @@ -419,9 +430,16 @@ def test_dense_bwd_ir_matches_golden(arch, flavor): def test_golden_covers_every_case_and_flavor(): golden = json.loads(_GOLDEN.read_text()) + aliases = golden.get("aliases", {}) + direct = golden.get("flavors", {}) + assert aliases == GOLDEN_ALIASES + assert set(direct) == set(GOLDEN_PROFILE_FLAVORS) + assert not set(aliases) & set(direct) want = {key for a in _ARCHS for key, _, _ in _golden_rows(a)} for flavor in _FLAVORS: - got = set(golden["flavors"][flavor]["cases"]) + sub = golden_subdocument(golden, flavor) + assert sub is not None, flavor + got = set(sub["cases"]) assert got == want, flavor diff --git a/dnn-providers/hip-kernel-provider/rocke/library/tests/test_attention_dense_gfx942_golden.py b/dnn-providers/hip-kernel-provider/rocke/library/tests/test_attention_dense_gfx942_golden.py index 1ffa4db96198..0ec21295e4fc 100644 --- a/dnn-providers/hip-kernel-provider/rocke/library/tests/test_attention_dense_gfx942_golden.py +++ b/dnn-providers/hip-kernel-provider/rocke/library/tests/test_attention_dense_gfx942_golden.py @@ -296,11 +296,12 @@ def _run(flavor): def _build_doc(): - from rocke.core.ir_golden import GOLDEN_FLAVORS + from rocke.core.ir_golden import GOLDEN_ALIASES, GOLDEN_PROFILE_FLAVORS return { "schema": "attention_dense_gfx942.ir_golden_sha256/v1", - "flavors": {fl: _run(fl) for fl in GOLDEN_FLAVORS}, + "aliases": GOLDEN_ALIASES, + "flavors": {fl: _run(fl) for fl in GOLDEN_PROFILE_FLAVORS}, } diff --git a/dnn-providers/hip-kernel-provider/rocke/library/tests/test_dsa_indexer_golden.py b/dnn-providers/hip-kernel-provider/rocke/library/tests/test_dsa_indexer_golden.py index 86502c917185..3224d70d4f05 100644 --- a/dnn-providers/hip-kernel-provider/rocke/library/tests/test_dsa_indexer_golden.py +++ b/dnn-providers/hip-kernel-provider/rocke/library/tests/test_dsa_indexer_golden.py @@ -31,13 +31,18 @@ _PLATFORM_PYTHON = _LIBRARY.parent / "platform" / "python" _GOLDEN = _TESTS / "golden" / "dsa_indexer_ir_sha256.json" _SCHEMA = "dsa_indexer.ir_golden_sha256/v1" -_FLAVORS = ("llvm20", "llvm22", "llvm23") _ARCHES = ("gfx942", "gfx950") for _path in (str(_LIBRARY), str(_PLATFORM_PYTHON)): if _path not in sys.path: sys.path.insert(0, _path) +from rocke.core.ir_golden import ( # noqa: E402 + GOLDEN_ALIASES, + GOLDEN_FLAVORS, + GOLDEN_PROFILE_FLAVORS, +) + def _cases() -> dict[str, Callable]: """Representative builders, arch-neutral (the arch is applied at lower time). @@ -91,12 +96,6 @@ def _cases() -> dict[str, Callable]: } -def _current_flavor() -> str: - from rocke.core.lower_llvm import _resolve_llvm_flavor - - return _resolve_llvm_flavor() - - def _sha_for(build: Callable, arch: str, flavor: str) -> tuple[str, int]: from rocke.core.lower_llvm import _lower_kernel_to_llvm_python @@ -109,6 +108,7 @@ def _build_doc() -> dict: cases = _cases() return { "schema": _SCHEMA, + "aliases": GOLDEN_ALIASES, "arches": { arch: { "flavors": { @@ -119,7 +119,7 @@ def _build_doc() -> dict: for sha, nbytes in [_sha_for(build, arch, flavor)] } } - for flavor in _FLAVORS + for flavor in GOLDEN_PROFILE_FLAVORS } } for arch in _ARCHES @@ -127,8 +127,9 @@ def _build_doc() -> dict: } +@pytest.mark.parametrize("flavor", GOLDEN_FLAVORS) @pytest.mark.parametrize("arch", _ARCHES) -def test_dsa_indexer_ir_matches_golden(arch: str): +def test_dsa_indexer_ir_matches_golden(arch: str, flavor: str): assert _GOLDEN.exists(), ( f"missing indexer golden fixture; generate it with " f"`python {Path(__file__).name} --write`" @@ -137,15 +138,17 @@ def test_dsa_indexer_ir_matches_golden(arch: str): assert golden.get("schema") == _SCHEMA assert arch in golden.get("arches", {}), f"no golden recorded for arch {arch!r}" - flavor = _current_flavor() + assert golden.get("aliases", {}) == GOLDEN_ALIASES + golden_flavor = golden.get("aliases", {}).get(flavor, flavor) arch_doc = golden["arches"][arch] - assert flavor in arch_doc.get("flavors", {}), ( + assert set(arch_doc.get("flavors", {})) == set(GOLDEN_PROFILE_FLAVORS) + assert golden_flavor in arch_doc.get("flavors", {}), ( f"no {arch} indexer golden recorded for LLVM flavor {flavor!r}; " "review and re-bless the fixture" ) cases = _cases() - recorded = arch_doc["flavors"][flavor]["cases"] + recorded = arch_doc["flavors"][golden_flavor]["cases"] assert set(recorded) == set(cases), ( f"{arch} indexer golden case set drifted: " f"recorded={sorted(recorded)}, current={sorted(cases)}" @@ -171,5 +174,6 @@ def test_dsa_indexer_ir_matches_golden(arch: str): print(f"wrote {_GOLDEN}") else: for _arch in _ARCHES: - test_dsa_indexer_ir_matches_golden(_arch) + for _flavor in GOLDEN_FLAVORS: + test_dsa_indexer_ir_matches_golden(_arch, _flavor) print("PASS") diff --git a/dnn-providers/hip-kernel-provider/rocke/library/tests/test_gdn_decode_golden.py b/dnn-providers/hip-kernel-provider/rocke/library/tests/test_gdn_decode_golden.py index 2b3fe17135c5..7b281a6e35d0 100644 --- a/dnn-providers/hip-kernel-provider/rocke/library/tests/test_gdn_decode_golden.py +++ b/dnn-providers/hip-kernel-provider/rocke/library/tests/test_gdn_decode_golden.py @@ -375,11 +375,15 @@ def _run(flavor): def _build_doc(): - from rocke.core.ir_golden import GOLDEN_FLAVORS + from rocke.core.ir_golden import GOLDEN_ALIASES, GOLDEN_PROFILE_FLAVORS - doc = {"schema": "gdn_decode_gfx950.ir_golden_sha256/v1", "flavors": {}} + doc = { + "schema": "gdn_decode_gfx950.ir_golden_sha256/v1", + "aliases": GOLDEN_ALIASES, + "flavors": {}, + } failures = [] - for flavor in GOLDEN_FLAVORS: + for flavor in GOLDEN_PROFILE_FLAVORS: cases = {} for cid, build in _cases().items(): try: @@ -424,18 +428,21 @@ def test_gdn_decode_ir_matches_golden(): def test_every_shipped_configuration_is_recorded(): """A new tuned tile must arrive with a golden entry, not silently uncovered.""" import pytest - from rocke.core.ir_golden import GOLDEN_FLAVORS + from rocke.core.ir_golden import GOLDEN_FLAVORS, golden_subdocument if not _GOLDEN.exists(): pytest.skip("gdn_decode golden fixture missing; generate with --write") golden = json.loads(_GOLDEN.read_text()) - flavors = golden.get("flavors", {}) - # A flavor with no sub-document leaves every configuration unrecorded. + # A lane with no direct or aliased profile document leaves every + # configuration unrecorded. missing = sorted( f"{flavor}/{cid}" for flavor in GOLDEN_FLAVORS for cid in _cases() - if not flavors.get(flavor, {}).get("cases", {}).get(cid, {}).get("sha256") + if not (golden_subdocument(golden, flavor) or {}) + .get("cases", {}) + .get(cid, {}) + .get("sha256") ) assert not missing, f"configurations without a SHA-256: {missing}" diff --git a/dnn-providers/hip-kernel-provider/rocke/library/tests/test_kda_gfx942_golden.py b/dnn-providers/hip-kernel-provider/rocke/library/tests/test_kda_gfx942_golden.py index b124ca4bd931..2d0c833cc1b6 100644 --- a/dnn-providers/hip-kernel-provider/rocke/library/tests/test_kda_gfx942_golden.py +++ b/dnn-providers/hip-kernel-provider/rocke/library/tests/test_kda_gfx942_golden.py @@ -84,11 +84,12 @@ def _run(flavor: str) -> dict: def _build_doc() -> dict: - from rocke.core.ir_golden import GOLDEN_FLAVORS + from rocke.core.ir_golden import GOLDEN_ALIASES, GOLDEN_PROFILE_FLAVORS return { "schema": "kda_gfx942.ir_golden_sha256/v1", - "flavors": {flavor: _run(flavor) for flavor in GOLDEN_FLAVORS}, + "aliases": GOLDEN_ALIASES, + "flavors": {flavor: _run(flavor) for flavor in GOLDEN_PROFILE_FLAVORS}, } diff --git a/dnn-providers/hip-kernel-provider/rocke/library/tests/test_kda_gfx950_golden.py b/dnn-providers/hip-kernel-provider/rocke/library/tests/test_kda_gfx950_golden.py index ec9d10191e5f..e7966a65cd0f 100644 --- a/dnn-providers/hip-kernel-provider/rocke/library/tests/test_kda_gfx950_golden.py +++ b/dnn-providers/hip-kernel-provider/rocke/library/tests/test_kda_gfx950_golden.py @@ -216,11 +216,12 @@ def _run(flavor: str) -> dict: def _build_doc() -> dict: - from rocke.core.ir_golden import GOLDEN_FLAVORS + from rocke.core.ir_golden import GOLDEN_ALIASES, GOLDEN_PROFILE_FLAVORS return { "schema": "kda_gfx950.ir_golden_sha256/v1", - "flavors": {flavor: _run(flavor) for flavor in GOLDEN_FLAVORS}, + "aliases": GOLDEN_ALIASES, + "flavors": {flavor: _run(flavor) for flavor in GOLDEN_PROFILE_FLAVORS}, } diff --git a/dnn-providers/hip-kernel-provider/rocke/library/tests/test_mla_prefill_gfx942_golden.py b/dnn-providers/hip-kernel-provider/rocke/library/tests/test_mla_prefill_gfx942_golden.py index 56f47c895447..b0731dba83c3 100644 --- a/dnn-providers/hip-kernel-provider/rocke/library/tests/test_mla_prefill_gfx942_golden.py +++ b/dnn-providers/hip-kernel-provider/rocke/library/tests/test_mla_prefill_gfx942_golden.py @@ -190,11 +190,12 @@ def _run(flavor): def _build_doc(): - from rocke.core.ir_golden import GOLDEN_FLAVORS + from rocke.core.ir_golden import GOLDEN_ALIASES, GOLDEN_PROFILE_FLAVORS return { "schema": _SCHEMA, - "flavors": {fl: _run(fl) for fl in GOLDEN_FLAVORS}, + "aliases": GOLDEN_ALIASES, + "flavors": {fl: _run(fl) for fl in GOLDEN_PROFILE_FLAVORS}, } @@ -215,12 +216,13 @@ def test_mla_prefill_gfx942_golden_covers_every_case(): Without this, a case added to ``_cases()`` but never blessed would be silently skipped rather than failing, and a typo'd cid would pin nothing. """ - from rocke.core.ir_golden import GOLDEN_FLAVORS + from rocke.core.ir_golden import GOLDEN_FLAVORS, golden_subdocument golden = _golden() want = set(_cases()) for flavor in GOLDEN_FLAVORS: - sub = golden["flavors"][flavor] + sub = golden_subdocument(golden, flavor) + assert sub is not None, flavor hashed = set(sub["cases"]) refused = set(sub.get("expected_failures", {})) assert not hashed & refused, f"{flavor}: {sorted(hashed & refused)}" @@ -235,7 +237,7 @@ def test_mla_prefill_gfx942_golden_expected_failures_are_the_llvm20_agpr_refusal """The only refusals the golden may hold are the agpr_acc cases at llvm20; anything else recorded as an expected failure is a failed bless, not a golden.""" - from rocke.core.ir_golden import GOLDEN_FLAVORS + from rocke.core.ir_golden import GOLDEN_FLAVORS, golden_subdocument agpr_cases = { "mla_prefill_gfx942/fwd_h128_agpr", @@ -243,7 +245,9 @@ def test_mla_prefill_gfx942_golden_expected_failures_are_the_llvm20_agpr_refusal } golden = _golden() for flavor in GOLDEN_FLAVORS: - refused = golden["flavors"][flavor].get("expected_failures", {}) + sub = golden_subdocument(golden, flavor) + assert sub is not None, flavor + refused = sub.get("expected_failures", {}) if flavor == "llvm20": assert set(refused) == agpr_cases for cid in agpr_cases: diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/AGENTS.md b/dnn-providers/hip-kernel-provider/rocke/platform/AGENTS.md index e6f4660cb301..e53b7af39bb6 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/AGENTS.md +++ b/dnn-providers/hip-kernel-provider/rocke/platform/AGENTS.md @@ -118,11 +118,12 @@ change must be made in **both** engines in the same change. Prove it: ROCKE_LLVM_FLAVOR=llvm20 python tools/check_byte_identity.py # build engine fresh + gate ROCKE_LLVM_FLAVOR=llvm22 python tools/check_byte_identity.py # and llvm22 ROCKE_LLVM_FLAVOR=llvm23 python tools/check_byte_identity.py # and llvm23 +ROCKE_LLVM_FLAVOR=llvm24 python tools/check_byte_identity.py # and llvm24 ``` A change is done only when the gate is GREEN for every family at every flavor. The llvm20 and llvm22 runs also re-run the `gfx1250_lowering` family at llvm23, -because its gfx1250-only ops lower at no other flavor. +because its gfx1250-only ops need the LLVM23-generation emission profile. ## Build / test / run @@ -481,7 +482,7 @@ dual-engine vs Python-only split. | `ROCKE_BACKEND` | `cpp` (default) \| `python` \| `both` (differential assert) | | `ROCKE_CPP_STRICT` | `1` = raise instead of silently falling back to Python when `rocke_engine` isn't built | | `ROCKE_DEBUG_LOC` | `1` = capture Python source locations while building and emit DWARF, so ATT traces map to source; off by default because it changes the emitted `.ll` | -| `ROCKE_LLVM_FLAVOR` | `llvm20` \| `llvm22` \| `llvm23` (AUTO queries the loaded COMGR compiler: LLVM <=20, 21/22, >=23; unavailable evidence raises; explicit flavors support offline emission) | +| `ROCKE_LLVM_FLAVOR` | `llvm20` \| `llvm22` \| `llvm23` \| `llvm24` (AUTO queries loaded COMGR: LLVM <=20, 21/22, 23, or 24; newer majors and unavailable evidence raise; explicit lanes support offline emission) | | `ROCKE_TEST_VERIFY_IR` | `1` = assemble emitted IR with `llvm-as` in `TestNewTargetIntrinsics`; needs an LLVM as new as the newest flavor | | `ROCM_PATH` / `ROCM_HOME` | ROCm install root; `/lib` is searched for `comgr`/HIP before the globbed `/opt/rocm*` trees | | `ROCKE_COMGR_LIB` / `ROCKE_HIP_LIB` | explicit full path to `libamd_comgr` / `libamdhip64`; wins over all discovery | diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/CMakeLists.txt b/dnn-providers/hip-kernel-provider/rocke/platform/CMakeLists.txt index 119785823c8d..792c911f01cf 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/CMakeLists.txt +++ b/dnn-providers/hip-kernel-provider/rocke/platform/CMakeLists.txt @@ -531,7 +531,7 @@ if(ROCKE_INSTALL_TESTS) # checks all of them) and canonical IR. tests/instances/differential/golden/README.md. set(_ROCKE_RUN_DIFF "${ROCKE_TEST_CTEST_REL}tests/instances/differential/run_diff.py") string(APPEND _ROCKE_INSTALLED_CTEST_ENTRIES - "add_test(rocke_differential_golden_ll python \"${_ROCKE_RUN_DIFF}\" --mode ll --python-only --check-golden --flavor llvm20,llvm22,llvm23)\n") + "add_test(rocke_differential_golden_ll python \"${_ROCKE_RUN_DIFF}\" --mode ll --python-only --check-golden --flavor llvm20,llvm22,llvm23,llvm24)\n") string(APPEND _ROCKE_INSTALLED_CTEST_ENTRIES "set_tests_properties(rocke_differential_golden_ll PROPERTIES LABELS \"ckc;python;golden;host;quick\" ENVIRONMENT \"PYTHONPATH=${_ROCKE_INSTALLED_PYTHONPATH}\" TIMEOUT 300)\n") string(APPEND _ROCKE_INSTALLED_CTEST_ENTRIES diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/bindings/rocke_engine.cpp b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/bindings/rocke_engine.cpp index 57cff5bf71f9..cf649c3be221 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/bindings/rocke_engine.cpp +++ b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/bindings/rocke_engine.cpp @@ -4070,7 +4070,7 @@ std::vector gfx1201_wmma_gemm_verify(const py::dict& d, const std:: * the engine's extern "C" boundary never aborts/terminates. * ------------------------------------------------------------------------ */ -/* "'llvm20', 'llvm22', 'llvm23'" -- built from the engine's flavor ladder so +/* Canonical concrete flavor names -- built from the engine's ladder so * the message cannot drift from what from_name() actually accepts. */ static std::string rocke_engine_flavor_list() { @@ -4138,7 +4138,7 @@ std::string lower_serialized_ir(const std::string& ir_text, fl = rocke_llvm_flavor_from_name(flavor.c_str()); if(fl == ROCKE_LLVM_FLAVOR_AUTO) { - throw std::runtime_error( + throw pybind11::value_error( std::string("rocke_engine.lower_serialized_ir: unknown LLVM flavor '") + flavor + "' (expected one of " + rocke_engine_flavor_list() + ")"); } diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/arch/domain.cpp b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/arch/domain.cpp index da17c8d603c1..53528274c903 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/arch/domain.cpp +++ b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/arch/domain.cpp @@ -27,12 +27,21 @@ struct column_t size_t count; }; -/* Defines ROCKE_ARCH_DOMAIN_DEFAULT_MODE, the per-flavor cell arrays and - * ROCKE_ARCH_DOMAIN_COLUMNS. Generated into the build tree; never edit or +/* A lane with no column of its own that enforces another lane's column + * (domain.COLUMN_ALIASES). */ +struct column_alias_t +{ + const char* flavor; + const char* column; +}; + +/* Defines ROCKE_ARCH_DOMAIN_DEFAULT_MODE, the per-flavor cell arrays, + * ROCKE_ARCH_DOMAIN_COLUMNS and the nullptr-terminated + * ROCKE_ARCH_DOMAIN_ALIASES. Generated into the build tree; never edit or * commit it. */ #include "rocke/arch_domain_table.inc" -const column_t* find_column(const char* flavor) +const column_t* find_exact(const char* flavor) { for(const column_t& c : ROCKE_ARCH_DOMAIN_COLUMNS) { @@ -44,6 +53,23 @@ const column_t* find_column(const char* flavor) return nullptr; } +/* Python: domain.load() -- the flavor's own column, else its alias's. */ +const column_t* find_column(const char* flavor) +{ + if(const column_t* own = find_exact(flavor)) + { + return own; + } + for(const column_alias_t* alias = ROCKE_ARCH_DOMAIN_ALIASES; alias->flavor != nullptr; ++alias) + { + if(strcmp(alias->flavor, flavor) == 0) + { + return find_exact(alias->column); + } + } + return nullptr; +} + /* Orders cells as the generator sorts them: by key, then arch, both compared * byte-wise -- which is Python's str ordering because both are ASCII. */ int compare(const rocke_arch_domain_cell_t& cell, const char* key, const char* arch) @@ -104,6 +130,12 @@ extern "C" const rocke_arch_domain_cell_t* rocke_arch_domain_column(const char* return col != nullptr && col->count != 0 ? col->cells : nullptr; } +extern "C" const char* rocke_arch_domain_column_flavor(const char* flavor) +{ + const column_t* col = flavor != nullptr ? find_column(flavor) : nullptr; + return col != nullptr ? col->flavor : flavor; +} + extern "C" const char* rocke_arch_domain_default_mode(void) { return ROCKE_ARCH_DOMAIN_DEFAULT_MODE; diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/ir/ir_tile.cpp b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/ir/ir_tile.cpp index 91729a102ec9..69db966c597e 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/ir/ir_tile.cpp +++ b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/ir/ir_tile.cpp @@ -994,7 +994,7 @@ static void rocke_b_gfx1250_scalar_control(rocke_ir_builder_t* b, const char* mn if(!op) return; rocke_attr_set_str(b, &op->attrs, "required_arch", "gfx1250"); - rocke_attr_set_str(b, &op->attrs, "required_llvm_flavor", "llvm23"); + rocke_attr_set_str(b, &op->attrs, "minimum_llvm_flavor", "llvm23"); } void rocke_b_s_delay_alu(rocke_ir_builder_t* b, int imm) diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/isa/backend.cpp b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/isa/backend.cpp index 97a682b3b59c..d7aa39d7bb57 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/isa/backend.cpp +++ b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/isa/backend.cpp @@ -12,42 +12,7 @@ #include -/* The shared LLVM constants are owned by lower_llvm in Python (pulled lazily to - * avoid an import cycle). In C there is no cycle: we hold the canonical strings - * here as static data, byte-identical to lower_llvm._TRIPLE / _DATALAYOUT. When - * the lower_llvm port lands, these may be moved there and referenced; until - * then this is the single C-side source. */ -static const char ROCKE_TRIPLE[] = "amdgcn-amd-amdhsa"; -/* The AMDGPU datalayout is FLAVOR-KEYED (Python _DATALAYOUT_LLVM20 / - * _DATALAYOUT_LLVM22 / _DATALAYOUT_LLVM23): two fields drift across flavors -- - * the buffer-resource address space p8 (the 128-bit buffer descriptor, not the - * p7 fat pointer) gained an index-width field in LLVM 22 (...-p8:128:128-... -> - * ...-p8:128:128:128:48-...), and the ELF symbol-mangling spec m:e (absent in - * LLVM 20 / 22) is present in LLVM 23 (ROCm 7.13+): e-p:64:64-... -> - * e-m:e-p:64:64-.... The triple is unchanged across flavors. Must stay - * byte-identical with the Python constants. */ -static const char ROCKE_DATALAYOUT_LLVM20[] - = "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32" - "-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16-v24:32-v32:32" - "-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048" - "-n32:64-S32-A5-G1-ni:7:8:9"; -static const char ROCKE_DATALAYOUT_LLVM22[] - = "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32" - "-p7:160:256:256:32-p8:128:128:128:48-p9:192:256:256:32-i64:64-v16:16-v24:32" - "-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048" - "-n32:64-S32-A5-G1-ni:7:8:9"; -/* Layout emitted for rocKE's llvm23 flavor: the llvm22 layout plus the ELF - * symbol-mangling spec m:e and address spaces p10-p15 (upstream 5bf967cb132b). - * Older compiler builds may omit p10-p15; see Python _DATALAYOUT_LLVM23 for the - * full rationale. Must stay byte-identical with it. Kept as its own constant - * rather than folded into the `else` arm below so the next divergence is a - * one-line edit, not a silent wrong-datalayout bug. */ -static const char ROCKE_DATALAYOUT_LLVM23[] - = "e-m:e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32" - "-p7:160:256:256:32-p8:128:128:128:48-p9:192:256:256:32-p10:32:32-p11:32:32" - "-p12:32:32-p13:32:32-p14:32:32-p15:32:32-i64:64-v16:16-v24:32" - "-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048" - "-n32:64-S32-A5-G1-ni:7:8:9"; +#include "rocke/llvm_profile_internal.h" /* ================================ registry ============================== */ @@ -158,23 +123,17 @@ bool rocke_backend_is_known(const char* gfx) const char* rocke_isa_triple(const rocke_isa_backend_t* be) { (void)be; /* shared across all wired targets */ - return ROCKE_TRIPLE; + return ckc::ROCKE_LL_TRIPLE; } -/* Python backend.datalayout(llvm_flavor) -> _datalayout_for_flavor, branch for - * branch: LLVM20 gets the legacy p8 layout, LLVM23 its own m:e constant, and - * anything else -- including an unexpected value -- the modern LLVM22 form. - * Mirrors rocke_ll_datalayout_for_flavor in lower_llvm/data.cpp; - * the two are held together by test_isa_and_lower_llvm_datalayouts_agree. */ +/* Python backend.datalayout(llvm_flavor) -> _datalayout_for_flavor. The ISA + * adapter delegates to the shared profile resolver; an unknown lane returns + * NULL rather than silently choosing a structural profile. */ const char* rocke_isa_datalayout_for_flavor(const rocke_isa_backend_t* be, rocke_llvm_flavor_t flavor) { - (void)be; /* shared across all wired targets; only the flavor drives p8 */ - if(flavor == ROCKE_LLVM_FLAVOR_LLVM20) - return ROCKE_DATALAYOUT_LLVM20; - if(flavor == ROCKE_LLVM_FLAVOR_LLVM23) - return ROCKE_DATALAYOUT_LLVM23; - return ROCKE_DATALAYOUT_LLVM22; + (void)be; /* shared across all wired targets; only the profile drives it */ + return ckc::rocke_ll_datalayout_for_flavor(flavor); } const char* rocke_isa_datalayout(const rocke_isa_backend_t* be) @@ -195,9 +154,14 @@ int rocke_isa_module_preamble_for_flavor(const rocke_isa_backend_t* be, return -1; } rocke_strbuf_clear(out); + const char* datalayout = rocke_isa_datalayout_for_flavor(be, flavor); + if(datalayout == NULL) + { + return -1; + } if(rocke_strbuf_appendf(out, "target datalayout = \"%s\"\ntarget triple = \"%s\"", - rocke_isa_datalayout_for_flavor(be, flavor), + datalayout, rocke_isa_triple(be)) != 0) { diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/llvm_profile.cpp b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/llvm_profile.cpp new file mode 100644 index 000000000000..f155c19f3788 --- /dev/null +++ b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/llvm_profile.cpp @@ -0,0 +1,201 @@ +// Copyright (c) Advanced Micro Devices, Inc., or its affiliates. +// SPDX-License-Identifier: MIT +/* + * llvm_profile.cpp -- native compiler-lane and structural LLVM emission-profile registry. + * This neutral layer is shared by the LLVM lowerer and ISA adapter. + */ +#include "rocke/llvm_profile_internal.h" + +#include +#include + +#include "rocke/error.hpp" + +namespace +{ + +static const ckc::rocke_ll_emission_profile_t ROCKE_LL_PROFILE_LLVM20 + = {ckc::ROCKE_LL_DATALAYOUT_PROFILE_LLVM20, ckc::ROCKE_LL_DECLARATION_ABI_LLVM20, 0}; +static const ckc::rocke_ll_emission_profile_t ROCKE_LL_PROFILE_LLVM22 + = {ckc::ROCKE_LL_DATALAYOUT_PROFILE_LLVM22, ckc::ROCKE_LL_DECLARATION_ABI_LLVM22, 0}; +static const ckc::rocke_ll_emission_profile_t ROCKE_LL_PROFILE_LLVM23 + = {ckc::ROCKE_LL_DATALAYOUT_PROFILE_LLVM23, + ckc::ROCKE_LL_DECLARATION_ABI_LLVM23, + ckc::ROCKE_LL_CAP_LLVM23_TARGET_OPS}; + +static const struct +{ + rocke_llvm_flavor_t flavor; + const char* name; + unsigned min_llvm_major; + const ckc::rocke_ll_emission_profile_t* profile; +} ROCKE_LL_FLAVOR_LADDER[] = { + {ROCKE_LLVM_FLAVOR_LLVM20, "llvm20", 0, &ROCKE_LL_PROFILE_LLVM20}, + {ROCKE_LLVM_FLAVOR_LLVM22, "llvm22", 21, &ROCKE_LL_PROFILE_LLVM22}, + {ROCKE_LLVM_FLAVOR_LLVM23, "llvm23", 23, &ROCKE_LL_PROFILE_LLVM23}, + {ROCKE_LLVM_FLAVOR_LLVM24, "llvm24", 24, &ROCKE_LL_PROFILE_LLVM23}, +}; + +static const int ROCKE_LL_FLAVOR_LADDER_COUNT + = (int)(sizeof(ROCKE_LL_FLAVOR_LADDER) / sizeof(ROCKE_LL_FLAVOR_LADDER[0])); + +} // namespace + +int rocke_llvm_flavor_count(void) +{ + return ROCKE_LL_FLAVOR_LADDER_COUNT; +} + +const char* rocke_llvm_flavor_at(int index) +{ + if(index < 0 || index >= ROCKE_LL_FLAVOR_LADDER_COUNT) + return ""; + return ROCKE_LL_FLAVOR_LADDER[index].name; +} + +const char* rocke_llvm_flavor_name(rocke_llvm_flavor_t flavor) +{ + for(int i = 0; i < ROCKE_LL_FLAVOR_LADDER_COUNT; ++i) + { + if(ROCKE_LL_FLAVOR_LADDER[i].flavor == flavor) + return ROCKE_LL_FLAVOR_LADDER[i].name; + } + return ""; +} + +rocke_llvm_flavor_t rocke_llvm_flavor_from_name(const char* name) +{ + if(name) + { + for(int i = 0; i < ROCKE_LL_FLAVOR_LADDER_COUNT; ++i) + { + if(std::strcmp(name, ROCKE_LL_FLAVOR_LADDER[i].name) == 0) + return ROCKE_LL_FLAVOR_LADDER[i].flavor; + } + } + return ROCKE_LLVM_FLAVOR_AUTO; +} + +bool rocke_llvm_flavor_is_known(rocke_llvm_flavor_t flavor) +{ + for(int i = 0; i < ROCKE_LL_FLAVOR_LADDER_COUNT; ++i) + { + if(ROCKE_LL_FLAVOR_LADDER[i].flavor == flavor) + return true; + } + return false; +} + +namespace ckc +{ + +const rocke_ll_emission_profile_t* rocke_ll_emission_profile(rocke_llvm_flavor_t flavor) +{ + for(int i = 0; i < ROCKE_LL_FLAVOR_LADDER_COUNT; ++i) + { + if(ROCKE_LL_FLAVOR_LADDER[i].flavor == flavor) + return ROCKE_LL_FLAVOR_LADDER[i].profile; + } + return NULL; +} + +bool rocke_ll_profile_has(rocke_llvm_flavor_t flavor, rocke_ll_emission_capability_t capability) +{ + const rocke_ll_emission_profile_t* profile = rocke_ll_emission_profile(flavor); + return profile && (profile->capabilities & (unsigned)capability) != 0; +} + +bool rocke_ll_flavor_is_modern(rocke_llvm_flavor_t flavor) +{ + const rocke_ll_emission_profile_t* profile = rocke_ll_emission_profile(flavor); + return profile && profile->datalayout != ROCKE_LL_DATALAYOUT_PROFILE_LLVM20; +} + +bool rocke_ll_flavor_at_least(rocke_llvm_flavor_t flavor, rocke_llvm_flavor_t required) +{ + int flavor_rank = -1; + int required_rank = -1; + for(int i = 0; i < ROCKE_LL_FLAVOR_LADDER_COUNT; ++i) + { + if(ROCKE_LL_FLAVOR_LADDER[i].flavor == flavor) + flavor_rank = i; + if(ROCKE_LL_FLAVOR_LADDER[i].flavor == required) + required_rank = i; + } + return flavor_rank >= 0 && required_rank >= 0 && flavor_rank >= required_rank; +} + +rocke_llvm_flavor_t rocke_ll_explicit_flavor(const char* value) +{ + if(!value || value[0] == '\0') + return ROCKE_LLVM_FLAVOR_AUTO; + rocke_llvm_flavor_t flavor = rocke_llvm_flavor_from_name(value); + if(flavor == ROCKE_LLVM_FLAVOR_AUTO) + { + std::string expected = "("; + for(int i = 0; i < ROCKE_LL_FLAVOR_LADDER_COUNT; ++i) + { + if(i) + expected += ", "; + expected += "'" + std::string(ROCKE_LL_FLAVOR_LADDER[i].name) + "'"; + } + expected += ")"; + throw ckc::ValueError("ROCKE_LLVM_FLAVOR='" + std::string(value) + + "' is not a recognized flavor; expected one of " + expected); + } + return flavor; +} + +rocke_llvm_flavor_t rocke_ll_flavor_for_llvm_major(unsigned major) +{ + const int latest = ROCKE_LL_FLAVOR_LADDER_COUNT - 1; + if(major > ROCKE_LL_FLAVOR_LADDER[latest].min_llvm_major) + { + throw ckc::ValueError( + ckc::format_error("LLVM compiler major %u is newer than the latest qualified lane %s", + major, + ROCKE_LL_FLAVOR_LADDER[latest].name)); + } + for(int i = latest; i >= 0; --i) + { + if(major >= ROCKE_LL_FLAVOR_LADDER[i].min_llvm_major) + return ROCKE_LL_FLAVOR_LADDER[i].flavor; + } + return ROCKE_LLVM_FLAVOR_LLVM20; +} + +const char* const ROCKE_LL_DATALAYOUT_LLVM20 + = "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32" + "-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16-v24:32-v32:32" + "-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048" + "-n32:64-S32-A5-G1-ni:7:8:9"; + +const char* const ROCKE_LL_DATALAYOUT_LLVM22 + = "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32" + "-p7:160:256:256:32-p8:128:128:128:48-p9:192:256:256:32-i64:64-v16:16-v24:32" + "-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048" + "-n32:64-S32-A5-G1-ni:7:8:9"; + +const char* const ROCKE_LL_DATALAYOUT_LLVM23 + = "e-m:e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32" + "-p7:160:256:256:32-p8:128:128:128:48-p9:192:256:256:32-p10:32:32-p11:32:32" + "-p12:32:32-p13:32:32-p14:32:32-p15:32:32-i64:64-v16:16-v24:32" + "-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048" + "-n32:64-S32-A5-G1-ni:7:8:9"; + +const char* const ROCKE_LL_DATALAYOUT = ROCKE_LL_DATALAYOUT_LLVM20; +const char* const ROCKE_LL_TRIPLE = "amdgcn-amd-amdhsa"; + +const char* rocke_ll_datalayout_for_flavor(rocke_llvm_flavor_t flavor) +{ + const rocke_ll_emission_profile_t* profile = rocke_ll_emission_profile(flavor); + if(!profile) + return NULL; + if(profile->datalayout == ROCKE_LL_DATALAYOUT_PROFILE_LLVM20) + return ROCKE_LL_DATALAYOUT_LLVM20; + if(profile->datalayout == ROCKE_LL_DATALAYOUT_PROFILE_LLVM23) + return ROCKE_LL_DATALAYOUT_LLVM23; + return ROCKE_LL_DATALAYOUT_LLVM22; +} + +} // namespace ckc diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/lower_llvm/core.cpp b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/lower_llvm/core.cpp index 6bc1be2125c0..2cf9abaf02ff 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/lower_llvm/core.cpp +++ b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/lower_llvm/core.cpp @@ -36,127 +36,26 @@ #include #include -/* ====================================================================== */ -/* Flavor ladder -- the single source for the C++ side */ -/* ====================================================================== */ - -/* One rung: the flavor, its canonical name, and its minimum LLVM major. - * Mirrors the Python LLVM_FLAVORS tuple and _LLVM_FLAVOR_LADDER, which - * are a single source enforced by test_no_hand_rolled_flavor_membership_lists. - * Everything on this side that names, parses, validates, enumerates, or - * version-maps a flavor reads this table, so adding a rung is one row here - * plus the enumerator in lower_llvm.h -- previously it was five coordinated - * edits across three files, which is exactly the drift the Python lint bans. - * - * Ordered oldest first to match LLVM_FLAVORS, so error messages listing the - * set read the same in both engines. */ -static const struct -{ - rocke_llvm_flavor_t flavor; - const char* name; - unsigned min_llvm_major; - /* Datalayout generation: false = the LLVM20 plain-p8 shape, true = the - * LLVM21+ indexed-p8 shape. Python's _DATALAYOUT_KIND_FLAVORS partition, - * as a column. */ - bool modern; -} ROCKE_LL_FLAVOR_LADDER[] = { - {ROCKE_LLVM_FLAVOR_LLVM20, "llvm20", 0, false}, - {ROCKE_LLVM_FLAVOR_LLVM22, "llvm22", 21, true}, - {ROCKE_LLVM_FLAVOR_LLVM23, "llvm23", 23, true}, -}; - -static const int ROCKE_LL_FLAVOR_LADDER_COUNT - = (int)(sizeof(ROCKE_LL_FLAVOR_LADDER) / sizeof(ROCKE_LL_FLAVOR_LADDER[0])); - -int rocke_llvm_flavor_count(void) -{ - return ROCKE_LL_FLAVOR_LADDER_COUNT; -} - -const char* rocke_llvm_flavor_at(int index) -{ - if(index < 0 || index >= ROCKE_LL_FLAVOR_LADDER_COUNT) - return ""; - return ROCKE_LL_FLAVOR_LADDER[index].name; -} - -const char* rocke_llvm_flavor_name(rocke_llvm_flavor_t flavor) -{ - int i; - for(i = 0; i < ROCKE_LL_FLAVOR_LADDER_COUNT; ++i) - { - if(ROCKE_LL_FLAVOR_LADDER[i].flavor == flavor) - return ROCKE_LL_FLAVOR_LADDER[i].name; - } - return ""; /* AUTO, or a value outside the enum */ -} - -rocke_llvm_flavor_t rocke_llvm_flavor_from_name(const char* name) -{ - int i; - if(name) - { - for(i = 0; i < ROCKE_LL_FLAVOR_LADDER_COUNT; ++i) - { - if(strcmp(name, ROCKE_LL_FLAVOR_LADDER[i].name) == 0) - return ROCKE_LL_FLAVOR_LADDER[i].flavor; - } - } - return ROCKE_LLVM_FLAVOR_AUTO; -} - -bool rocke_llvm_flavor_is_known(rocke_llvm_flavor_t flavor) -{ - int i; - for(i = 0; i < ROCKE_LL_FLAVOR_LADDER_COUNT; ++i) - { - if(ROCKE_LL_FLAVOR_LADDER[i].flavor == flavor) - return true; - } - return false; -} - -/* The lowerer's private symbols live in namespace ckc; the public entry points - * (rocke_llvm_flavor_name/from_name above, rocke_lower_kernel_to_llvm[_ex] below) - * stay at global scope under their extern "C" header declarations. */ +/* The lowerer's private symbols live in namespace ckc; public entry points stay + * at global scope under their extern "C" header declarations. */ namespace ckc { -bool rocke_ll_flavor_is_modern(rocke_llvm_flavor_t flavor) -{ - int i; - for(i = 0; i < ROCKE_LL_FLAVOR_LADDER_COUNT; ++i) - { - if(ROCKE_LL_FLAVOR_LADDER[i].flavor == flavor) - return ROCKE_LL_FLAVOR_LADDER[i].modern; - } - return false; /* AUTO / out of range: the legacy shape, as before */ -} - /* Resolve from the compiler loaded by COMGR. Explicit flavors keep offline * emission independent of a runtime installation. If no compiler can be * queried, reject AUTO; offline callers must supply an explicit flavor. * Python-driven C++ lowering passes its resolved flavor explicitly. */ static rocke_llvm_flavor_t ll_resolve_flavor(void) { - const char* env = getenv("ROCKE_LLVM_FLAVOR"); - if(env) - { - rocke_llvm_flavor_t flavor = rocke_llvm_flavor_from_name(env); - if(flavor != ROCKE_LLVM_FLAVOR_AUTO) - return flavor; - } + rocke_llvm_flavor_t explicit_flavor = rocke_ll_explicit_flavor(getenv("ROCKE_LLVM_FLAVOR")); + if(explicit_flavor != ROCKE_LLVM_FLAVOR_AUTO) + return explicit_flavor; const ckc::CompilerInfo* info = ckc::candidate_compiler_info(); if(!info || !info->llvm_major) throw ckc::ValueError( "Cannot determine LLVM flavor: COMGR could not be loaded or queried. " "Select a queryable COMGR library or an explicit LLVM flavor for offline IR emission."); - for(int i = ROCKE_LL_FLAVOR_LADDER_COUNT - 1; i >= 0; --i) - { - if(info->llvm_major >= ROCKE_LL_FLAVOR_LADDER[i].min_llvm_major) - return ROCKE_LL_FLAVOR_LADDER[i].flavor; - } - return ROCKE_LLVM_FLAVOR_LLVM20; + return rocke_ll_flavor_for_llvm_major(info->llvm_major); } /* ====================================================================== */ @@ -371,7 +270,7 @@ void rocke_ll_require_llvm23_target_fact(rocke_lower_t* L, ll_target_fact_name(fact), gfx ? gfx : "(unknown)"); } - if(L->flavor != ROCKE_LLVM_FLAVOR_LLVM23) + if(!rocke_ll_profile_has(L->flavor, ROCKE_LL_CAP_LLVM23_TARGET_OPS)) { rocke_ll_fail(L, ROCKE_ERR_VALUE, @@ -608,7 +507,7 @@ static void ll_check_arch_domain(rocke_lower_t* L, const char* key) return; } char msg[ROCKE_ERR_MSG_CAP]; - const char* flavor = rocke_llvm_flavor_name(L->flavor); + const char* flavor = rocke_arch_domain_column_flavor(rocke_llvm_flavor_name(L->flavor)); const rocke_arch_domain_cell_t* cell = rocke_arch_domain_negative(flavor, key, L->backend->gfx); if(cell == NULL || cell->waived) { diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/lower_llvm/crosslane.cpp b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/lower_llvm/crosslane.cpp index 47305f88f8aa..2ed2abbc7525 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/lower_llvm/crosslane.cpp +++ b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/lower_llvm/crosslane.cpp @@ -999,6 +999,16 @@ static void _op_tile_inline_asm(rocke_lower_t* L, const rocke_op_t* op) const char* required_arch = rocke_attr_get_str(&op->attrs, "required_arch"); const char* required_flavor = rocke_attr_get_str(&op->attrs, "required_llvm_flavor"); + const rocke_attr_value_t* minimum_flavor_attr + = rocke_attr_get(&op->attrs, "minimum_llvm_flavor"); + if(minimum_flavor_attr != NULL && minimum_flavor_attr->kind != ROCKE_ATTR_STR) + { + rocke_ll_fail(L, + ROCKE_ERR_TYPE, + "tile.inline_asm failed - minimum_llvm_flavor has a non-string value, " + "expected a string"); + } + const char* minimum_flavor = minimum_flavor_attr != NULL ? minimum_flavor_attr->u.s : NULL; if(required_arch && (!L->backend || !L->backend->gfx || strcmp(L->backend->gfx, required_arch) != 0)) { @@ -1016,6 +1026,18 @@ static void _op_tile_inline_asm(rocke_lower_t* L, const rocke_op_t* op) required_flavor, rocke_llvm_flavor_name(L->flavor)); } + if(minimum_flavor) + { + rocke_llvm_flavor_t minimum = rocke_llvm_flavor_from_name(minimum_flavor); + if(minimum == ROCKE_LLVM_FLAVOR_AUTO || !rocke_ll_flavor_at_least(L->flavor, minimum)) + { + rocke_ll_fail(L, + ROCKE_ERR_VALUE, + "tile.inline_asm requires LLVM flavor %s, got %s", + minimum_flavor, + rocke_llvm_flavor_name(L->flavor)); + } + } raw_template = rocke_attr_get_str(&op->attrs, "template"); if(raw_template == NULL) { diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/lower_llvm/data.cpp b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/lower_llvm/data.cpp index 471f38b4ba32..fc8412799116 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/lower_llvm/data.cpp +++ b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/lower_llvm/data.cpp @@ -5,7 +5,6 @@ * rocke.core.lower_llvm. Defines the externs declared in * rocke/lower_llvm_internal.h: * - * - ROCKE_LL_DATALAYOUT / ROCKE_LL_TRIPLE (Python _DATALAYOUT / _TRIPLE) * - ROCKE_LL_INTRINSIC_DECLS[] (+ _COUNT) (Python _INTRINSIC_DECLS) * - ROCKE_LL_INTRINSIC_DECLS_LLVM22_OVERRIDES[] (+ _COUNT) * (Python ..._LLVM22_OVERRIDES) @@ -26,63 +25,6 @@ namespace ckc { -/* ---------------------------------------------------------------------- */ -/* datalayout / triple (Python _DATALAYOUT_LLVM20 / _DATALAYOUT_LLVM22 / */ -/* _DATALAYOUT_LLVM23 / _TRIPLE). The AMDGPU datalayout is FLAVOR-KEYED: */ -/* two fields drift across LLVM flavors: */ -/* * buffer-resource address space (p8, the 128-bit buffer descriptor -- */ -/* NOT the p7 fat pointer) gained an index-width field: */ -/* LLVM 20 (ROCm 7.0/7.1): e-...-p8:128:128-... */ -/* LLVM 22 (ROCm 7.2): e-...-p8:128:128:128:48-... */ -/* * ELF symbol-mangling spec (m:e): absent in LLVM 20 and LLVM 22, */ -/* present in LLVM 23 (ROCm 7.13+, AMD clang 23.0.0git): */ -/* LLVM 20 / 22: e-p:64:64-... */ -/* LLVM 23: e-m:e-p:64:64-... */ -/* Pick via rocke_ll_datalayout_for_flavor, mirroring _datalayout_for_flavor.*/ -/* ---------------------------------------------------------------------- */ - -const char* const ROCKE_LL_DATALAYOUT_LLVM20 - = "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32" - "-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16-v24:32-v32:32" - "-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048" - "-n32:64-S32-A5-G1-ni:7:8:9"; - -const char* const ROCKE_LL_DATALAYOUT_LLVM22 - = "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32" - "-p7:160:256:256:32-p8:128:128:128:48-p9:192:256:256:32-i64:64-v16:16-v24:32" - "-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048" - "-n32:64-S32-A5-G1-ni:7:8:9"; - -/* Layout emitted for rocKE's llvm23 flavor: the llvm22 layout plus the ELF - * symbol-mangling spec m:e and address spaces p10-p15 (upstream 5bf967cb132b). - * Older compiler builds may omit p10-p15; see Python _DATALAYOUT_LLVM23 for the - * full rationale. Must stay byte-identical with it. */ -const char* const ROCKE_LL_DATALAYOUT_LLVM23 - = "e-m:e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32" - "-p7:160:256:256:32-p8:128:128:128:48-p9:192:256:256:32-p10:32:32-p11:32:32" - "-p12:32:32-p13:32:32-p14:32:32-p15:32:32-i64:64-v16:16-v24:32" - "-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048" - "-n32:64-S32-A5-G1-ni:7:8:9"; - -/* Back-compat alias: callers that have not yet been flavor-threaded see the - * LLVM20 form (the historical hardcoded value). New code keys on the flavor - * via rocke_ll_datalayout_for_flavor / rocke_isa_datalayout. */ -const char* const ROCKE_LL_DATALAYOUT = ROCKE_LL_DATALAYOUT_LLVM20; - -const char* const ROCKE_LL_TRIPLE = "amdgcn-amd-amdhsa"; - -/* Python _datalayout_for_flavor: LLVM20 returns the legacy p8 layout, LLVM23 - * returns its own m:e form, and anything else (incl. an unexpected value) - * degrades to the modern LLVM22 form. */ -const char* rocke_ll_datalayout_for_flavor(rocke_llvm_flavor_t flavor) -{ - if(flavor == ROCKE_LLVM_FLAVOR_LLVM20) - return ROCKE_LL_DATALAYOUT_LLVM20; - if(flavor == ROCKE_LLVM_FLAVOR_LLVM23) - return ROCKE_LL_DATALAYOUT_LLVM23; - return ROCKE_LL_DATALAYOUT_LLVM22; -} - /* ---------------------------------------------------------------------- */ /* The base (LLVM20) intrinsic-declaration table (Python _INTRINSIC_DECLS) */ /* Insertion order preserved. */ @@ -572,13 +514,14 @@ const int ROCKE_LL_INTRINSIC_DECLS_LLVM23_OVERRIDES_COUNT * mirroring the Python _Lowerer choosing which OVERRIDES dict to .update(). */ const rocke_ll_decl_t* rocke_ll_flavor_overrides(rocke_llvm_flavor_t flavor, int* out_count) { - if(flavor == ROCKE_LLVM_FLAVOR_LLVM22) + const rocke_ll_emission_profile_t* profile = rocke_ll_emission_profile(flavor); + if(profile && profile->declarations == ROCKE_LL_DECLARATION_ABI_LLVM22) { if(out_count) *out_count = ROCKE_LL_INTRINSIC_DECLS_LLVM22_OVERRIDES_COUNT; return ROCKE_LL_INTRINSIC_DECLS_LLVM22_OVERRIDES; } - if(flavor == ROCKE_LLVM_FLAVOR_LLVM23) + if(profile && profile->declarations == ROCKE_LL_DECLARATION_ABI_LLVM23) { if(out_count) *out_count = ROCKE_LL_INTRINSIC_DECLS_LLVM23_OVERRIDES_COUNT; diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/lower_llvm/mma.cpp b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/lower_llvm/mma.cpp index efd9d9848328..ff98aebd812c 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/lower_llvm/mma.cpp +++ b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/core/lower_llvm/mma.cpp @@ -630,7 +630,7 @@ static void _emit_wmma_scale(rocke_lower_t* L, const rocke_op_t* op) op_name, gfx ? gfx : "(unknown)"); } - if(L->flavor != ROCKE_LLVM_FLAVOR_LLVM23) + if(!rocke_ll_profile_has(L->flavor, ROCKE_LL_CAP_LLVM23_TARGET_OPS)) { rocke_ll_fail(L, ROCKE_ERR_NOTIMPL, diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/include/rocke/arch_domain.h b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/include/rocke/arch_domain.h index c326fd7f3a6a..bfb36c7cc449 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/include/rocke/arch_domain.h +++ b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/include/rocke/arch_domain.h @@ -60,6 +60,11 @@ const rocke_arch_domain_cell_t* * Python reader cell for cell. */ const rocke_arch_domain_cell_t* rocke_arch_domain_column(const char* flavor, size_t* count); +/* The flavor whose column `flavor` checks against: its own, else its + * domain.COLUMN_ALIASES source, else `flavor` itself. Messages use this so a + * refusal names the column Python can load. */ +const char* rocke_arch_domain_column_flavor(const char* flavor); + /* Parse a mode as Python's domain.mode() does. NULL, empty and all-whitespace * mean the default generated from domain.DEFAULT_MODE; case and surrounding * ASCII whitespace are ignored. Anything else returns ROCKE_ERR_VALUE and diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/include/rocke/isa_backend.h b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/include/rocke/isa_backend.h index 6c6ea4a21186..d70671ce2cc4 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/include/rocke/isa_backend.h +++ b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/include/rocke/isa_backend.h @@ -109,6 +109,7 @@ const char* rocke_isa_triple(const rocke_isa_backend_t* be); /* The LLVM datalayout string for `flavor` (Python backend.datalayout(flavor)). * Only the buffer-fat-pointer address space (p8) drifts between LLVM 20 (ROCm * 7.0/7.1) and LLVM 22 (ROCm >= 7.2). */ +/* Borrowed process-lifetime string, or NULL for AUTO/an unknown flavor. */ const char* rocke_isa_datalayout_for_flavor(const rocke_isa_backend_t* be, rocke_llvm_flavor_t flavor); /* Flavor-agnostic accessor: the historical shared form (LLVM20). New callers @@ -116,7 +117,8 @@ const char* rocke_isa_datalayout_for_flavor(const rocke_isa_backend_t* be, const char* rocke_isa_datalayout(const rocke_isa_backend_t* be); /* The two leading IR lines for `flavor` (Python backend.module_preamble): * `target datalayout = "..."` + newline + `target triple = "..."`. Written - * into `out` (cleared first). Returns 0 on success, -1 on OOM. */ + * into `out` (cleared first). Returns 0 on success, -1 on OOM or an unknown + * flavor; failure leaves `out` empty. */ int rocke_isa_module_preamble_for_flavor(const rocke_isa_backend_t* be, rocke_llvm_flavor_t flavor, rocke_strbuf_t* out); diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/include/rocke/llvm_profile_internal.h b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/include/rocke/llvm_profile_internal.h new file mode 100644 index 000000000000..bf617ecb4bd8 --- /dev/null +++ b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/include/rocke/llvm_profile_internal.h @@ -0,0 +1,63 @@ +/* Copyright (c) Advanced Micro Devices, Inc., or its affiliates. + * SPDX-License-Identifier: MIT + * + * rocke/llvm_profile_internal.h -- PRIVATE compiler-lane and LLVM emission-profile model. + * Shared by the native LLVM lowerer and ISA adapter; not a public ABI. + */ +#ifndef ROCKE_LLVM_PROFILE_INTERNAL_H +#define ROCKE_LLVM_PROFILE_INTERNAL_H + +#include + +#include "rocke/lower_llvm.h" + +namespace ckc +{ + +typedef enum rocke_ll_datalayout_profile +{ + ROCKE_LL_DATALAYOUT_PROFILE_LLVM20, + ROCKE_LL_DATALAYOUT_PROFILE_LLVM22, + ROCKE_LL_DATALAYOUT_PROFILE_LLVM23 +} rocke_ll_datalayout_profile_t; + +typedef enum rocke_ll_declaration_abi +{ + ROCKE_LL_DECLARATION_ABI_LLVM20, + ROCKE_LL_DECLARATION_ABI_LLVM22, + ROCKE_LL_DECLARATION_ABI_LLVM23 +} rocke_ll_declaration_abi_t; + +typedef enum rocke_ll_emission_capability +{ + ROCKE_LL_CAP_LLVM23_TARGET_OPS = 1u << 0 +} rocke_ll_emission_capability_t; + +typedef struct rocke_ll_emission_profile +{ + rocke_ll_datalayout_profile_t datalayout; + rocke_ll_declaration_abi_t declarations; + unsigned capabilities; +} rocke_ll_emission_profile_t; + +/* Borrowed process-lifetime profile. LLVM23 and LLVM24 intentionally return + * the same object because the qualified LLVM24 lane has no structural IR delta. */ +const rocke_ll_emission_profile_t* rocke_ll_emission_profile(rocke_llvm_flavor_t flavor); +bool rocke_ll_profile_has(rocke_llvm_flavor_t flavor, rocke_ll_emission_capability_t capability); +bool rocke_ll_flavor_is_modern(rocke_llvm_flavor_t flavor); +bool rocke_ll_flavor_at_least(rocke_llvm_flavor_t flavor, rocke_llvm_flavor_t required); +rocke_llvm_flavor_t rocke_ll_flavor_for_llvm_major(unsigned major); +rocke_llvm_flavor_t rocke_ll_explicit_flavor(const char* value); + +extern const char* const ROCKE_LL_DATALAYOUT_LLVM20; +extern const char* const ROCKE_LL_DATALAYOUT_LLVM22; +extern const char* const ROCKE_LL_DATALAYOUT_LLVM23; +extern const char* const ROCKE_LL_DATALAYOUT; +extern const char* const ROCKE_LL_TRIPLE; + +/* Borrowed process-lifetime string, or NULL for AUTO/an unknown flavor. */ +const char* rocke_ll_datalayout_for_flavor(rocke_llvm_flavor_t flavor); + +} // namespace ckc + +#endif // ROCKE_LLVM_PROFILE_INTERNAL_H diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/include/rocke/lower_llvm.h b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/include/rocke/lower_llvm.h index b6d1830a88d2..0447b5e9ec6c 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/include/rocke/lower_llvm.h +++ b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/include/rocke/lower_llvm.h @@ -43,19 +43,19 @@ extern "C" { * and LLVM 21+. The flavor selects a baseline datalayout and pins * the declaration text emitted up front (comgr verifies declares before the * auto-upgrade pass). Mirrors LLVM_FLAVOR_LLVM20 / LLVM_FLAVOR_LLVM22 / - * LLVM_FLAVOR_LLVM23. */ + * LLVM_FLAVOR_LLVM23 / LLVM_FLAVOR_LLVM24. */ typedef enum rocke_llvm_flavor { ROCKE_LLVM_FLAVOR_AUTO = 0, /* explicit override or loaded COMGR compiler */ ROCKE_LLVM_FLAVOR_LLVM20, /* "llvm20" */ ROCKE_LLVM_FLAVOR_LLVM22, /* "llvm22" */ - ROCKE_LLVM_FLAVOR_LLVM23 /* "llvm23" */ + ROCKE_LLVM_FLAVOR_LLVM23, /* "llvm23" */ + ROCKE_LLVM_FLAVOR_LLVM24 /* "llvm24" */ } rocke_llvm_flavor_t; -/* Canonical flavor string ("llvm20"/"llvm22"/"llvm23"), or "" for AUTO. */ +/* Canonical flavor string ("llvm20"/"llvm22"/"llvm23"/"llvm24"), or "" for AUTO. */ const char* rocke_llvm_flavor_name(rocke_llvm_flavor_t flavor); -/* Reverse: "llvm20"/"llvm22"/"llvm23" -> flavor; ROCKE_LLVM_FLAVOR_AUTO if - * unknown. */ +/* Reverse a canonical concrete flavor name; ROCKE_LLVM_FLAVOR_AUTO if unknown. */ rocke_llvm_flavor_t rocke_llvm_flavor_from_name(const char* name); /* Enumerate the concrete (non-AUTO) flavors, oldest first, so a caller can diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/include/rocke/lower_llvm_internal.h b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/include/rocke/lower_llvm_internal.h index 5577319cf469..c004c416a26f 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/cpp/include/rocke/lower_llvm_internal.h +++ b/dnn-providers/hip-kernel-provider/rocke/platform/cpp/include/rocke/lower_llvm_internal.h @@ -2,7 +2,7 @@ * SPDX-License-Identifier: MIT * * rocke/lower_llvm_internal.h -- PRIVATE shared declarations for the C99 port of - * rocke.core.lower_llvm. NOT a public API: only the lower_llvm_*.c translation + * rocke.core.lower_llvm. NOT a public API: only the lower_llvm translation * units include this. The public contract is rocke/lower_llvm.h. * * The Python lowerer is one stateful object, ``_Lowerer``, with ~140 per-op @@ -37,6 +37,7 @@ #include "rocke/arch_domain.h" #include "rocke/arena.h" #include "rocke/ir.h" +#include "rocke/llvm_profile_internal.h" #include "rocke/lower_llvm.h" #include "rocke/strbuf.h" #include "rocke/vec.h" @@ -44,39 +45,6 @@ namespace ckc { -/* ====================================================================== */ -/* Constants (module-level Python data) */ -/* ====================================================================== */ - -/* Verbatim datalayout / triple copied from clang for gfx950 (Python - * _DATALAYOUT_LLVM20 / _DATALAYOUT_LLVM22 / _DATALAYOUT_LLVM23 / _TRIPLE). - * Shared by all CDNA backends per flavor, but the AMDGPU datalayout is - * FLAVOR-KEYED: the buffer-resource address space (p8, the 128-bit buffer - * descriptor, not the p7 fat pointer) drifts between LLVM 20 (ROCm 7.0/7.1) and - * LLVM 22 (ROCm 7.2), and the ELF symbol-mangling spec (m:e) is present in - * LLVM 23 (ROCm 7.13+) but absent in LLVM 20 / 22. ROCKE_LL_DATALAYOUT is a - * back-compat alias - * for the LLVM20 form; new code keys on the flavor via - * rocke_ll_datalayout_for_flavor. */ -extern const char* const ROCKE_LL_DATALAYOUT_LLVM20; -extern const char* const ROCKE_LL_DATALAYOUT_LLVM22; -extern const char* const ROCKE_LL_DATALAYOUT_LLVM23; /* LLVM22 p8 layout + m:e */ -extern const char* const ROCKE_LL_DATALAYOUT; /* == ROCKE_LL_DATALAYOUT_LLVM20 */ -extern const char* const ROCKE_LL_TRIPLE; - -/* Python _datalayout_for_flavor: LLVM20 => legacy p8 layout, LLVM23 => its m:e - * form, anything else (incl. unexpected values) => the modern LLVM22 layout. */ -const char* rocke_ll_datalayout_for_flavor(rocke_llvm_flavor_t flavor); - -/* Python _is_modern_flavor: true for LLVM 21+ IR shapes (llvm22 / llvm23), - * which share the same datalayout + intrinsic declares. - * - * Reads the datalayout-generation column of the flavor ladder in - * lower_llvm/core.cpp rather than naming the members here, mirroring Python, - * where the answer comes from _DATALAYOUT_KIND_FLAVORS. Spelling the pair out - * in an expression is what leaves a new flavor silently classed as legacy. */ -bool rocke_ll_flavor_is_modern(rocke_llvm_flavor_t flavor); - /* CDNA buffer-resource-descriptor DWORD3 (Python ISABackend.buffer_rsrc_word3 * == 0x00027000). RDNA word3 differs (0x31014000) -- see backend struct. */ #define ROCKE_LL_BUFFER_RSRC_WORD3_CDNA 0x00027000 diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/dsl_docs/development/multi_toolchain_strategy.md b/dnn-providers/hip-kernel-provider/rocke/platform/dsl_docs/development/multi_toolchain_strategy.md index 8981a347a4e2..a6bc11dd7bbf 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/dsl_docs/development/multi_toolchain_strategy.md +++ b/dnn-providers/hip-kernel-provider/rocke/platform/dsl_docs/development/multi_toolchain_strategy.md @@ -17,14 +17,15 @@ strategy** for scaling to more toolchains and more targets. > obsolete. Probe results in §2.4 are LLVM-23 observations; re-run before > trusting them on another compiler. > -> **Superseded in part.** §4's R1 has since shipped as -> `tools/gen_arch_domain.py`, and the §2.4 hand-probes are no longer the data — -> the generated columns under -> `python/rocke/core/arch/data/intrinsic_arch_domain..json` are. All -> three flavors are committed (`llvm20`, `llvm22`, `llvm23`), so the survey -> above now has a machine-checked column behind it. Where §2.4 -> and the artifacts disagree, the artifacts win — see -> [`arch_axis_proposal.md`](arch_axis_proposal.md) §3.2 for the rows that changed. +> **Historical architecture snapshot.** §1–§2 predate the explicit LLVM24 +> compiler lane and emission-profile model. Current code separates qualified +> compiler lanes from structural profiles; LLVM23 and LLVM24 share one profile, +> and future compiler majors fail closed. The authoritative current description +> is [`../ir_lowering/backend_details.md`](../ir_lowering/backend_details.md#llvm-intrinsic-flavor). +> §4's R1 also shipped as `tools/gen_arch_domain.py`; committed columns currently +> cover llvm20, llvm22, and llvm23, while LLVM24 artifact generation is separate +> follow-up work. Treat the remaining tables and proposals as historical design +> rationale, not current API documentation. --- diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/dsl_docs/ir_lowering/backend_details.md b/dnn-providers/hip-kernel-provider/rocke/platform/dsl_docs/ir_lowering/backend_details.md index 7fc720b059cf..92cd562e6533 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/dsl_docs/ir_lowering/backend_details.md +++ b/dnn-providers/hip-kernel-provider/rocke/platform/dsl_docs/ir_lowering/backend_details.md @@ -37,32 +37,29 @@ The default `compile_kernel` ISA is `amdgcn-amd-amdhsa--gfx950`, and gfx950 (MI3 ## LLVM Intrinsic Flavor -A small set of AMDGPU intrinsic signatures changed between LLVM 20 and LLVM 21+. The DSL has three baseline emission flavors — `llvm20`, `llvm22`, `llvm23` — enumerated in `LLVM_FLAVORS` (`core/lower_llvm.py`) and mirrored by the C++ engine's flavor table (`cpp/core/lower_llvm/core.cpp`, readable from Python as `rocke_engine.llvm_flavors()`). Automatic selection uses compiler-version evidence from the loaded COMGR binary. A detected LLVM version selects a baseline; toolchain-specific compilation and drift tests remain necessary because compiler builds can differ in DataLayout or intrinsic support. +rocKE separates a **compiler lane** from an **emission profile**. A lane records a qualified compiler major; a profile records the structural LLVM IR that rocKE emits: datalayout generation, declaration ABI, call shapes, and admitted target operations. The qualified lanes are `llvm20`, `llvm22`, `llvm23`, and `llvm24`, enumerated by `LLVM_FLAVORS` in `core/llvm_profile.py` and mirrored by the neutral C++ profile registry in `cpp/core/llvm_profile.cpp`. LLVM23 and LLVM24 intentionally share one emission profile because qualification found no structural IR delta between them. -The signature changes at the llvm20 → llvm21+ boundary: +The profiles capture these differences: -- `llvm.amdgcn.make.buffer.rsrc.p1` → `llvm.amdgcn.make.buffer.rsrc.p8.p1`, `num_records` widened from `i32` to `i64` (LLVM PR #126828). -- `llvm.amdgcn.mfma.f32.{16x16x32,32x32x16}.{fp8,bf8}.{fp8,bf8}` A/B operands collapsed from `<2 x i32>` to scalar `i64`. +- LLVM20 uses the plain-`p8` datalayout and legacy buffer-resource/FP8 MFMA declarations. +- LLVM22 uses indexed `p8`, `make.buffer.rsrc.p8.p1` with an `i64` count, scalar-`i64` FP8/BF8 MFMA operands, and the eleven-argument scaled-MFMA form. +- LLVM23/24 add `m:e` and address spaces `p10`–`p15`, use the nine-argument scaled-MFMA form, and admit the LLVM23-generation target-op surface. -`_INTRINSIC_DECLS_LLVM23_OVERRIDES` currently copies the llvm22 intrinsic table. Both flavors use the `P8_INDEXED` generation (`p8:128:128:128:48`), but their complete datalayouts differ: `_DATALAYOUT_LLVM23` adds the ELF symbol-mangling field `m:e` and address spaces `p10`–`p15`, which `_DATALAYOUT_LLVM22` omits. They therefore emit different IR bytes. Python and C++ must still emit byte-identical IR for the same kernel, target, and flavor. - -**The emitted IR must be compatible with the compiler loaded by COMGR.** Intrinsic declarations from the LLVM 21+ generation can fail verification when compiled by an LLVM 20 compiler. Automatic detection queries the loaded binary; distribution layout and ROCm package versions are not compiler-version evidence. +The compiler resolver never infers structural compatibility from a lane name. Emission decisions consult the selected profile rather than exact `llvm23` comparisons. Python and C++ must emit byte-identical IR for the same kernel, target, and lane. Detection (`core/lower_llvm.py::_detect_llvm_flavor`): -1. A supported `ROCKE_LLVM_FLAVOR` value (`llvm20`, `llvm22`, or `llvm23`) selects emission without loading COMGR. -2. `runtime/comgr.py::loaded_compiler_info()` loads COMGR using the existing library-discovery rules and queries `LLVMGetVersion` through that handle or its loaded dependencies. If that query cannot supply a version, it preprocesses Clang's built-in version macros through the same COMGR. Neither query requires a GPU, an external compiler executable, or a ROCm release file. `_LLVM_FLAVOR_LADDER` maps the detected LLVM major: `< 21` → `llvm20`, `21–22` → `llvm22`, `>= 23` → `llvm23`. -3. If COMGR cannot be loaded or its compiler version cannot be queried, automatic lowering fails. Offline callers must select an explicit flavor through `ROCKE_LLVM_FLAVOR` or the lowering API. - -Resolution is lazy: automatic lowering calls `_resolve_llvm_flavor()`, while an explicit API flavor bypasses discovery. Python caches compiler evidence with the loaded COMGR handle. Python and native AUTO retain the first successfully loaded library and its query result for the process lifetime, including a compiler whose version cannot be queried. Failed loads remain retryable if library availability changes. Configure library selection before automatic lowering or compilation; importing torch or changing library-selection settings afterward does not replace a retained compiler. Changing that compiler requires a new process. +1. A supported `ROCKE_LLVM_FLAVOR` value selects offline emission without loading COMGR. +2. Otherwise COMGR's loaded compiler maps as follows: LLVM <=20 → `llvm20`, 21–22 → `llvm22`, 23 → `llvm23`, and 24 → `llvm24`. +3. A compiler newer than the latest qualified lane fails instead of silently inheriting the newest profile. Missing compiler evidence also fails. Offline callers can select an explicit qualified lane. -Python-driven C++ lowering receives the Python-resolved flavor explicitly. Standalone C++ AUTO discovers and queries its own retained COMGR candidate; it does not share its private handle with a separate compilation stage. A native caller that owns that stage must pass its compiler's flavor explicitly. See [Compiler detection and provenance](../reference/env_flags.md#compiler-detection-and-provenance) for query diagnostics and the library-lifetime contract. +Resolution is lazy and compiler evidence is retained with the loaded COMGR handle. Python-driven C++ lowering receives Python's resolved lane explicitly. Standalone native AUTO applies the same mapping and unknown-value failures. A native caller that owns compilation should pass the lane matching that compiler. See [Compiler detection and provenance](../reference/env_flags.md#compiler-detection-and-provenance). -**Compile-time guard.** `runtime/comgr.py::build_hsaco_from_llvm_ir` calls `_assert_ir_flavor_matches_lib`, which compares the recognized IR datalayout `p8` generation with the generation selected from loaded compiler evidence. `p8:128:128:128:48` is `P8_INDEXED` (llvm22/llvm23); `p8:128:128` is `P8_PLAIN` (llvm20). A known mismatch in either direction raises `ComgrError` with compiler provenance and corrective guidance. The check is independent of emission overrides: selecting a flavor does not change the compiler consuming the IR. Unavailable compiler-version evidence raises `ComgrError` before creating IR compiler inputs, even with an emission override or an unrecognized input datalayout. With known compiler evidence, matching generations pass this guard and an unrecognized input layout leaves layout validation to COMGR. This Python runtime guard applies to IR from either lowering engine when compiled through that path. It checks the p8 generation, not every DataLayout field or intrinsic signature. +**Compile-time guard.** `runtime/comgr.py::build_hsaco_from_llvm_ir` compares the recognized IR `p8` generation with the profile selected from loaded compiler evidence. `p8:128:128:128:48` is `P8_INDEXED` (llvm22/llvm23/llvm24); `p8:128:128` is `P8_PLAIN` (llvm20). This catches a known ABI-generation mismatch but does not replace real-toolchain validity and datalayout-drift checks. -Tests / callers who need a specific flavor pass `lower_kernel_to_llvm(kernel, arch="gfx950", llvm_flavor=LLVM_FLAVOR_LLVM20)` (or `LLVM_FLAVOR_LLVM22` / `LLVM_FLAVOR_LLVM23`). All three constants live in `core/lower_llvm.py`. Adding a new intrinsic that changes shape across versions: add the LLVM 20 signature to `_INTRINSIC_DECLS`, the LLVM 21+ override to `_INTRINSIC_DECLS_LLVM22_OVERRIDES` (and to `_INTRINSIC_DECLS_LLVM23_OVERRIDES` if LLVM 23 differs again — it currently just copies the llvm22 table), and branch on `self._flavor` inside the `_op_*` handler (see `_op_tile_buffer_rsrc` and `_lower_mfma_fp8_bf8` for working examples). Prefer `_is_modern_flavor(self._flavor)` over naming flavors in the branch: `test_no_hand_rolled_flavor_membership_lists` rejects a literal listing two or more flavor constants, because that is the shape that silently left `llvm23` out. +When adding a lane, first characterize its real compiler output. Add a lane only for qualification; add a distinct profile only for a structural IR difference. Put declaration and call-shape decisions in the profile instead of branching on a lane name. Python/C++ profile tests, the real-toolchain drift guard, emitted-IR validity, and byte identity cover different contracts and remain independently required. -The committed golden (`tests/golden/rocke_representative_ir_sha256.json`) holds one sub-document per flavor and `check_golden` verifies **all** of them from any host, so an llvm23 hash cannot go stale just because CI runs on ROCm 7.2. The comparator lives in `core/ir_golden.py` and takes its flavor list straight from `LLVM_FLAVORS`, so adding a flavor fails every golden that uses it (this one and the library's gfx942 `attention_dense` fixture) until they are re-blessed, with no golden-test edit. +Goldens store one sub-document per distinct emission profile. A lane in `aliases` is still lowered and compared, but reuses the profile-identical baseline instead of duplicating thousands of hashes. Thus LLVM24 is checked against LLVM23's baseline while remaining a separately exercised compiler lane. ## Wave Size diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/dsl_docs/reference/env_flags.md b/dnn-providers/hip-kernel-provider/rocke/platform/dsl_docs/reference/env_flags.md index fe84b74a0b72..cea2d356bc2d 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/dsl_docs/reference/env_flags.md +++ b/dnn-providers/hip-kernel-provider/rocke/platform/dsl_docs/reference/env_flags.md @@ -14,9 +14,9 @@ For setup and the most common flags in context, see | Variable | Values (default) | Purpose | |---|---|---| | `ROCKE_BACKEND` | `cpp` \| `python` \| `both` (**cpp**) | Which engine lowers Python-authored kernels. `cpp` = C++ engine (auto-falls back to Python if `rocke_engine` isn't built); `python` = native lowerer; `both` = run both and assert byte-identical (the differential check). | -| `ROCKE_LLVM_FLAVOR` | `llvm20` \| `llvm22` \| `llvm23` (auto) | Override the emitted LLVM IR flavor. AUTO loads COMGR, queries its compiler, and maps LLVM <=20 to `llvm20`, 21/22 to `llvm22`, and >=23 to `llvm23`. If no compiler can be queried, AUTO raises; select a flavor explicitly for offline IR emission. An override selects emission; it does not change or bypass validation against the loaded compiler. | +| `ROCKE_LLVM_FLAVOR` | `llvm20` \| `llvm22` \| `llvm23` \| `llvm24` (auto) | Select a qualified compiler lane for emitted LLVM IR. AUTO loads COMGR, queries its compiler, and maps LLVM <=20 to `llvm20`, 21/22 to `llvm22`, 23 to `llvm23`, and 24 to `llvm24`. A newer compiler or unavailable evidence raises instead of silently inheriting the latest lane. Explicit selection supports offline emission but does not bypass runtime compiler validation. LLVM23 and LLVM24 currently share one structural emission profile. | | `ROCKE_CPP_STRICT` | `1` (unset) | Make `cpp` backend **raise** instead of silently falling back to Python when `rocke_engine` is unavailable. | -| `ROCKE_ARCH_DOMAIN` | `error` \| `warn` \| `off` (**warn**) | What both engines do when a kernel demands an intrinsic the committed arch-domain table (`python/rocke/core/arch/data/intrinsic_arch_domain..json`) says the target cannot lower. `error` refuses the lowering with `ArchDomainError` unless the cell is waived in `arch_domain_waivers.json`; `warn` reports it as `ArchDomainWarning` and keeps lowering; `off` skips the lookup. Case and surrounding whitespace are ignored; any other value raises. The C++ engine reads it too, and refuses in `error` mode with the same message. See [`../../../TESTING.md`](../../../TESTING.md), the arch-domain gate. | +| `ROCKE_ARCH_DOMAIN` | `error` \| `warn` \| `off` (**warn**) | What both engines do when a kernel demands an intrinsic the committed arch-domain table (`python/rocke/core/arch/data/intrinsic_arch_domain..json`) says the target cannot lower. Until it has its own measured column, the `llvm24` lane enforces the `llvm23` column that applied before the lanes were split; that column has not been measured on LLVM24, and a committed `llvm24` column automatically takes precedence. `error` refuses the lowering with `ArchDomainError` unless the cell is waived in `arch_domain_waivers.json`; `warn` reports it as `ArchDomainWarning` and keeps lowering; `off` skips the lookup. Case and surrounding whitespace are ignored; any other value raises. The C++ engine reads it too, and refuses in `error` mode with the same message. See [`../../../TESTING.md`](../../../TESTING.md), the arch-domain gate. | | `ROCKE_DEBUG` | `1` (unset) | Verbose engine diagnostics during build/lowering. | | `ROCKE_DEBUG_LOC` | `1` (unset) | Record the Python call stack behind every op while the kernel builds, and lower it to DWARF inlining scopes, so an ATT trace maps instructions back to the source that authored them. Off by default for two reasons: it costs a stack walk per op (material on sweeps that build thousands of kernels), and populating `op.loc` **changes the emitted `.ll` bytes**, so the byte-identity gate and the IR goldens run without it. The added metadata does not change the generated ISA, so a trace captured with it on is still representative. `IRBuilder(capture_loc=True)` is the per-builder equivalent. Set it on the process that **builds** the kernel, not on the compiler; [`capture_wavescope_trace.py`](../optimization/utilities/tools/wavescope/capture_wavescope_trace.py) does that and the rest of the capture in one command. The same DWARF is what lets `rocgdb` name the authoring line behind a memory fault — see [`../development/debugging_rocgdb.md`](../development/debugging_rocgdb.md). | | `ROCKE_TIME` | `1` (unset) | Print phase timings for the build/lower/compile pipeline. | @@ -169,6 +169,7 @@ their explicit argument/environment precedence is unchanged. Offline IR emission requires an explicit flavor. COMGR compilation requires a known compiler version even with an emission override or an unrecognised input datalayout. -The detected LLVM version selects a baseline flavor; it does not prove that -all builds of that version share an exact DataLayout or intrinsic catalog. -Toolchain-specific compilation and drift tests remain necessary. +The detected LLVM version selects a qualified compiler lane, which then selects +an emission profile. LLVM23 and LLVM24 currently share one profile. That does not +prove every build of either major has an identical DataLayout or intrinsic +catalog; toolchain-specific compilation and drift tests remain necessary. diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/core/arch/domain.py b/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/core/arch/domain.py index 5209b227514d..dcef8a355a68 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/core/arch/domain.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/core/arch/domain.py @@ -197,16 +197,42 @@ def committed_flavors() -> tuple[str, ...]: ) +# Lanes that enforce another lane's measured column until their own is +# committed. The borrowed column was not measured on the borrowing toolchain; +# it preserves the gate that applied before the compiler lane was split out and +# is safer than silently running with no gate. A lane's own column always wins. +# tools/gen_arch_domain_cpp.py copies this map into the C++ engine. +COLUMN_ALIASES: dict[str, str] = {"llvm24": "llvm23"} + + +def _column_path(flavor: str) -> Path: + return _DATA_DIR / f"{_COLUMN_PREFIX}{flavor}{_COLUMN_SUFFIX}" + + +def column_flavor(flavor: str) -> str: + """The column ``flavor`` checks against: its own, else its alias.""" + if _column_path(flavor).is_file(): + return flavor + return COLUMN_ALIASES.get(flavor, flavor) + + @functools.cache def load(flavor: str) -> ArchDomain | None: """The committed column for ``flavor``, or ``None`` if there is not one. + A flavor in :data:`COLUMN_ALIASES` with no column of its own gets its + source's column. The returned table's ``flavor`` names that source, which + messages and waivers must also use. + A host can only measure its own LLVM, so a missing column is normal, not an error. Callers must treat the ``None`` as no data. Only absence is: a column that exists but cannot be read (permissions, I/O) raises, because returning ``None`` for it would switch the whole lane off without a word. """ - path = _DATA_DIR / f"{_COLUMN_PREFIX}{flavor}{_COLUMN_SUFFIX}" + source = column_flavor(flavor) + if source != flavor: + return load(source) + path = _column_path(flavor) try: text = path.read_text(encoding="utf-8") except FileNotFoundError: diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/core/ir.py b/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/core/ir.py index 1b1cbeaf5e3a..53bb11df19d6 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/core/ir.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/core/ir.py @@ -3266,7 +3266,7 @@ def _gfx1250_scalar_control(self, mnemonic: str, imm: int) -> None: "sideeffect": True, "convergent": False, "required_arch": "gfx1250", - "required_llvm_flavor": "llvm23", + "minimum_llvm_flavor": "llvm23", }, ) diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/core/ir_golden.py b/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/core/ir_golden.py index 07aac0cc3508..9f4e55ee2c6a 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/core/ir_golden.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/core/ir_golden.py @@ -3,15 +3,17 @@ """Comparator for flavor-keyed LLVM-IR golden fixtures. -A golden stores one sub-document per LLVM flavor under ``flavors``, each -holding a ``cases`` map (``case_id -> {"sha256": ...}``) and optionally an -``expected_failures`` map (``case_id -> {"type", "message"}``). Lowering takes -the flavor as an argument, so any host can verify every sub-document, not just -the one its ROCm vintage autodetects. +A golden stores one sub-document per distinct emission profile under +``flavors``. ``aliases`` maps a compiler lane to another lane with the same +profile, avoiding duplicate fixtures while still lowering and checking the +aliased lane. Each sub-document holds a ``cases`` map and optionally an +``expected_failures`` map. Lowering takes the lane as an argument, so any host +can verify every qualified lane, not just the one it autodetects. :data:`GOLDEN_FLAVORS` is :data:`~rocke.core.lower_llvm.LLVM_FLAVORS` itself. -Adding a flavor there makes every golden checked through :func:`check_golden` -fail until it is re-blessed, with no edit to the golden test. This module is +Adding a lane there makes every golden checked through :func:`check_golden` +fail until it receives a profile document or an explicit shared-profile alias, +with no edit to the golden test. This module is shipped so ``library/`` goldens can share it (the dependency stays ``library -> platform``). """ @@ -23,13 +25,28 @@ from pathlib import Path from typing import Any -from .lower_llvm import LLVM_FLAVORS +from .llvm_profile import LLVM_EMISSION_ALIASES, LLVM_EMISSION_FLAVORS, LLVM_FLAVORS -#: Flavors every golden must record. Deliberately the same object as +#: Lanes every golden must represent directly or through an alias. Same object as #: :data:`LLVM_FLAVORS`, never a copy. GOLDEN_FLAVORS = LLVM_FLAVORS +GOLDEN_PROFILE_FLAVORS = LLVM_EMISSION_FLAVORS +GOLDEN_ALIASES = LLVM_EMISSION_ALIASES -__all__ = ["GOLDEN_FLAVORS", "check_golden", "compare"] +__all__ = [ + "GOLDEN_ALIASES", + "GOLDEN_FLAVORS", + "GOLDEN_PROFILE_FLAVORS", + "check_golden", + "compare", + "golden_subdocument", +] + + +def golden_subdocument(doc: Mapping[str, Any], flavor: str) -> Mapping[str, Any] | None: + """Return the baseline for ``flavor``, following one profile alias.""" + source = doc.get("aliases", {}).get(flavor, flavor) + return doc.get("flavors", {}).get(source) def compare(base: Mapping[str, Any], cur: Mapping[str, Any]) -> list[str]: @@ -74,21 +91,47 @@ def check_golden( """ doc = json.loads(Path(golden_path).read_text()) have = doc.get("flavors", {}) + aliases = doc.get("aliases", {}) wanted = [flavor] if flavor else list(GOLDEN_FLAVORS) errors: list[str] = [] + if not flavor: + if aliases != GOLDEN_ALIASES: + errors.append( + f"golden aliases {aliases} do not match emission-profile aliases " + f"{GOLDEN_ALIASES}; re-bless it" + ) + if set(have) != set(GOLDEN_PROFILE_FLAVORS): + errors.append( + f"golden profile documents {sorted(have)} do not match " + f"{list(GOLDEN_PROFILE_FLAVORS)}; re-bless it" + ) + overlap = set(have) & set(aliases) + if overlap: + errors.append( + f"golden lanes are both direct and aliased: {sorted(overlap)}; " + "re-bless it" + ) + if errors: + return errors for fl in wanted: - base = have.get(fl) + base = golden_subdocument(doc, fl) if base is None: errors.append( - f"golden has no entry for flavor {fl!r} (have {sorted(have)}); " - "re-bless it" + f"golden has no entry or valid alias for flavor {fl!r} " + f"(have {sorted(have)}); re-bless it" ) continue prefix = "" if len(wanted) == 1 else f"[{fl}] " errors.extend(prefix + e for e in compare(base, run(fl))) if not flavor: - for fl in sorted(set(have) - set(GOLDEN_FLAVORS)): + represented = set(have) | set(aliases) + for fl in sorted(represented - set(GOLDEN_FLAVORS)): errors.append( f"golden has stale flavor {fl!r} not in LLVM_FLAVORS; re-bless it" ) + for fl, source in sorted(aliases.items()): + if source not in have: + errors.append( + f"golden alias {fl!r} names missing flavor {source!r}; re-bless it" + ) return errors diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/core/isa/backend.py b/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/core/isa/backend.py index 0554775f995e..b6ee5107e729 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/core/isa/backend.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/core/isa/backend.py @@ -32,6 +32,7 @@ from ..arch import ArchTarget from ..arch.wmma_scale import gfx1250_scaled_wmma from ..ir import I32, Op, VectorType +from ..llvm_profile import _supports_llvm23_target_ops from .wmma_scale import ScaledWmmaLLVM @@ -229,7 +230,7 @@ def emit_scaled_wmma(self, lowerer, op) -> None: f"{name} is not available on {self.arch.gfx}: " "its MMA catalog does not list it" ) - if lowerer._flavor != "llvm23": + if not _supports_llvm23_target_ops(lowerer._flavor): raise NotImplementedError( f"{name} requires llvm23 (ROCm 7.13+), got {lowerer._flavor}" ) diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/core/llvm_profile.py b/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/core/llvm_profile.py new file mode 100644 index 000000000000..d27120456288 --- /dev/null +++ b/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/core/llvm_profile.py @@ -0,0 +1,328 @@ +# Copyright (c) Advanced Micro Devices, Inc., or its affiliates. +# SPDX-License-Identifier: MIT + +"""Qualified LLVM compiler lanes and structural emission profiles. + +This neutral module is shared by the LLVM lowerer and ISA adapter. A compiler +lane records qualification; a profile records the LLVM-IR structure emitted by +one or more lanes. +""" + +from __future__ import annotations + +import enum +from dataclasses import dataclass + +# Datalayout / triple. Copied verbatim from clang's output for the same +# target on this box: clang -target amdgcn-amd-amdhsa -mcpu=gfx950 +# -emit-llvm -S. The string is LLVM-version-keyed, not gfx-keyed: every +# wired arch shares one datalayout, but two fields drift across LLVM 20 +# (ROCm 7.0/7.1), LLVM 22 (ROCm 7.2), and LLVM 23 (ROCm 7.13+): +# +# * the ELF symbol-mangling spec ``m:e``: absent in LLVM 20 and LLVM 22, +# present in LLVM 23 (AMD clang 23.0.0git, ROCm 7.13). (It also appeared +# in early LLVM 22 builds but was dropped; ROCm 7.2's LLVM 22 omits it.) +# LLVM 20: e-p:64:64-... +# LLVM 22: e-p:64:64-... +# LLVM 23: e-m:e-p:64:64-... +# * the buffer-resource address space (``p8``, the 128-bit buffer +# descriptor -- NOT the buffer fat pointer, which is ``p7``) gained an +# index-width field in LLVM 22: +# LLVM 20: ...-p8:128:128-... +# LLVM 22 / 23: ...-p8:128:128:128:48-... +# +# Each constant reflects what the installed hipcc actually produces for that +# LLVM vintage; the drift guard re-derives them from the toolchain. +# +# (Confirmed against clang 20 and current clang 22 amdgcn output.) On the +# textual-IR (comgr SOURCE) path the parser is lenient: it overrides the +# module datalayout with the target's canonical one, so a stale-but-well- +# formed string compiles to byte-identical HSACO and the drift is +# invisible at runtime. That leniency is not a contract -- bitcode input +# or a stricter verifier can reject a mismatch, so we emit the correct +# string up front. Pick by :data:`LLVM_FLAVOR_*` via +# :func:`_datalayout_for_flavor`. A drift guard +# (``test_datalayout_matches_hipcc_emitted_ir``) re-derives both from the +# installed toolchain; if it fails, regenerate with the clang command above. +_DATALAYOUT_LLVM20 = ( + "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32" + "-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16-v24:32-v32:32" + "-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048" + "-n32:64-S32-A5-G1-ni:7:8:9" +) +_DATALAYOUT_LLVM22 = ( + "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32" + "-p7:160:256:256:32-p8:128:128:128:48-p9:192:256:256:32-i64:64-v16:16-v24:32" + "-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048" + "-n32:64-S32-A5-G1-ni:7:8:9" +) +# Layout emitted for rocKE's ``llvm23`` flavor. Relative to our ``llvm22`` +# constant it adds two independent things: +# +# 1. the ELF symbol-mangling spec ``m:e``, which LLVM 20 and LLVM 22 omit; +# 2. address spaces ``p10``-``p15``, introduced upstream by ``5bf967cb132b``. +# +# Both were re-derived from the clang on an amd-staging host and confirmed +# gfx-invariant there across every wired arch +# (gfx90a/942/950/1100/1151/1201/1250). +# +# This is rocKE's flavor constant, NOT a claim about what every LLVM 23+ / +# ROCm 7.13+ build emits: compiler builds vary, and older ones -- including some +# builds numbered LLVM 23 or later -- omit ``p10``-``p15``. The drift guard +# ``test_datalayout_matches_hipcc_emitted_ir`` accommodates exactly that +# variation. +# +# Why we carry the longer form. LLVM's backend has long rejected a module whose +# DataLayout is incompatible with the target's ("Can't create a MachineFunction +# using a Module with a Target-incompatible DataLayout attached" -- the check is +# already in LLVM 22's MachineFunction.cpp, so it predates ``fc6829a3``). What +# changed in ``fc6829a3`` ("clang: Do not overwrite a module's DataLayout in the +# backend") is that clang stopped replacing an explicitly supplied layout, which +# exposes that pre-existing check to the layout rocKE hands it. On the clang +# builds we tested, the consequence is concrete: +# +# * against staging clang (post-``fc6829a3``), a module carrying the short +# form fails codegen outright, and the long form builds and links; +# * against the older ``/opt/rocm`` clang we tested, whose own layout omits +# ``p10``-``p15``, the long form is still accepted (rc=0) because that clang +# overwrites the supplied layout before codegen. +# +# That is an observation about the builds we exercised, not a proof about every +# toolchain. It is still the right trade: do NOT "fix" a mismatch against an +# older hipcc by deleting ``p10``-``p15``, since that re-breaks every kernel on a +# current toolchain. Regenerate via ``test_datalayout_matches_hipcc_emitted_ir`` +# if a future build drifts further. +_DATALAYOUT_LLVM23 = ( + "e-m:e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32" + "-p7:160:256:256:32-p8:128:128:128:48-p9:192:256:256:32-p10:32:32-p11:32:32" + "-p12:32:32-p13:32:32-p14:32:32-p15:32:32-i64:64-v16:16-v24:32" + "-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048" + "-n32:64-S32-A5-G1-ni:7:8:9" +) +_TRIPLE = "amdgcn-amd-amdhsa" + + +# A small set of AMDGPU intrinsic signatures changed between LLVM 20 +# (ROCm 7.0/7.1) and LLVM 21+ (ROCm 7.2 ships LLVM 22): +# +# * ``make.buffer.rsrc.p1`` -> ``make.buffer.rsrc.p8.p1`` and the +# ``num_records`` arg widened from ``i32`` to ``i64`` (LLVM PR +# #126828). +# * fp8 / bf8 MFMA A/B operands collapsed from ``<2 x i32>`` to a +# scalar ``i64`` (same 64 bits, different LLVM type). +# +# comgr verifies the toplevel ``declare`` lines BEFORE running the +# auto-upgrade pass, so we have to emit the right signature up front. +# Resolve from the loaded compiler when lowering; ``lower_kernel_to_llvm`` +# also accepts an explicit ``llvm_flavor=`` for offline emission. +LLVM_FLAVOR_LLVM20 = "llvm20" +LLVM_FLAVOR_LLVM22 = "llvm22" +LLVM_FLAVOR_LLVM23 = "llvm23" +LLVM_FLAVOR_LLVM24 = "llvm24" + +# Compiler lanes, ordered by the first LLVM major they qualify. A lane names +# the compiler contract; its emission profile below names the LLVM-IR structure. +# Keeping those concepts separate lets llvm23 and llvm24 share IR deliberately +# without silently treating every future compiler as compatible. +_LLVM_FLAVOR_LADDER: tuple[tuple[int, str], ...] = ( + (0, LLVM_FLAVOR_LLVM20), + (21, LLVM_FLAVOR_LLVM22), + (23, LLVM_FLAVOR_LLVM23), + (24, LLVM_FLAVOR_LLVM24), +) + +# Every compiler lane rocke qualifies, oldest first. Derive this from the +# resolver ladder so enumeration and automatic selection cannot drift apart. +LLVM_FLAVORS: tuple[str, ...] = tuple(flavor for _, flavor in _LLVM_FLAVOR_LADDER) +_LLVM_FLAVOR_RANK: dict[str, int] = { + flavor: rank for rank, flavor in enumerate(LLVM_FLAVORS) +} + + +class LlvmDatalayoutKind(enum.Enum): + """Datalayout generation, i.e. what an IR module's ``p8`` field reveals. + + Two datalayout fields drift between flavors -- the buffer-resource address + space ``p8`` shape and the ELF mangling spec ``m:e`` -- but only ``p8`` + partitions the flavors into the *generation* that gates intrinsic-declare + compatibility (``make.buffer.rsrc.p8.p1``, fp8/bf8 MFMA operand widths). So + this kind groups flavors by p8 shape, NOT by full datalayout identity: + llvm22 and llvm23 share a generation yet differ in ``m:e`` (llvm23 has it), + so the datalayout alone still cannot narrow to a single flavor. + + Members are named after the datalayout shape, deliberately not after its + recency: a "modern" label stops being true the moment a newer generation + lands, whereas ``P8_INDEXED`` keeps describing exactly what it matches. + """ + + #: LLVM 20 and older: ``p8:128:128`` (no index-width field). + P8_PLAIN = "p8_plain" + #: LLVM 21+: ``p8:128:128:128:48`` (index width appended). + P8_INDEXED = "p8_indexed" + + @property + def flavors(self) -> frozenset[str]: + """Flavors that emit this datalayout generation.""" + return _DATALAYOUT_KIND_FLAVORS[self] + + def describe(self) -> str: + """Human-readable form for diagnostics, e.g. ``p8_indexed (llvm22/llvm23)``.""" + return f"{self.value} ({'/'.join(sorted(self.flavors))})" + + +# Partition of :data:`LLVM_FLAVORS` by datalayout generation. Every flavor must +# appear in exactly one entry, and every enum member must have an entry; +# ``test_datalayout_kinds_partition_every_flavor`` is the exhaustiveness check a +# language-level ``match`` would give for free. +class _LlvmDeclarationAbi(enum.Enum): + """Declaration and call-shape generation selected by an emission profile.""" + + LLVM20 = "llvm20" + LLVM22 = "llvm22" + LLVM23 = "llvm23" + + +class _LlvmEmissionCapability(enum.Enum): + """Structural operations admitted by an emission profile.""" + + LLVM23_TARGET_OPS = "llvm23_target_ops" + + +@dataclass(frozen=True) +class _LlvmEmissionProfile: + """LLVM-IR structure shared by one or more qualified compiler lanes.""" + + datalayout: str + datalayout_kind: LlvmDatalayoutKind + declaration_abi: _LlvmDeclarationAbi + capabilities: frozenset[_LlvmEmissionCapability] = frozenset() + + def has(self, capability: _LlvmEmissionCapability) -> bool: + return capability in self.capabilities + + +_PROFILE_LLVM20 = _LlvmEmissionProfile( + _DATALAYOUT_LLVM20, + LlvmDatalayoutKind.P8_PLAIN, + _LlvmDeclarationAbi.LLVM20, +) +_PROFILE_LLVM22 = _LlvmEmissionProfile( + _DATALAYOUT_LLVM22, + LlvmDatalayoutKind.P8_INDEXED, + _LlvmDeclarationAbi.LLVM22, +) +_PROFILE_LLVM23 = _LlvmEmissionProfile( + _DATALAYOUT_LLVM23, + LlvmDatalayoutKind.P8_INDEXED, + _LlvmDeclarationAbi.LLVM23, + frozenset({_LlvmEmissionCapability.LLVM23_TARGET_OPS}), +) + +# LLVM 24 is a distinct qualified compiler lane with no structural IR delta +# from LLVM 23 in the qualified toolchain. Sharing the object makes that an +# executable decision rather than a copied set of coincidentally equal fields. +_LLVM_EMISSION_PROFILES: dict[str, _LlvmEmissionProfile] = { + LLVM_FLAVOR_LLVM20: _PROFILE_LLVM20, + LLVM_FLAVOR_LLVM22: _PROFILE_LLVM22, + LLVM_FLAVOR_LLVM23: _PROFILE_LLVM23, + LLVM_FLAVOR_LLVM24: _PROFILE_LLVM23, +} + +# One canonical lane per distinct structural profile, plus explicit aliases. +# Golden writers use these to avoid storing identical hash documents. Keep the +# mapping reviewable: aliasing is a qualification decision, not object identity. +LLVM_EMISSION_ALIASES: dict[str, str] = { + LLVM_FLAVOR_LLVM24: LLVM_FLAVOR_LLVM23, +} +LLVM_EMISSION_FLAVORS: tuple[str, ...] = tuple( + flavor for flavor in LLVM_FLAVORS if flavor not in LLVM_EMISSION_ALIASES +) + + +def _emission_profile(flavor: str) -> _LlvmEmissionProfile: + try: + return _LLVM_EMISSION_PROFILES[flavor] + except KeyError as exc: + raise ValueError( + f"unknown LLVM flavor {flavor!r}; expected one of {LLVM_FLAVORS}" + ) from exc + + +def _supports_llvm23_target_ops(flavor: str) -> bool: + """Whether ``flavor`` admits the LLVM23-generation target-op surface.""" + return _emission_profile(flavor).has(_LlvmEmissionCapability.LLVM23_TARGET_OPS) + + +def _flavor_at_least(flavor: str, required: str) -> bool: + """Compare qualified compiler lanes without comparing their names.""" + try: + return _LLVM_FLAVOR_RANK[flavor] >= _LLVM_FLAVOR_RANK[required] + except KeyError as exc: + unknown = flavor if flavor not in _LLVM_FLAVOR_RANK else required + raise ValueError( + f"unknown LLVM flavor {unknown!r}; expected one of {LLVM_FLAVORS}" + ) from exc + + +# Compatibility view retained for the datalayout-generation guard and COMGR +# mismatch diagnostics. It is derived from profiles rather than maintained as +# another flavor membership list. +_DATALAYOUT_KIND_FLAVORS: dict[LlvmDatalayoutKind, frozenset[str]] = { + kind: frozenset( + flavor + for flavor, profile in _LLVM_EMISSION_PROFILES.items() + if profile.datalayout_kind is kind + ) + for kind in LlvmDatalayoutKind +} + +# Substrings that identify each generation in a module's ``target datalayout``. +# Kept consistent with the ``_DATALAYOUT_*`` constants by +# ``test_datalayout_kind_markers_match_datalayouts``. +_P8_MARKERS: dict[LlvmDatalayoutKind, str] = { + LlvmDatalayoutKind.P8_INDEXED: "p8:128:128:128:48", + LlvmDatalayoutKind.P8_PLAIN: "p8:128:128-", +} + + +def _datalayout_kind_for_flavor(flavor: str) -> LlvmDatalayoutKind | None: + """Datalayout generation a flavor emits, or ``None`` if unrecognised.""" + profile = _LLVM_EMISSION_PROFILES.get(flavor) + return profile.datalayout_kind if profile is not None else None + + +def _datalayout_kind_from_ir(ir_text: str) -> LlvmDatalayoutKind | None: + """Datalayout generation of an IR module, read from its ``p8`` field. + + ``None`` when the module has no recognisable ``target datalayout``. This + cannot narrow to a single flavor -- see :class:`LlvmDatalayoutKind`. + """ + # P8_INDEXED first: its marker has the plain form as a prefix. + for kind in (LlvmDatalayoutKind.P8_INDEXED, LlvmDatalayoutKind.P8_PLAIN): + if _P8_MARKERS[kind] in ir_text: + return kind + return None + + +def _is_modern_flavor(flavor: str) -> bool: + """True for flavors emitting the LLVM 21+ indexed-``p8`` ABI.""" + return _datalayout_kind_for_flavor(flavor) is LlvmDatalayoutKind.P8_INDEXED + + +def _datalayout_for_flavor(flavor: str) -> str: + """Module ``target datalayout`` selected by a compiler lane's profile.""" + return _emission_profile(flavor).datalayout + + +def _flavor_for_llvm(major: int) -> str: + """Map a compiler major to a qualified lane, failing beyond the frontier.""" + latest_major, latest_flavor = _LLVM_FLAVOR_LADDER[-1] + if major > latest_major: + raise ValueError( + f"LLVM compiler major {major} is newer than the latest qualified " + f"lane {latest_flavor}" + ) + for minimum, flavor in reversed(_LLVM_FLAVOR_LADDER): + if major >= minimum: + return flavor + return LLVM_FLAVORS[0] diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/core/lower_llvm.py b/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/core/lower_llvm.py index f4af4b7b0582..ff3bd5f5f9ac 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/core/lower_llvm.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/core/lower_llvm.py @@ -36,7 +36,7 @@ import os import warnings from dataclasses import dataclass, field -from typing import Dict, FrozenSet, List, NamedTuple, Optional, Set, Tuple +from typing import Dict, List, NamedTuple, Optional, Set, Tuple from .arch import MmaEmulationRecipe from .codegen_policy import codegen_policy_for_kernel @@ -80,124 +80,31 @@ ) from .tf32 import tf32_mma_target_error, tf32_op_error - -# Datalayout / triple. Copied verbatim from clang's output for the same -# target on this box: clang -target amdgcn-amd-amdhsa -mcpu=gfx950 -# -emit-llvm -S. The string is LLVM-version-keyed, not gfx-keyed: every -# wired arch shares one datalayout, but two fields drift across LLVM 20 -# (ROCm 7.0/7.1), LLVM 22 (ROCm 7.2), and LLVM 23 (ROCm 7.13+): -# -# * the ELF symbol-mangling spec ``m:e``: absent in LLVM 20 and LLVM 22, -# present in LLVM 23 (AMD clang 23.0.0git, ROCm 7.13). (It also appeared -# in early LLVM 22 builds but was dropped; ROCm 7.2's LLVM 22 omits it.) -# LLVM 20: e-p:64:64-... -# LLVM 22: e-p:64:64-... -# LLVM 23: e-m:e-p:64:64-... -# * the buffer-resource address space (``p8``, the 128-bit buffer -# descriptor -- NOT the buffer fat pointer, which is ``p7``) gained an -# index-width field in LLVM 22: -# LLVM 20: ...-p8:128:128-... -# LLVM 22 / 23: ...-p8:128:128:128:48-... -# -# Each constant reflects what the installed hipcc actually produces for that -# LLVM vintage; the drift guard re-derives them from the toolchain. -# -# (Confirmed against clang 20 and current clang 22 amdgcn output.) On the -# textual-IR (comgr SOURCE) path the parser is lenient: it overrides the -# module datalayout with the target's canonical one, so a stale-but-well- -# formed string compiles to byte-identical HSACO and the drift is -# invisible at runtime. That leniency is not a contract -- bitcode input -# or a stricter verifier can reject a mismatch, so we emit the correct -# string up front. Pick by :data:`LLVM_FLAVOR_*` via -# :func:`_datalayout_for_flavor`. A drift guard -# (``test_datalayout_matches_hipcc_emitted_ir``) re-derives both from the -# installed toolchain; if it fails, regenerate with the clang command above. -_DATALAYOUT_LLVM20 = ( - "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32" - "-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16-v24:32-v32:32" - "-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048" - "-n32:64-S32-A5-G1-ni:7:8:9" -) -_DATALAYOUT_LLVM22 = ( - "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32" - "-p7:160:256:256:32-p8:128:128:128:48-p9:192:256:256:32-i64:64-v16:16-v24:32" - "-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048" - "-n32:64-S32-A5-G1-ni:7:8:9" -) -# Layout emitted for rocKE's ``llvm23`` flavor. Relative to our ``llvm22`` -# constant it adds two independent things: -# -# 1. the ELF symbol-mangling spec ``m:e``, which LLVM 20 and LLVM 22 omit; -# 2. address spaces ``p10``-``p15``, introduced upstream by ``5bf967cb132b``. -# -# Both were re-derived from the clang on an amd-staging host and confirmed -# gfx-invariant there across every wired arch -# (gfx90a/942/950/1100/1151/1201/1250). -# -# This is rocKE's flavor constant, NOT a claim about what every LLVM 23+ / -# ROCm 7.13+ build emits: compiler builds vary, and older ones -- including some -# builds numbered LLVM 23 or later -- omit ``p10``-``p15``. The drift guard -# ``test_datalayout_matches_hipcc_emitted_ir`` accommodates exactly that -# variation. -# -# Why we carry the longer form. LLVM's backend has long rejected a module whose -# DataLayout is incompatible with the target's ("Can't create a MachineFunction -# using a Module with a Target-incompatible DataLayout attached" -- the check is -# already in LLVM 22's MachineFunction.cpp, so it predates ``fc6829a3``). What -# changed in ``fc6829a3`` ("clang: Do not overwrite a module's DataLayout in the -# backend") is that clang stopped replacing an explicitly supplied layout, which -# exposes that pre-existing check to the layout rocKE hands it. On the clang -# builds we tested, the consequence is concrete: -# -# * against staging clang (post-``fc6829a3``), a module carrying the short -# form fails codegen outright, and the long form builds and links; -# * against the older ``/opt/rocm`` clang we tested, whose own layout omits -# ``p10``-``p15``, the long form is still accepted (rc=0) because that clang -# overwrites the supplied layout before codegen. -# -# That is an observation about the builds we exercised, not a proof about every -# toolchain. It is still the right trade: do NOT "fix" a mismatch against an -# older hipcc by deleting ``p10``-``p15``, since that re-breaks every kernel on a -# current toolchain. Regenerate via ``test_datalayout_matches_hipcc_emitted_ir`` -# if a future build drifts further. -_DATALAYOUT_LLVM23 = ( - "e-m:e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32" - "-p7:160:256:256:32-p8:128:128:128:48-p9:192:256:256:32-p10:32:32-p11:32:32" - "-p12:32:32-p13:32:32-p14:32:32-p15:32:32-i64:64-v16:16-v24:32" - "-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048" - "-n32:64-S32-A5-G1-ni:7:8:9" -) -_TRIPLE = "amdgcn-amd-amdhsa" - - -# A small set of AMDGPU intrinsic signatures changed between LLVM 20 -# (ROCm 7.0/7.1) and LLVM 21+ (ROCm 7.2 ships LLVM 22): -# -# * ``make.buffer.rsrc.p1`` -> ``make.buffer.rsrc.p8.p1`` and the -# ``num_records`` arg widened from ``i32`` to ``i64`` (LLVM PR -# #126828). -# * fp8 / bf8 MFMA A/B operands collapsed from ``<2 x i32>`` to a -# scalar ``i64`` (same 64 bits, different LLVM type). -# -# comgr verifies the toplevel ``declare`` lines BEFORE running the -# auto-upgrade pass, so we have to emit the right signature up front. -# Resolve from the loaded compiler when lowering; ``lower_kernel_to_llvm`` -# also accepts an explicit ``llvm_flavor=`` for offline emission. -LLVM_FLAVOR_LLVM20 = "llvm20" -LLVM_FLAVOR_LLVM22 = "llvm22" -LLVM_FLAVOR_LLVM23 = "llvm23" - -# Every flavor rocke can emit, oldest first. This is the SSOT every flavor -# membership test must go through -- validating against a hand-rolled tuple is -# how ``llvm23`` was silently rejected by the C++ backend path while the Python -# path accepted it. ``test_no_hand_rolled_flavor_membership_lists`` pins that no -# such private list reappears, and -# ``test_cpp_engine_accepts_exactly_the_python_flavor_set`` pins that the C++ -# engine's ladder still matches this tuple. -LLVM_FLAVORS: Tuple[str, ...] = ( +from .llvm_profile import ( + LLVM_EMISSION_ALIASES, + LLVM_EMISSION_FLAVORS, LLVM_FLAVOR_LLVM20, LLVM_FLAVOR_LLVM22, LLVM_FLAVOR_LLVM23, + LLVM_FLAVOR_LLVM24, + LLVM_FLAVORS, + LlvmDatalayoutKind, + _DATALAYOUT_KIND_FLAVORS, + _DATALAYOUT_LLVM20, + _DATALAYOUT_LLVM22, + _DATALAYOUT_LLVM23, + _LLVM_EMISSION_PROFILES, + _LlvmDeclarationAbi, + _LlvmEmissionCapability, + _TRIPLE, + _datalayout_for_flavor, + _datalayout_kind_for_flavor, + _datalayout_kind_from_ir, + _emission_profile, + _flavor_at_least, + _flavor_for_llvm, + _is_modern_flavor, + _supports_llvm23_target_ops, ) @@ -277,119 +184,6 @@ def __reduce__(self): ) -class LlvmDatalayoutKind(enum.Enum): - """Datalayout generation, i.e. what an IR module's ``p8`` field reveals. - - Two datalayout fields drift between flavors -- the buffer-resource address - space ``p8`` shape and the ELF mangling spec ``m:e`` -- but only ``p8`` - partitions the flavors into the *generation* that gates intrinsic-declare - compatibility (``make.buffer.rsrc.p8.p1``, fp8/bf8 MFMA operand widths). So - this kind groups flavors by p8 shape, NOT by full datalayout identity: - llvm22 and llvm23 share a generation yet differ in ``m:e`` (llvm23 has it), - so the datalayout alone still cannot narrow to a single flavor. - - Members are named after the datalayout shape, deliberately not after its - recency: a "modern" label stops being true the moment a newer generation - lands, whereas ``P8_INDEXED`` keeps describing exactly what it matches. - """ - - #: LLVM 20 and older: ``p8:128:128`` (no index-width field). - P8_PLAIN = "p8_plain" - #: LLVM 21+: ``p8:128:128:128:48`` (index width appended). - P8_INDEXED = "p8_indexed" - - @property - def flavors(self) -> FrozenSet[str]: - """Flavors that emit this datalayout generation.""" - return _DATALAYOUT_KIND_FLAVORS[self] - - def describe(self) -> str: - """Human-readable form for diagnostics, e.g. ``p8_indexed (llvm22/llvm23)``.""" - return f"{self.value} ({'/'.join(sorted(self.flavors))})" - - -# Partition of :data:`LLVM_FLAVORS` by datalayout generation. Every flavor must -# appear in exactly one entry, and every enum member must have an entry; -# ``test_datalayout_kinds_partition_every_flavor`` is the exhaustiveness check a -# language-level ``match`` would give for free. -_DATALAYOUT_KIND_FLAVORS: Dict[LlvmDatalayoutKind, FrozenSet[str]] = { - LlvmDatalayoutKind.P8_PLAIN: frozenset({LLVM_FLAVOR_LLVM20}), - LlvmDatalayoutKind.P8_INDEXED: frozenset({LLVM_FLAVOR_LLVM22, LLVM_FLAVOR_LLVM23}), -} - -# Substrings that identify each generation in a module's ``target datalayout``. -# Kept consistent with the ``_DATALAYOUT_*`` constants by -# ``test_datalayout_kind_markers_match_datalayouts``. -_P8_MARKERS: Dict[LlvmDatalayoutKind, str] = { - LlvmDatalayoutKind.P8_INDEXED: "p8:128:128:128:48", - LlvmDatalayoutKind.P8_PLAIN: "p8:128:128-", -} - - -def _datalayout_kind_for_flavor(flavor: str) -> Optional[LlvmDatalayoutKind]: - """Datalayout generation a flavor emits, or ``None`` if unrecognised.""" - for kind, flavors in _DATALAYOUT_KIND_FLAVORS.items(): - if flavor in flavors: - return kind - return None - - -def _datalayout_kind_from_ir(ir_text: str) -> Optional[LlvmDatalayoutKind]: - """Datalayout generation of an IR module, read from its ``p8`` field. - - ``None`` when the module has no recognisable ``target datalayout``. This - cannot narrow to a single flavor -- see :class:`LlvmDatalayoutKind`. - """ - # P8_INDEXED first: its marker has the plain form as a prefix. - for kind in (LlvmDatalayoutKind.P8_INDEXED, LlvmDatalayoutKind.P8_PLAIN): - if _P8_MARKERS[kind] in ir_text: - return kind - return None - - -def _is_modern_flavor(flavor: str) -> bool: - """True for flavors emitting the LLVM 21+ ``p8`` shape (llvm22 / llvm23).""" - return flavor in _DATALAYOUT_KIND_FLAVORS[LlvmDatalayoutKind.P8_INDEXED] - - -def _datalayout_for_flavor(flavor: str) -> str: - """Module ``target datalayout`` string for an LLVM flavor. - - Two fields drift between flavors: the buffer-resource address space ``p8`` - (the 128-bit buffer descriptor, not the ``p7`` fat pointer) gained an - index-width field in LLVM 22, and the ELF symbol-mangling spec ``m:e`` - (absent in LLVM 20 and LLVM 22) is present in LLVM 23 - (see :data:`_DATALAYOUT_LLVM20` / :data:`_DATALAYOUT_LLVM22` / - :data:`_DATALAYOUT_LLVM23`). LLVM22 is the default for unknown values so a - typo'd override degrades to the modern layout rather than the legacy one. - """ - if flavor == LLVM_FLAVOR_LLVM20: - return _DATALAYOUT_LLVM20 - if flavor == LLVM_FLAVOR_LLVM23: - return _DATALAYOUT_LLVM23 - return _DATALAYOUT_LLVM22 - - -def _flavor_for_llvm(major: int) -> str: - """Map the loaded compiler's LLVM major to an existing emission flavor. - - LLVM 21 introduced the indexed-p8 generation represented by llvm22. - Newer compilers use the latest known flavor; this mapping does not claim - that every build of an LLVM major has an identical DataLayout. - """ - for minimum, flavor in reversed(_LLVM_FLAVOR_LADDER): - if major >= minimum: - return flavor - return LLVM_FLAVORS[0] - - -_LLVM_FLAVOR_LADDER: tuple[tuple[int, str], ...] = ( - (0, LLVM_FLAVOR_LLVM20), - (21, LLVM_FLAVOR_LLVM22), - (23, LLVM_FLAVOR_LLVM23), -) - - def _detect_llvm_flavor() -> str: """Choose an explicit flavor or query the compiler loaded by COMGR. @@ -403,7 +197,7 @@ def _detect_llvm_flavor() -> str: silently falling back to auto-detection -- a typo'd override otherwise looks like it pinned a flavor while actually asking COMGR to guess. """ - env = os.environ.get("ROCKE_LLVM_FLAVOR", "").strip().lower() + env = os.environ.get("ROCKE_LLVM_FLAVOR", "") if env: if env not in LLVM_FLAVORS: raise ValueError( @@ -1200,9 +994,10 @@ def _decls_for_flavor(flavor: str) -> Dict[str, str]: lowerer to ask. """ decls = dict(_INTRINSIC_DECLS) - if flavor == LLVM_FLAVOR_LLVM22: + abi = _emission_profile(flavor).declaration_abi + if abi is _LlvmDeclarationAbi.LLVM22: decls.update(_INTRINSIC_DECLS_LLVM22_OVERRIDES) - elif flavor == LLVM_FLAVOR_LLVM23: + elif abi is _LlvmDeclarationAbi.LLVM23: decls.update(_INTRINSIC_DECLS_LLVM23_OVERRIDES) return decls @@ -2072,16 +1867,17 @@ def _check_arch_domain(self, key: str) -> None: table = arch_domain.load(self._flavor) if table is None: return + flavor = table.flavor arch = self._backend.arch.gfx cell = table.lookup(key, arch) if cell is None or not arch_domain.is_negative(cell.status): return - waived = arch_domain.is_waived(key, arch, self._flavor) + waived = arch_domain.is_waived(key, arch, flavor) if mode == arch_domain.MODE_ERROR and not waived: - raise ArchDomainError(key, arch, self._flavor, cell.status, cell.evidence) + raise ArchDomainError(key, arch, flavor, cell.status, cell.evidence) warnings.warn( ArchDomainWarning( - key, arch, self._flavor, cell.status, cell.evidence, waived=waived + key, arch, flavor, cell.status, cell.evidence, waived=waived ), stacklevel=3, ) @@ -2118,17 +1914,18 @@ def _require_fp8_scale_conversion( ) def _require_llvm23_target_fact(self, op: str, fact: _OpTargetFact) -> None: - """Reject an LLVM-23-only operation unless the target records ``fact``. + """Require the LLVM23-generation target-op profile and target fact. - The rule reads the target's facts, never its name, so a target whose - row records the fact lowers the operation with no code change. + The profile capability is shared by the qualified LLVM23 and LLVM24 + lanes. The target rule reads facts, never a target name, so a new target + whose row records the fact needs no lowering change. """ arch = self._backend.arch if not fact.holds_for(arch): raise ValueError( f"{op} requires a target with {fact.value}, got {arch.gfx}" ) - if self._flavor != LLVM_FLAVOR_LLVM23: + if not _supports_llvm23_target_ops(self._flavor): raise ValueError(f"{op} requires LLVM flavor llvm23, got {self._flavor}") # ----- constant folding helpers ----- @@ -5322,6 +5119,12 @@ def _op_tile_inline_asm(self, op: Op) -> None: """ required_arch = op.attrs.get("required_arch") required_flavor = op.attrs.get("required_llvm_flavor") + minimum_flavor = op.attrs.get("minimum_llvm_flavor") + if minimum_flavor is not None and not isinstance(minimum_flavor, str): + raise TypeError( + "tile.inline_asm failed - minimum_llvm_flavor has a non-string " + "value, expected a string" + ) if required_arch is not None and self._backend.arch.gfx != required_arch: raise ValueError( f"tile.inline_asm requires {required_arch}, got {self._backend.arch.gfx}" @@ -5331,6 +5134,13 @@ def _op_tile_inline_asm(self, op: Op) -> None: f"tile.inline_asm requires LLVM flavor {required_flavor}, " f"got {self._flavor}" ) + if minimum_flavor is not None and not _flavor_at_least( + self._flavor, minimum_flavor + ): + raise ValueError( + f"tile.inline_asm requires LLVM flavor {minimum_flavor}, " + f"got {self._flavor}" + ) template = _escape_llvm_asm_string(op.attrs["template"]) constraints = op.attrs["constraints"] flags = [] @@ -7591,7 +7401,8 @@ def lower_kernel_to_llvm( ``llvm_flavor`` overrides the autodetected default (one of :data:`LLVM_FLAVOR_LLVM20` / :data:`LLVM_FLAVOR_LLVM22` / - :data:`LLVM_FLAVOR_LLVM23`). Useful for tests that want to pin a + :data:`LLVM_FLAVOR_LLVM23` / :data:`LLVM_FLAVOR_LLVM24`). Useful for tests + that want to pin a specific flavor regardless of the host ROCm install. ``arch`` selects the ISA backend (e.g. ``"gfx942"``, ``"gfx950"``) that diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/runtime/comgr.py b/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/runtime/comgr.py index 35ac47bf1d27..6c06f6ab9886 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/runtime/comgr.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/python/rocke/runtime/comgr.py @@ -46,7 +46,6 @@ _rocm_sdk_core_release, ) - # Status codes. AMD_COMGR_STATUS_SUCCESS = 0 @@ -473,17 +472,20 @@ def _assert_ir_flavor_matches_lib(ir_text: str) -> None: not change the compiler that will consume it. Unknown compiler evidence is an error; with a known compiler, unrecognised IR layouts are left to COMGR. """ - from ..core.lower_llvm import ( + from ..core.llvm_profile import ( _datalayout_kind_for_flavor, _datalayout_kind_from_ir, _flavor_for_llvm, ) info = _require_compiler_info() + try: + lib_flavor = _flavor_for_llvm(info.llvm_version[0]) + except ValueError as exc: + raise ComgrError(f"{exc}: {info.describe()}") from exc ir_kind = _datalayout_kind_from_ir(ir_text) if ir_kind is None: return - lib_flavor = _flavor_for_llvm(info.llvm_version[0]) lib_kind = _datalayout_kind_for_flavor(lib_flavor) if lib_kind is None or lib_kind is ir_kind: return diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/flavor_datalayout_ssot.cpp b/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/flavor_datalayout_ssot.cpp index f1138fdad3d8..c36a5feb4eff 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/flavor_datalayout_ssot.cpp +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/flavor_datalayout_ssot.cpp @@ -1,20 +1,13 @@ // Copyright (c) Advanced Micro Devices, Inc., or its affiliates. // SPDX-License-Identifier: MIT /* - * tests/core/flavor_datalayout_ssot.cpp -- host unit test holding the two - * C-side flavor->datalayout tables together. + * tests/core/flavor_datalayout_ssot.cpp -- host unit test holding the C-side + * compiler-lane and structural emission-profile APIs together. * - * The engine answers "what datalayout does this LLVM flavor use?" in two - * places: rocke_isa_datalayout_for_flavor (isa/backend.cpp, the ISA-layer - * accessor the standalone C emitters call) and rocke_ll_datalayout_for_flavor - * (lower_llvm/data.cpp, what the lowerer stamps into the module header). - * Python has one function, _datalayout_for_flavor, that both of its layers - * call. Two copies of a string table is a drift hazard with no natural - * failure: an llvm23 branch missing from one table can emit IR that differs - * only in a field the runtime tolerates today and is silently wrong the day a - * stricter path (bitcode, a tighter verifier) rejects it. This test makes the - * two agree by construction over the whole flavor ladder, so adding a rung or - * changing a layout has to be done in both places. + * The ISA accessor delegates to the lowerer's profile resolver so there is one + * C-side datalayout table. This test walks every public lane and proves that the + * API layers resolve the same layout and that each profile's structural fields + * agree with the rendered string. * * Plain executable: returns non-zero on the first failed check (a clean run is * the pass criterion). Registered via tests/CMakeLists.txt so it is installed @@ -22,11 +15,18 @@ */ #include #include +#include #include "rocke/isa_backend.h" #include "rocke/lower_llvm.h" #include "rocke/lower_llvm_internal.h" +static_assert(ROCKE_LLVM_FLAVOR_AUTO == 0); +static_assert(ROCKE_LLVM_FLAVOR_LLVM20 == 1); +static_assert(ROCKE_LLVM_FLAVOR_LLVM22 == 2); +static_assert(ROCKE_LLVM_FLAVOR_LLVM23 == 3); +static_assert(ROCKE_LLVM_FLAVOR_LLVM24 == 4); + static int g_failures = 0; #define CHECK(cond, msg) \ @@ -49,6 +49,17 @@ int main(void) CHECK(err == NULL, "gfx950 must resolve to an ISA backend"); CHECK(n > 0, "the flavor ladder must be non-empty"); + rocke_strbuf_t preamble = {}; + CHECK(rocke_strbuf_init(&preamble, 32) == 0, "preamble buffer initializes"); + CHECK(rocke_strbuf_append(&preamble, "stale") == 0, "preamble buffer accepts a sentinel"); + CHECK(rocke_isa_module_preamble_for_flavor(&be, ROCKE_LLVM_FLAVOR_AUTO, &preamble) == -1, + "AUTO is not a concrete preamble flavor"); + CHECK(strcmp(rocke_strbuf_cstr(&preamble), "") == 0, + "a rejected preamble leaves no malformed IR"); + CHECK(rocke_isa_module_preamble_for_flavor(&be, (rocke_llvm_flavor_t)99, &preamble) == -1, + "an out-of-range preamble flavor is rejected"); + rocke_strbuf_free(&preamble); + for(i = 0; i < n; ++i) { const char* name = rocke_llvm_flavor_at(i); @@ -91,18 +102,56 @@ int main(void) } /* The ELF symbol-mangling spec m:e is the second drift axis, orthogonal to - * p8: absent in LLVM 20 / 22, present in LLVM 23. Pin it per flavor so a - * wrong or missing m:e is caught here with an explanation -- the same guard - * the p8 field gets above -- instead of surfacing as golden hash churn. */ + * p8. Pin it to the structural profile rather than compiler-lane names. */ for(i = 0; i < n; ++i) { const char* name = rocke_llvm_flavor_at(i); rocke_llvm_flavor_t f = rocke_llvm_flavor_from_name(name); const char* dl = ckc::rocke_ll_datalayout_for_flavor(f); - bool want_me = (f == ROCKE_LLVM_FLAVOR_LLVM23); + const ckc::rocke_ll_emission_profile_t* profile = ckc::rocke_ll_emission_profile(f); + bool want_me = profile && profile->datalayout == ckc::ROCKE_LL_DATALAYOUT_PROFILE_LLVM23; bool has_me = dl != NULL && strstr(dl, "-m:e-") != NULL; - CHECK(dl != NULL && has_me == want_me, name); + CHECK(profile != NULL && dl != NULL && has_me == want_me, name); + } + + const ckc::rocke_ll_emission_profile_t* llvm23 + = ckc::rocke_ll_emission_profile(ROCKE_LLVM_FLAVOR_LLVM23); + const ckc::rocke_ll_emission_profile_t* llvm24 + = ckc::rocke_ll_emission_profile(ROCKE_LLVM_FLAVOR_LLVM24); + CHECK(llvm23 != NULL && llvm23 == llvm24, "llvm23 and llvm24 share one emission profile"); + CHECK(ckc::rocke_ll_profile_has(ROCKE_LLVM_FLAVOR_LLVM24, ckc::ROCKE_LL_CAP_LLVM23_TARGET_OPS), + "llvm24 admits LLVM23-generation target operations"); + CHECK(ckc::rocke_ll_flavor_for_llvm_major(23) == ROCKE_LLVM_FLAVOR_LLVM23, + "LLVM 23 resolves to llvm23"); + CHECK(ckc::rocke_ll_flavor_for_llvm_major(24) == ROCKE_LLVM_FLAVOR_LLVM24, + "LLVM 24 resolves to llvm24"); + + try + { + (void)ckc::rocke_ll_flavor_for_llvm_major(25); + CHECK(false, "an unqualified future compiler major must fail"); + } + catch(const std::exception& error) + { + CHECK(strstr(error.what(), "latest qualified lane llvm24") != NULL, + "future-major failure names the qualification frontier"); + } + const char* invalid_flavors[] = {"llvm25", "LLVM24", " llvm24 "}; + for(const char* invalid : invalid_flavors) + { + try + { + (void)ckc::rocke_ll_explicit_flavor(invalid); + CHECK(false, "an unknown explicit flavor must fail"); + } + catch(const std::exception& error) + { + CHECK(strstr(error.what(), invalid) != NULL, + "unknown explicit-flavor failure names the bad value"); + CHECK(strstr(error.what(), "expected one of") != NULL, + "unknown explicit-flavor failure lists qualified lanes"); + } } if(g_failures == 0) diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/future_intrinsic_lowering.cpp b/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/future_intrinsic_lowering.cpp index 2a8840d6ccf7..03b108376308 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/future_intrinsic_lowering.cpp +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/future_intrinsic_lowering.cpp @@ -144,36 +144,37 @@ rocke_value_t* global_ptr_param(rocke_ir_builder_t* b, const char* name, const r void case_gfx1250_standalone_bridge() { - const std::string ir = lower_one( - "gfx1250_bridge", - [](rocke_ir_builder_t* b) { - const int shape[] = {1}; - rocke_value_t* dst = global_ptr_param(b, "dst", rocke_i16()); - rocke_value_t* smem = rocke_b_smem_alloc(b, rocke_i64(), shape, 1, "barrier"); - rocke_value_t* local = rocke_b_smem_addr_of(b, smem); - rocke_value_t* members = rocke_b_const_i32(b, 2); - rocke_value_t* d4 = rocke_b_zero_vec(b, rocke_i32(), 4); - rocke_value_t* d8 = rocke_b_zero_vec(b, rocke_i32(), 8); - - rocke_b_s_wait_tensorcnt(b, 3); - rocke_b_s_barrier_signal(b, 1); - rocke_b_s_barrier_wait(b, 2); - rocke_b_s_barrier_init(b, local, members); - rocke_b_s_barrier_signal_var(b, local, members); - rocke_b_s_barrier_join(b, local); - rocke_b_s_wakeup_barrier(b, local); - rocke_b_s_barrier_leave(b, 4); - rocke_b_s_delay_alu(b, 0x1234); - rocke_b_s_wait_alu(b, 0x2345); - rocke_b_s_clause(b, 0x3456); - rocke_b_s_wait_xcnt(b, 0x4567); - rocke_b_global_store_async_from_lds(b, dst, local, 16, -4, 31); - rocke_b_global_load_tr16_b128(b, dst, rocke_i16()); - rocke_b_tensor_load_to_lds(b, d4, d8, d4, d4, d8, 5); - rocke_b_tensor_store_from_lds(b, d4, d8, d4, d4, d8, 6); - }, - "gfx1250", - ROCKE_LLVM_FLAVOR_LLVM23); + const auto build = [](rocke_ir_builder_t* b) { + const int shape[] = {1}; + rocke_value_t* dst = global_ptr_param(b, "dst", rocke_i16()); + rocke_value_t* smem = rocke_b_smem_alloc(b, rocke_i64(), shape, 1, "barrier"); + rocke_value_t* local = rocke_b_smem_addr_of(b, smem); + rocke_value_t* members = rocke_b_const_i32(b, 2); + rocke_value_t* d4 = rocke_b_zero_vec(b, rocke_i32(), 4); + rocke_value_t* d8 = rocke_b_zero_vec(b, rocke_i32(), 8); + + rocke_b_s_wait_tensorcnt(b, 3); + rocke_b_s_barrier_signal(b, 1); + rocke_b_s_barrier_wait(b, 2); + rocke_b_s_barrier_init(b, local, members); + rocke_b_s_barrier_signal_var(b, local, members); + rocke_b_s_barrier_join(b, local); + rocke_b_s_wakeup_barrier(b, local); + rocke_b_s_barrier_leave(b, 4); + rocke_b_s_delay_alu(b, 0x1234); + rocke_b_s_wait_alu(b, 0x2345); + rocke_b_s_clause(b, 0x3456); + rocke_b_s_wait_xcnt(b, 0x4567); + rocke_b_global_store_async_from_lds(b, dst, local, 16, -4, 31); + rocke_b_global_load_tr16_b128(b, dst, rocke_i16()); + rocke_b_tensor_load_to_lds(b, d4, d8, d4, d4, d8, 5); + rocke_b_tensor_store_from_lds(b, d4, d8, d4, d4, d8, 6); + }; + const std::string ir = lower_one("gfx1250_bridge", build, "gfx1250", ROCKE_LLVM_FLAVOR_LLVM23); + const std::string ir24 + = lower_one("gfx1250_bridge", build, "gfx1250", ROCKE_LLVM_FLAVOR_LLVM24); + if(ir24 != ir) + fail("LLVM24 bridge output differs from its shared LLVM23 profile", __LINE__); EXPECT_IR(ir, "call void @llvm.amdgcn.s.wait.tensorcnt(i16 3)"); EXPECT_IR(ir, "call void @llvm.amdgcn.s.barrier.signal(i32 1)"); @@ -188,6 +189,60 @@ void case_gfx1250_standalone_bridge() EXPECT_IR(ir, "call void @llvm.amdgcn.tensor.store.from.lds("); } +void case_inline_asm_rejects_non_string_minimum_flavor() +{ + rocke_ir_builder_t b; + if(rocke_ir_builder_init(&b, "malformed_minimum_flavor") != ROCKE_OK) + { + fail("rocke_ir_builder_init", __LINE__); + return; + } + rocke_value_t* operand = rocke_b_const_i32(&b, 0); + rocke_value_t* operands[] = {operand}; + const rocke_type_t* result_types[] = {rocke_i32()}; + rocke_op_t* op + = rocke_b_inline_asm(&b, "v_mov_b32 $0, $1", "=v,v", operands, 1, result_types, 1, nullptr); + rocke_attr_set_int(&b, &op->attrs, "minimum_llvm_flavor", 23); + rocke_b_ret(&b); + + char* ll = nullptr; + char err[ROCKE_ERR_MSG_CAP]; + err[0] = '\0'; + const rocke_status_t st = rocke_lower_kernel_to_llvm_ex( + rocke_ir_builder_kernel(&b), ROCKE_LLVM_FLAVOR_LLVM20, "gfx950", &ll, err, sizeof(err)); + if(st != ROCKE_ERR_TYPE) + fail("non-string minimum_llvm_flavor did not return ROCKE_ERR_TYPE", __LINE__); + const char* expected + = "tile.inline_asm failed - minimum_llvm_flavor has a non-string value, expected a string"; + if(strcmp(err, expected) != 0) + fail("non-string minimum_llvm_flavor diagnostic changed", __LINE__); + std::free(ll); + rocke_ir_builder_free(&b); +} + +void case_scaled_mfma_shared_profile() +{ + const auto build = [](rocke_ir_builder_t* b) { + rocke_value_t* a = rocke_b_zero_vec(b, rocke_i32(), 8); + rocke_value_t* bb = rocke_b_zero_vec(b, rocke_i32(), 8); + rocke_value_t* c = rocke_b_zero_vec(b, rocke_f32(), 4); + rocke_value_t* a_scale = rocke_b_const_i32(b, 3); + rocke_value_t* b_scale = rocke_b_const_i32(b, 5); + rocke_b_mfma_scale_f32_16x16x128_f8f6f4(b, a, bb, c, a_scale, b_scale); + }; + const std::string ir23 + = lower_one("scaled_mfma_profile", build, "gfx950", ROCKE_LLVM_FLAVOR_LLVM23); + const std::string ir24 + = lower_one("scaled_mfma_profile", build, "gfx950", ROCKE_LLVM_FLAVOR_LLVM24); + if(ir24 != ir23) + fail("LLVM24 scaled-MFMA output differs from its shared LLVM23 profile", __LINE__); + EXPECT_IR(ir24, + "declare <4 x float> " + "@llvm.amdgcn.mfma.scale.f32.16x16x128.f8f6f4.v8i32.v8i32(" + "<8 x i32>, <8 x i32>, <4 x float>, i32 immarg, i32 immarg, " + "i32 immarg, i32, i32 immarg, i32)"); +} + /* Build one kernel and return the C++ engine's HIP source. */ template std::string lower_one_hip(const char* name, BuildFn build) @@ -3389,6 +3444,7 @@ struct TestCase }; const TestCase k_cases[] = { + {"scaled_mfma_shared_profile", case_scaled_mfma_shared_profile}, {"lowbit_dtype_aliases", case_lowbit_dtype_aliases}, {"wmma_result_count", case_wmma_result_count}, {"ds_swizzle_raw_offset", case_ds_swizzle_raw_offset}, @@ -3462,6 +3518,8 @@ const TestCase k_cases[] = { {"hip_zext_uses_unsigned_source_cast", case_hip_zext_uses_unsigned_source_cast}, {"gfx1250_scaled_wmma", case_gfx1250_scaled_wmma}, {"gfx1250_standalone_bridge", case_gfx1250_standalone_bridge}, + {"inline_asm_rejects_non_string_minimum_flavor", + case_inline_asm_rejects_non_string_minimum_flavor}, {"flag_ops", case_flag_ops}, {"fence_system_scope", case_fence_system_scope}, {"flag_ops_hip", case_flag_ops_hip}, diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/test_arch_domain_lane.py b/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/test_arch_domain_lane.py index c678eb4f77df..a0701d37ed5d 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/test_arch_domain_lane.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/test_arch_domain_lane.py @@ -74,6 +74,27 @@ def test_at_least_one_column_is_committed() -> None: assert _committed_flavors(), "no committed arch-domain column to test against" +def test_every_lane_has_a_column_or_an_alias() -> None: + """A lane with neither would silently run without the qualification gate.""" + from rocke.core.lower_llvm import LLVM_FLAVORS + + assert [flavor for flavor in LLVM_FLAVORS if arch_domain.load(flavor) is None] == [] + + +def test_a_column_alias_borrows_its_emission_alias_and_retires() -> None: + """An alias follows profile sharing and disappears when its own column lands.""" + from rocke.core.llvm_profile import LLVM_EMISSION_ALIASES + + committed = set(arch_domain.committed_flavors()) + for lane, source in arch_domain.COLUMN_ALIASES.items(): + assert LLVM_EMISSION_ALIASES.get(lane) == source, lane + assert source in committed, lane + assert lane not in committed, f"{lane} has its own column; drop the alias" + table = arch_domain.load(lane) + assert table is arch_domain.load(source) + assert table.flavor == source + + def test_only_arch_absent_is_negative() -> None: for status in ( arch_domain.STATUS_OK, @@ -805,6 +826,25 @@ def _lower_dpp8(flavor: str) -> str: ) +def test_a_borrowing_lane_refuses_at_its_source( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A borrowed column keeps Python and C++ diagnostics on its source lane.""" + monkeypatch.setenv(arch_domain.MODE_ENV, "error") + tested: list[str] = [] + for lane, source in arch_domain.COLUMN_ALIASES.items(): + table = arch_domain.load(source) + assert table is not None + cell = table.lookup(_DPP8_KEY, _DPP8_ARCH) + if cell is None or not arch_domain.is_negative(cell.status): + continue + with pytest.raises(ArchDomainError) as refused: + _lower_dpp8(lane) + assert refused.value.flavor == source, lane + tested.append(lane) + assert tested, "no borrowing lane had the negative test cell" + + def _waive(monkeypatch: pytest.MonkeyPatch, *cells: tuple[str, str, str]) -> None: table = {c: arch_domain.Waiver(*c, "test: the measurement is wrong") for c in cells} monkeypatch.setattr(arch_domain, "waivers", lambda: table) diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/test_arch_domain_refusal.cpp b/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/test_arch_domain_refusal.cpp index 0b984fd6b649..ab5c9e52df79 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/test_arch_domain_refusal.cpp +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/test_arch_domain_refusal.cpp @@ -252,6 +252,47 @@ void test_lowering(const char* flavor, const rocke_arch_domain_cell_t* cell) set_mode(nullptr); } +/* Every qualified lane resolves to its own column or a declared alias. */ +void test_every_lane_has_a_column() +{ + for(int i = 0; i < rocke_llvm_flavor_count(); ++i) + { + const char* lane = rocke_llvm_flavor_at(i); + size_t count = 0; + (void)rocke_arch_domain_column(lane, &count); + EXPECT(count > 0, std::string("no arch-domain column for lane ") + lane); + } +} + +/* A borrowing lane refuses as its source and names that source in the message. */ +void test_a_borrowing_lane_refuses_as_its_source() +{ + bool tested = false; + for(int i = 0; i < rocke_llvm_flavor_count(); ++i) + { + const char* lane = rocke_llvm_flavor_at(i); + const char* source = rocke_arch_domain_column_flavor(lane); + if(std::strcmp(source, lane) == 0) + { + continue; + } + const rocke_arch_domain_cell_t* cell = rocke_arch_domain_negative(source, kKey, kArch); + if(cell == nullptr || cell->waived) + { + continue; + } + char want[ROCKE_ERR_MSG_CAP]; + rocke_arch_domain_message(cell, source, want, sizeof want); + set_mode("error"); + Lowered refused = lower_dpp8(lane); + EXPECT(refused.status == ROCKE_ERR_ARCH_DOMAIN && refused.text == want, + std::string(lane) + " refuses as " + source + ": " + refused.text); + tested = true; + set_mode(nullptr); + } + EXPECT(tested, "no borrowing lane had the negative test cell"); +} + } // namespace int main() @@ -259,6 +300,8 @@ int main() test_mode_parsing(); test_message_cap(); test_message_text(); + test_every_lane_has_a_column(); + test_a_borrowing_lane_refuses_as_its_source(); const rocke_arch_domain_cell_t* cell = nullptr; const char* flavor = refusing_flavor(&cell); diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/test_gfx1250_llvm_bridge.py b/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/test_gfx1250_llvm_bridge.py index ca9de3907708..5646557bc4ba 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/test_gfx1250_llvm_bridge.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/test_gfx1250_llvm_bridge.py @@ -1,12 +1,13 @@ # Copyright (c) Advanced Micro Devices, Inc., or its affiliates. # SPDX-License-Identifier: MIT -"""Focused validation for the standalone gfx1250 LLVM 23 bridge.""" +"""Focused validation for the gfx1250 LLVM23-generation emission profile.""" from __future__ import annotations import unittest +from rocke.core.backend import BackendError, _lower_via_cpp_engine from rocke.core.ir import F32, I16, I32, I64, IRBuilder, PtrType from rocke.core.ir_serialize import parse, serialize from rocke.core.lower_llvm import _lower_kernel_to_llvm_python @@ -54,6 +55,7 @@ def _lower(kernel, *, arch="gfx1250", flavor="llvm23"): class TestGfx1250LlvmBridge(unittest.TestCase): def test_exact_control_intrinsics_and_inline_asm(self): llvm = _lower(_build_all()) + self.assertEqual(llvm, _lower(_build_all(), flavor="llvm24")) expected = ( "call void @llvm.amdgcn.s.wait.tensorcnt(i16 3)", "call void @llvm.amdgcn.s.barrier.signal(i32 1)", @@ -109,6 +111,36 @@ def test_serialization_roundtrip_preserves_all_ops(self): self.assertEqual(text, serialize(parsed)) self.assertEqual(_lower(kernel), _lower(parsed)) + def test_non_string_minimum_flavor_is_rejected_by_both_engines(self): + builder = IRBuilder("malformed_minimum_flavor") + value = builder.const_i32(0) + result = builder.inline_asm( + "v_mov_b32 $0, $1", + "=v,v", + [value], + result_type=I32, + sideeffect=True, + ) + result.op.attrs["minimum_llvm_flavor"] = 23 + builder.ret() + kernel = builder.kernel + message = ( + "tile.inline_asm failed - minimum_llvm_flavor has a non-string " + "value, expected a string" + ) + with self.assertRaisesRegex(TypeError, message): + _lower(kernel, flavor="llvm20") + + serialized = serialize(kernel) + try: + _lower_via_cpp_engine(serialized, "gfx1250", "llvm20") + except BackendError as exc: + self.skipTest(f"C++ engine unavailable: {exc}") + except RuntimeError as exc: + self.assertIn(message, str(exc)) + else: + self.fail("C++ engine accepted a non-string minimum_llvm_flavor") + def test_unsupported_arch_rejected(self): with self.assertRaisesRegex( ValueError, diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/test_gfx1250_scaled_wmma.py b/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/test_gfx1250_scaled_wmma.py index 2f5496aaa15f..73c7e7bdef7c 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/test_gfx1250_scaled_wmma.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/test_gfx1250_scaled_wmma.py @@ -204,7 +204,7 @@ def test_catalog_fragment_lengths(self): (op.a_frag_len, op.b_frag_len, op.c_frag_len), (16, 16, 8) ) - def test_scale_and_scale16_exact_llvm23_abi(self): + def test_scale_and_scale16_exact_modern_abi(self): cases = ( ( False, @@ -220,23 +220,24 @@ def test_scale_and_scale16_exact_llvm23_abi(self): "i64", ), ) - for scale16, intrinsic, scale_ty in cases: - with self.subTest(scale16=scale16): - ll = lower_kernel_to_llvm( - _build_scaled_atom(scale16=scale16), - llvm_flavor="llvm23", - arch="gfx1250", - ) - self.assertIn(f"declare <8 x float> @{intrinsic}", ll) - self.assertIn( - "i32 0, <16 x i32>", - next( - line - for line in ll.splitlines() - if f"call <8 x float> @{intrinsic}" in line - ), - ) - self.assertIn(f", {scale_ty} %", ll) + for flavor in ("llvm23", "llvm24"): + for scale16, intrinsic, scale_ty in cases: + with self.subTest(flavor=flavor, scale16=scale16): + ll = lower_kernel_to_llvm( + _build_scaled_atom(scale16=scale16), + llvm_flavor=flavor, + arch="gfx1250", + ) + self.assertIn(f"declare <8 x float> @{intrinsic}", ll) + self.assertIn( + "i32 0, <16 x i32>", + next( + line + for line in ll.splitlines() + if f"call <8 x float> @{intrinsic}" in line + ), + ) + self.assertIn(f", {scale_ty} %", ll) def test_scaled_wmma_rejects_pre_llvm23_flavors(self): # A native rejection is retried in Python unless strict C++ is requested. diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/test_ir_golden.py b/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/test_ir_golden.py index 5dd1fcfc057c..6c8a022a9c99 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/test_ir_golden.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/test_ir_golden.py @@ -3,8 +3,8 @@ """Tests for :mod:`rocke.core.ir_golden`, the shared all-flavor golden comparator. -The property that matters: a new entry in ``LLVM_FLAVORS`` needs no golden-test -edit, and every golden checked through ``check_golden`` fails until re-blessed. +A new compiler lane needs no golden-test edit: each golden must add either a +new profile baseline or an explicit alias to a structurally identical profile. """ from __future__ import annotations @@ -16,7 +16,13 @@ from unittest.mock import patch from rocke.core import ir_golden -from rocke.core.ir_golden import GOLDEN_FLAVORS, check_golden, compare +from rocke.core.ir_golden import ( + GOLDEN_ALIASES, + GOLDEN_FLAVORS, + GOLDEN_PROFILE_FLAVORS, + check_golden, + compare, +) from rocke.core.lower_llvm import LLVM_FLAVORS @@ -30,14 +36,21 @@ def setUp(self): self.addCleanup(tmp.cleanup) self.path = Path(tmp.name) / "golden.json" - def _write(self, flavors): - self.path.write_text(json.dumps({"flavors": {fl: _sub() for fl in flavors}})) + def _write(self, flavors, aliases=None): + self.path.write_text( + json.dumps( + { + "aliases": aliases or {}, + "flavors": {fl: _sub() for fl in flavors}, + } + ) + ) def test_golden_flavors_is_llvm_flavors(self): self.assertIs(GOLDEN_FLAVORS, LLVM_FLAVORS) def test_every_flavor_checked(self): - self._write(GOLDEN_FLAVORS) + self._write(GOLDEN_PROFILE_FLAVORS, GOLDEN_ALIASES) seen = [] def run(fl): @@ -47,21 +60,27 @@ def run(fl): self.assertEqual(check_golden(self.path, run), []) self.assertEqual(tuple(seen), GOLDEN_FLAVORS) - def test_new_flavor_fails_until_reblessed(self): - self._write(GOLDEN_FLAVORS) + def test_new_flavor_fails_until_profile_or_alias_is_declared(self): + self._write(GOLDEN_PROFILE_FLAVORS, GOLDEN_ALIASES) grown = GOLDEN_FLAVORS + ("llvm99",) with patch.object(ir_golden, "GOLDEN_FLAVORS", grown): errors = check_golden(self.path, lambda fl: _sub()) self.assertEqual(len(errors), 1) self.assertIn("'llvm99'", errors[0]) - self._write(grown) - self.assertEqual(check_golden(self.path, lambda fl: _sub()), []) - def test_stale_flavor_reported(self): - self._write(GOLDEN_FLAVORS + ("llvm19",)) + def test_shared_profile_alias_checks_the_requested_lane(self): + self._write(GOLDEN_PROFILE_FLAVORS, GOLDEN_ALIASES) + seen = [] + self.assertEqual( + check_golden(self.path, lambda fl: seen.append(fl) or _sub()), [] + ) + self.assertEqual(tuple(seen), GOLDEN_FLAVORS) + + def test_stale_profile_document_reported(self): + self._write(GOLDEN_PROFILE_FLAVORS + ("llvm19",), GOLDEN_ALIASES) errors = check_golden(self.path, lambda fl: _sub()) self.assertEqual(len(errors), 1) - self.assertIn("stale flavor 'llvm19'", errors[0]) + self.assertIn("profile documents", errors[0]) def test_single_flavor_ignores_others(self): self._write(GOLDEN_FLAVORS[:1]) @@ -70,11 +89,22 @@ def test_single_flavor_ignores_others(self): ) def test_drift_prefixed_by_flavor(self): - self._write(GOLDEN_FLAVORS) + self._write(GOLDEN_PROFILE_FLAVORS, GOLDEN_ALIASES) bad = GOLDEN_FLAVORS[-1] errors = check_golden(self.path, lambda fl: _sub("b" if fl == bad else "a")) self.assertEqual(errors, [f"[{bad}] k: a -> b"]) + def test_wrong_profile_alias_is_rejected(self): + self._write(GOLDEN_PROFILE_FLAVORS, {"llvm24": "llvm22"}) + errors = check_golden(self.path, lambda fl: _sub()) + self.assertEqual(len(errors), 1) + self.assertIn("do not match emission-profile aliases", errors[0]) + + def test_direct_and_aliased_lane_is_rejected(self): + self._write(GOLDEN_PROFILE_FLAVORS + ("llvm24",), GOLDEN_ALIASES) + errors = check_golden(self.path, lambda fl: _sub()) + self.assertTrue(any("both direct and aliased" in error for error in errors)) + def test_compare_case_sets_and_failures(self): base = { "cases": {"k": {"sha256": "a"}, "gone": {"sha256": "x"}}, diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/test_llvm24_profile.py b/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/test_llvm24_profile.py new file mode 100644 index 000000000000..bd9ae486698a --- /dev/null +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/core/test_llvm24_profile.py @@ -0,0 +1,45 @@ +# Copyright (c) Advanced Micro Devices, Inc., or its affiliates. +# SPDX-License-Identifier: MIT + +"""LLVM24 is a qualified compiler lane sharing LLVM23's emission profile.""" + +from __future__ import annotations + +import pytest + +from rocke.core import lower_llvm +from rocke.core.ir import IRBuilder + + +def test_lane_order_and_shared_profile() -> None: + assert lower_llvm.LLVM_FLAVORS == ("llvm20", "llvm22", "llvm23", "llvm24") + assert tuple(lower_llvm._LLVM_EMISSION_PROFILES) == lower_llvm.LLVM_FLAVORS + assert lower_llvm.LLVM_EMISSION_FLAVORS == ("llvm20", "llvm22", "llvm23") + assert lower_llvm.LLVM_EMISSION_ALIASES == {"llvm24": "llvm23"} + llvm23 = lower_llvm._emission_profile("llvm23") + llvm24 = lower_llvm._emission_profile("llvm24") + assert llvm24 is llvm23 + assert lower_llvm._datalayout_for_flavor("llvm24") == ( + lower_llvm._datalayout_for_flavor("llvm23") + ) + assert lower_llvm._decls_for_flavor("llvm24") == lower_llvm._decls_for_flavor( + "llvm23" + ) + assert lower_llvm._supports_llvm23_target_ops("llvm24") + + +def test_explicit_llvm24_emission_does_not_query_comgr(monkeypatch) -> None: + def reject_query() -> None: + raise AssertionError("queried COMGR") + + monkeypatch.setattr("rocke.runtime.comgr._require_compiler_info", reject_query) + builder = IRBuilder("llvm24_offline") + llvm = lower_llvm._lower_kernel_to_llvm_python( + builder.kernel, arch="gfx950", llvm_flavor="llvm24" + ) + assert lower_llvm._datalayout_for_flavor("llvm24") in llvm + + +def test_unknown_profile_fails_with_the_supported_lanes() -> None: + with pytest.raises(ValueError, match="unknown LLVM flavor 'llvm25'.*llvm24"): + lower_llvm._emission_profile("llvm25") diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/golden/rocke_representative_ir_sha256.json b/dnn-providers/hip-kernel-provider/rocke/platform/tests/golden/rocke_representative_ir_sha256.json index b3afb40ec9e3..48e2f1e3df1a 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/golden/rocke_representative_ir_sha256.json +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/golden/rocke_representative_ir_sha256.json @@ -1,4 +1,5 @@ { + "aliases": {"llvm24": "llvm23"}, "flavors": { "llvm20": { "cases": { diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/golden/README.md b/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/golden/README.md index fd12199b6b37..a30ab9479fc2 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/golden/README.md +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/golden/README.md @@ -8,9 +8,10 @@ way in both engines; this file can. It holds two kinds of hash (format: `golden_store.py`): -- `ll` -- the lowered LLVM IR text, **one section per LLVM flavor** (`llvm20`, `llvm22`, - `llvm23`). IR text differs between flavors, so a hash is only compared with one recorded for - the same flavor. +- `ll` -- the lowered LLVM IR text, **one section per distinct emission profile** + (`llvm20`, `llvm22`, `llvm23`). The top-level `aliases` map represents qualified lanes + that intentionally share a profile; `llvm24` resolves to the `llvm23` hashes while still + being lowered and checked as `llvm24`. - `ir_canonical` -- the canonical `ck.dsl.ir/v1` serialization (stable across SSA-id renumbering). It is produced before lowering and is the same in every flavor, so it has one section. @@ -19,7 +20,7 @@ It holds two kinds of hash (format: `golden_store.py`): ```bash cd tests/instances/differential -python3 run_diff.py --mode ll --python-only --check-golden --flavor llvm20,llvm22,llvm23 +python3 run_diff.py --mode ll --python-only --check-golden --flavor llvm20,llvm22,llvm23,llvm24 python3 run_diff.py --mode ir --canonical --python-only --check-golden ``` @@ -40,7 +41,7 @@ reported missing. It matches by substring (`--only conv_implicit_gemm` also sele ## Re-bless (only for a reviewed, intended output change) ```bash -python3 run_diff.py --mode ll --python-only --record-golden --flavor llvm20,llvm22,llvm23 +python3 run_diff.py --mode ll --python-only --record-golden --flavor llvm20,llvm22,llvm23,llvm24 python3 run_diff.py --mode ir --canonical --python-only --record-golden ``` diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/golden/llvm_gfx_all.json b/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/golden/llvm_gfx_all.json index 168a95b7ce71..8a1615cd161b 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/golden/llvm_gfx_all.json +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/golden/llvm_gfx_all.json @@ -1,4 +1,7 @@ { + "aliases": { + "llvm24": "llvm23" + }, "ir_canonical": { "add_rmsnorm2d_bf16": { "0": "77846fc7b98264e280640fc3615658606c05982646e8c56420623e78e602b9a9", @@ -1111,7 +1114,7 @@ "13": "7d38b252eb0695267deac5f8c1c91233c8a9a9343a1d1ae249483093dd509363", "14": "084a6844dd427c9479c46649c19b8da21ae57593dfaa72077c3422a7fea9f535", "15": "084a6844dd427c9479c46649c19b8da21ae57593dfaa72077c3422a7fea9f535", - "16": "a9205d0e7d0cc7a19a0a144600b1f825f253a8dbabab8d1f84fca42d2174245b", + "16": "4dc4291506da423579efad1bb5c6264f29424042c756e4575a2d793beb02b5c5", "17": "efd2f3b4ffe2f81622f6bbd5ad83da5bd8283a209e9d0e882a1e62b8ea498d24", "18": "33d0325ced3807bdf3dd3c6b7d1deb6a2c89d6be597ff9e8c6d4eb3bc80e515a", "19": "06eaa8b88be99be455e1d246ae36e0da05697b419c4347aaa7735b773c957449", diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/golden_store.py b/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/golden_store.py index 45ba232aaa4e..b559e0a49d01 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/golden_store.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/golden_store.py @@ -10,10 +10,11 @@ { "schema": 2, - "ll": { # LLVM IR text, one section per LLVM flavor + "aliases": {"llvm24": "llvm23"}, # lanes sharing an emission profile + "ll": { # LLVM IR text, one section per LLVM profile "llvm20": {"": {"": "", ...}, ...}, "llvm22": {...}, - "llvm23": {...} + "llvm23": {...} # llvm24 resolves through aliases }, "ir_canonical": { # canonical ck.dsl.ir: the same in every flavor "": {"": "", ...} @@ -77,6 +78,7 @@ def _check_section(kind: str, flavor: str | None) -> None: class GoldenStore: """The parsed golden: hashes for `ll` per flavor, and for `ir_canonical`.""" + aliases: dict[str, str] = field(default_factory=dict) ll: dict[str, FamilyShas] = field(default_factory=dict) ir_canonical: FamilyShas = field(default_factory=dict) @@ -97,15 +99,43 @@ def load(cls, path: Path) -> "GoldenStore": "format stored no LLVM flavor -- re-record it with run_diff.py " "--record-golden for each flavor" ) - unknown = sorted(set(document) - {"schema", *KINDS}) + unknown = sorted(set(document) - {"schema", "aliases", *KINDS}) if unknown: raise GoldenFormatError( f"golden file {path} has unknown sections {unknown}" ) - return cls(ll=document.get(LL, {}), ir_canonical=document.get(IR_CANONICAL, {})) + aliases = document.get("aliases", {}) + if not isinstance(aliases, dict) or not all( + isinstance(lane, str) and isinstance(source, str) + for lane, source in aliases.items() + ): + raise GoldenFormatError( + "golden aliases must map flavor strings to flavor strings" + ) + ll = document.get(LL, {}) + overlap = sorted(set(aliases) & set(ll)) + if overlap: + raise GoldenFormatError( + f"golden flavors are both direct and aliased: {overlap}" + ) + missing = sorted(source for source in aliases.values() if source not in ll) + if missing: + raise GoldenFormatError( + f"golden aliases name missing flavor sections: {missing}" + ) + return cls( + aliases=aliases, + ll=ll, + ir_canonical=document.get(IR_CANONICAL, {}), + ) def save(self, path: Path) -> None: - document = {"schema": SCHEMA, LL: self.ll, IR_CANONICAL: self.ir_canonical} + document = { + "schema": SCHEMA, + "aliases": self.aliases, + LL: self.ll, + IR_CANONICAL: self.ir_canonical, + } path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(document, indent=2, sort_keys=True) + "\n") @@ -114,7 +144,10 @@ def save(self, path: Path) -> None: def section(self, kind: str, flavor: str | None) -> FamilyShas: """The hashes for `kind`; `ll` needs the flavor, `ir_canonical` takes none.""" _check_section(kind, flavor) - return self.ll.get(flavor, {}) if kind == LL else self.ir_canonical + if kind == IR_CANONICAL: + return self.ir_canonical + source = self.aliases.get(flavor, flavor) + return self.ll.get(source, {}) def record( self, @@ -143,7 +176,8 @@ def record( else: merged.pop(family, None) if kind == LL: - self.ll[flavor] = merged + source = self.aliases.get(flavor, flavor) + self.ll[source] = merged else: self.ir_canonical = merged return sorted(set(before) - set(merged)) diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/run_diff.py b/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/run_diff.py index d923f30aeb23..08dba78c8830 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/run_diff.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/run_diff.py @@ -1057,6 +1057,18 @@ def _run_families( def main(): + """Run the CLI without leaking its pinned flavor to in-process callers.""" + previous_flavor = os.environ.get("ROCKE_LLVM_FLAVOR") + try: + return _main() + finally: + if previous_flavor is None: + os.environ.pop("ROCKE_LLVM_FLAVOR", None) + else: + os.environ["ROCKE_LLVM_FLAVOR"] = previous_flavor + + +def _main(): ap = argparse.ArgumentParser() ap.add_argument("--mode", default="ll", choices=["ll", "ir", "verify"]) ap.add_argument( diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/test_check_byte_identity_progress.py b/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/test_check_byte_identity_progress.py index f4f473708686..ccafdebf9484 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/test_check_byte_identity_progress.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/test_check_byte_identity_progress.py @@ -9,9 +9,12 @@ import pytest -@pytest.mark.parametrize(("flavor", "expected_gate_calls"), [(None, 2), ("llvm23", 1)]) +@pytest.mark.parametrize( + ("flavor", "supports_target_ops", "expected_gate_calls"), + [(None, False, 2), ("llvm23", True, 1), ("llvm24", True, 1)], +) def test_differential_gate_streams_unbuffered_progress( - monkeypatch, tmp_path, flavor, expected_gate_calls + monkeypatch, tmp_path, flavor, supports_target_ops, expected_gate_calls ): if flavor is None: monkeypatch.delenv("ROCKE_LLVM_FLAVOR", raising=False) @@ -34,6 +37,9 @@ def run(command, **kwargs): monkeypatch.setattr(module.subprocess, "run", run) monkeypatch.setattr(module, "_cxx", lambda: None) + monkeypatch.setattr( + module, "_selected_profile_supports_target_ops", lambda: supports_target_ops + ) monkeypatch.setattr( module.sys, "argv", @@ -43,8 +49,19 @@ def run(command, **kwargs): assert module.main() == 0 gate_calls = [call for call in calls if str(module.RUN_DIFF) in call[0]] assert len(gate_calls) == expected_gate_calls + if not supports_target_ops: + primary, supplemental = gate_calls + assert "--exclude" in primary[0] + assert module.TARGET_OP_PROFILE_FAMILIES[0] in primary[0] + assert supplemental[1]["env"]["ROCKE_LLVM_FLAVOR"] == "llvm23" + only_index = supplemental[0].index("--only") + supplemental_families = supplemental[0][only_index + 1].split(",") + assert module.GFX1250_FAMILY in supplemental_families + assert module.TARGET_OP_PROFILE_FAMILIES[0] in supplemental_families for command, kwargs in gate_calls: assert command[:3] == [module.sys.executable, "-u", str(module.RUN_DIFF)] + if supports_target_ops: + assert "--exclude" not in command assert "capture_output" not in kwargs assert "stdout" not in kwargs assert "stderr" not in kwargs diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/test_gate_verdict.py b/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/test_gate_verdict.py index d9ae7acfadc7..99262bff4def 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/test_gate_verdict.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/test_gate_verdict.py @@ -23,6 +23,7 @@ import hashlib import json +import os import subprocess import sys import threading @@ -774,7 +775,11 @@ def test_a_golden_record_keeps_the_families_it_excluded(self): return_value=({"kept": {"0": "new"}}, []), ): with mock.patch.object(sys, "argv", argv): - self.assertEqual(run_diff.main(), 0) + with mock.patch.dict( + os.environ, {"ROCKE_LLVM_FLAVOR": "llvm24"} + ): + self.assertEqual(run_diff.main(), 0) + self.assertEqual(os.environ["ROCKE_LLVM_FLAVOR"], "llvm24") recorded = run_diff.GoldenStore.load(golden).section(run_diff.LL, "llvm20") self.assertEqual(recorded, {"kept": {"0": "new"}, "left_out": {"0": "x"}}) diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/test_golden_store.py b/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/test_golden_store.py index 9cb297e1ea0b..41906c42915f 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/test_golden_store.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/differential/test_golden_store.py @@ -56,6 +56,38 @@ def test_a_missing_file_is_an_empty_store(tmp_path): assert store.section(IR_CANONICAL, None) == {} +def test_a_shared_profile_alias_resolves_and_records_its_source(tmp_path): + store = GoldenStore( + aliases={"llvm24": "llvm23"}, + ll={"llvm23": {"conv": {"0": "a23"}}}, + ) + assert store.section(LL, "llvm24") == {"conv": {"0": "a23"}} + store.record(LL, "llvm24", {"conv": {"0": "a24"}}) + assert store.ll == {"llvm23": {"conv": {"0": "a24"}}} + + store.save(tmp_path / "g.json") + loaded = GoldenStore.load(tmp_path / "g.json") + assert loaded.aliases == {"llvm24": "llvm23"} + assert loaded.section(LL, "llvm24") == {"conv": {"0": "a24"}} + + +def test_aliases_must_name_a_distinct_existing_section(tmp_path): + overlap = _write( + tmp_path / "overlap.json", + '{"schema": 2, "aliases": {"llvm24": "llvm23"}, ' + '"ll": {"llvm23": {}, "llvm24": {}}}', + ) + with pytest.raises(GoldenFormatError, match="both direct and aliased"): + GoldenStore.load(overlap) + + missing = _write( + tmp_path / "missing.json", + '{"schema": 2, "aliases": {"llvm24": "llvm23"}, "ll": {}}', + ) + with pytest.raises(GoldenFormatError, match="missing flavor sections"): + GoldenStore.load(missing) + + def test_flavors_are_separate_sections(tmp_path): store = GoldenStore() store.record(LL, "llvm20", {"conv": {"0": "a20"}}) diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/rocke_ir_parity_harness.py b/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/rocke_ir_parity_harness.py index 55a63b28394e..56cb7681087d 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/rocke_ir_parity_harness.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/rocke_ir_parity_harness.py @@ -12,7 +12,11 @@ from collections import Counter from pathlib import Path -from rocke.core.ir_golden import GOLDEN_FLAVORS +from rocke.core.ir_golden import ( + GOLDEN_ALIASES, + GOLDEN_FLAVORS, + GOLDEN_PROFILE_FLAVORS, +) from rocke.core.ir_golden import check_golden as _check_golden @@ -5211,7 +5215,8 @@ def build_golden() -> dict: """Run every case under each golden flavor and return the flavor-keyed doc.""" return { "schema": GOLDEN_SCHEMA, - "flavors": {fl: run(flavor=fl) for fl in GOLDEN_FLAVORS}, + "aliases": GOLDEN_ALIASES, + "flavors": {fl: run(flavor=fl) for fl in GOLDEN_PROFILE_FLAVORS}, } @@ -5229,8 +5234,8 @@ def main(): ap.add_argument( "--write", type=Path, - help="(re-)bless the flavor-keyed golden: run every case under each of " - f"{GOLDEN_FLAVORS} and write the result. Run only from a verified-good " + help="(re-)bless the profile-keyed golden: run every case under each of " + f"{GOLDEN_PROFILE_FLAVORS} and write lane aliases. Run only from a verified-good " "tree; re-blessing should accompany a reviewed, expected output change.", ) ap.add_argument( diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/test_rocke_multiarch.py b/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/test_rocke_multiarch.py index 2689fb4ef95f..34ca578bbbcd 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/test_rocke_multiarch.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/instances/test_rocke_multiarch.py @@ -762,6 +762,7 @@ def test_datalayout_matches_hipcc_emitted_ir(self): from rocke.core.lower_llvm import ( LLVM_FLAVOR_LLVM23, _datalayout_for_flavor, + _emission_profile, _flavor_for_llvm, ) from rocke.helpers.compile import emit_device_llvm_ir_via_hipcc @@ -788,13 +789,16 @@ def test_datalayout_matches_hipcc_emitted_ir(self): self.skipTest("cannot determine reference hipcc's LLVM version") detected_flavor = _flavor_for_llvm(int(match[1])) rocke_dl = _datalayout_for_flavor(detected_flavor) + uses_llvm23_profile = _emission_profile(detected_flavor) is _emission_profile( + LLVM_FLAVOR_LLVM23 + ) # The address spaces LLVM gained in 5bf967cb132b. Bound unconditionally: # the per-arch loop below reads it on the llvm23 path too. expected_p10_p15 = ( "-p10:32:32-p11:32:32-p12:32:32-p13:32:32-p14:32:32-p15:32:32" ) - if detected_flavor == LLVM_FLAVOR_LLVM23: + if uses_llvm23_profile: # rocKE's llvm23 constant is the llvm22 one with TWO independent # additions -- the ELF symbol-mangling spec `m:e` after the leading # endianness field, and address spaces p10-p15 (upstream @@ -837,7 +841,7 @@ def test_datalayout_matches_hipcc_emitted_ir(self): self.skipTest(f"hipcc cannot target {arch} on this toolchain: {e}") toolchain_dl = self._extract_datalayout_from_ir(ir) if ( - detected_flavor == LLVM_FLAVOR_LLVM23 + uses_llvm23_profile and toolchain_dl != rocke_dl and toolchain_dl.replace("-i64:64", expected_p10_p15 + "-i64:64", 1) == rocke_dl diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/portable_ir/replay_cli.cpp b/dnn-providers/hip-kernel-provider/rocke/platform/tests/portable_ir/replay_cli.cpp index 454321dddb95..572544dcb8a2 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/portable_ir/replay_cli.cpp +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/portable_ir/replay_cli.cpp @@ -23,7 +23,7 @@ * replay_cli --recipe --cbor [common opts] [spec opts] * replay_cli --bundle --key KEY [common opts] [spec opts] * - * common opts: --arch GFX (default gfx950), --flavor llvm20|llvm22|llvm23 + * common opts: --arch GFX (default gfx950), --flavor llvm20|llvm22|llvm23|llvm24 * spec opts : --int NAME=VALUE, --str NAME=VALUE (repeatable) * * Exits nonzero with a message on stderr for any read, parse, replay, or @@ -57,7 +57,7 @@ void usage(const char* argv0) { std::fprintf(stderr, "usage: %s (--ir FILE | --recipe FILE [--cbor] | --bundle FILE --key KEY)\n" - " [--arch GFX] [--flavor llvm20|llvm22|llvm23]\n" + " [--arch GFX] [--flavor llvm20|llvm22|llvm23|llvm24]\n" " [--int NAME=VALUE]... [--str NAME=VALUE]...\n" " %s --provenance\n", argv0, diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/test_binding_compiler_selection.py b/dnn-providers/hip-kernel-provider/rocke/platform/tests/test_binding_compiler_selection.py index a898bf52205c..213e44f30fd2 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/test_binding_compiler_selection.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/test_binding_compiler_selection.py @@ -215,12 +215,16 @@ def fail_reduce(): else: raise AssertionError("invalid serialized input was accepted") -try: - rocke_engine.lower_serialized_ir("not serialized IR", arch="gfx950", flavor="invalid") -except RuntimeError as exc: - assert "unknown LLVM flavor" in str(exc) -else: - raise AssertionError("invalid explicit flavor was accepted") +for invalid_flavor in ("llvm25", "LLVM24", " llvm24 "): + try: + rocke_engine.lower_serialized_ir( + "not serialized IR", arch="gfx950", flavor=invalid_flavor + ) + except ValueError as exc: + assert invalid_flavor in str(exc) + assert "unknown LLVM flavor" in str(exc) + else: + raise AssertionError("invalid explicit flavor was accepted") ir = serialize(IRBuilder("cleanup_explicit_probe").kernel) for _ in range(2): @@ -232,6 +236,7 @@ def fail_reduce(): raise AssertionError("serialized-IR resolver failure did not propagate") assert rocke_engine.lower_serialized_ir(ir, arch="gfx950", flavor="llvm20") +assert rocke_engine.lower_serialized_ir(ir, arch="gfx950", flavor="llvm24") """ diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/test_compiler_detection.py b/dnn-providers/hip-kernel-provider/rocke/platform/tests/test_compiler_detection.py index 311dfcfba3f1..31da17a08810 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/test_compiler_detection.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/test_compiler_detection.py @@ -114,6 +114,16 @@ def test_unavailable_library_does_not_prevent_offline_emission(monkeypatch): assert lower_llvm._resolve_llvm_flavor() == "llvm23" +@pytest.mark.parametrize("value", ["llvm25", "LLVM24", " llvm24 "]) +def test_unknown_explicit_flavor_fails_without_querying(monkeypatch, value): + monkeypatch.setenv("ROCKE_LLVM_FLAVOR", value) + query = Mock(side_effect=AssertionError("unknown override queried COMGR")) + monkeypatch.setattr(comgr, "_require_compiler_info", query) + with pytest.raises(ValueError, match="not a recognized flavor"): + lower_llvm._resolve_llvm_flavor() + query.assert_not_called() + + def test_auto_lowering_recovers_then_retains_success(monkeypatch): monkeypatch.setenv("ROCKE_BACKEND", "python") monkeypatch.setattr(comgr, "_lib", None) @@ -176,13 +186,18 @@ def test_explicit_lowering_bypasses_library_load(monkeypatch, source): (21, "llvm22"), (22, "llvm22"), (23, "llvm23"), - (24, "llvm23"), + (24, "llvm24"), ], ) def test_llvm_flavor_boundaries(major, flavor): assert lower_llvm._flavor_for_llvm(major) == flavor +def test_newer_compiler_major_is_not_silently_qualified(): + with pytest.raises(ValueError, match="major 25.*latest qualified lane llvm24"): + lower_llvm._flavor_for_llvm(25) + + def test_override_does_not_falsify_guard_evidence(monkeypatch): info = comgr.CompilerInfo( (20, 0, 0), "COMGR preprocessing", "requested.so", "loaded.so", "loaded.so" @@ -197,6 +212,28 @@ def test_override_does_not_falsify_guard_evidence(monkeypatch): assert info.describe() in str(error.value) +@pytest.mark.parametrize( + "ir", + [ + "define void @k() {}", + 'target datalayout = "unrecognized"\ndefine void @k() {}', + f'target datalayout = "{lower_llvm._datalayout_for_flavor("llvm24")}"\n' + "define void @k() {}", + ], +) +def test_unqualified_future_compiler_is_rejected_before_ir_shape_checks( + monkeypatch, ir +): + info = comgr.CompilerInfo( + (25, 0, 0), "fixture", "requested.so", "loaded.so", "loaded.so" + ) + monkeypatch.setattr(comgr, "loaded_compiler_info", lambda: info) + with pytest.raises( + comgr.ComgrError, match="major 25.*latest qualified lane llvm24" + ): + comgr._assert_ir_flavor_matches_lib(ir) + + def test_loader_skips_unloadable_candidate_before_querying(monkeypatch): lib = compiler_library((23, 0, 0), "second.so") monkeypatch.setattr(comgr, "_lib", None) diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/test_rocke.py b/dnn-providers/hip-kernel-provider/rocke/platform/tests/test_rocke.py index 8c838aa6ebfc..0ff78ff2cf26 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/test_rocke.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/test_rocke.py @@ -4884,14 +4884,14 @@ def test_cpp_engine_lowers_every_arch_python_wires(self): def test_flavor_rejection_is_never_swallowed(self): """One engine rejecting a flavor the other took is a defect, not a gap.""" with self.assertRaises(ValueError): - self._run(ValueError("unknown LLVM flavor 'llvm24'")) + self._run(ValueError("unknown LLVM flavor 'llvm25'")) self.assertEqual(self.backend.cpp_fallbacks(), []) def test_flavor_rejection_is_not_excused_on_an_unported_arch(self): """Even on a listed arch a ValueError is a defect, not a coverage gap.""" self._with_gap("gfxfuture") with self.assertRaises(ValueError): - self._run(ValueError("unknown LLVM flavor 'llvm24'"), arch="gfxfuture") + self._run(ValueError("unknown LLVM flavor 'llvm25'"), arch="gfxfuture") class TestFusionPlanner(unittest.TestCase): diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/tools/test_arch_domain_artifact.py b/dnn-providers/hip-kernel-provider/rocke/platform/tests/tools/test_arch_domain_artifact.py index e1c4e437bea9..f8520afe287c 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/tools/test_arch_domain_artifact.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/tools/test_arch_domain_artifact.py @@ -123,6 +123,10 @@ def test_columns_are_well_formed(self): self.assertEqual(sorted(tc.get("arches", [])), sorted(wired_arches())) + def test_llvm24_uses_the_shared_llvm23_declaration_profile(self): + self.assertEqual(G._decl_table("llvm24"), G._decl_table("llvm23")) + self.assertNotEqual(G._decl_table("llvm24"), G._decl_table("llvm20")) + def test_every_decl_key_is_covered_on_every_wired_arch(self): """The drift this file exists to catch: a decl key the artifact has no opinion on, in JSON that is still valid and still looks authoritative. diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/tools/test_gen_arch_domain_cpp.py b/dnn-providers/hip-kernel-provider/rocke/platform/tests/tools/test_gen_arch_domain_cpp.py index 4bca2b12a1c1..c883bca24339 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/tools/test_gen_arch_domain_cpp.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/tools/test_gen_arch_domain_cpp.py @@ -145,6 +145,27 @@ def test_the_generator_reads_through_the_python_reader(gen) -> None: } +def test_only_aliases_the_loader_would_follow_are_emitted(gen) -> None: + """C++ applies the same own-column and committed-source precedence as Python.""" + fake = SimpleNamespace( + committed_flavors=lambda: ("llvm98", "llvm99"), + load=lambda flavor: SimpleNamespace(keys=lambda: (), arches=lambda key: ()), + is_negative=lambda status: True, + is_waived=lambda key, arch, flavor: False, + DEFAULT_MODE="warn", + COLUMN_ALIASES={ + "llvm100": "llvm99", + "llvm98": "llvm99", + "llvm101": "llvm97", + }, + ) + text = gen.render(fake) + assert ' {"llvm100", "llvm99"},' in text + assert '"llvm98", "llvm99"' not in text + assert '"llvm101"' not in text + assert " {nullptr, nullptr},\n};" in text + + def test_an_empty_column_is_a_null_entry_not_an_empty_array(gen) -> None: """A zero-length array does not compile, and a flavor whose column has no negative cell is normal -- every probe could come back ``ok``.""" @@ -268,5 +289,9 @@ def test_the_engine_carries_the_python_readers_table() -> None: view = _python_view() for flavor, cells in view.items(): assert [tuple(c) for c in engine.arch_domain_column(flavor)] == cells, flavor + for lane, source in arch_domain.COLUMN_ALIASES.items(): + if lane not in view and source in view: + got = [tuple(c) for c in engine.arch_domain_column(lane)] + assert got == view[source], lane assert engine.arch_domain_column("llvm-that-nobody-ships") == [] assert engine.arch_domain_default_mode() == arch_domain.DEFAULT_MODE diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tests/tools/test_run_checks.py b/dnn-providers/hip-kernel-provider/rocke/platform/tests/tools/test_run_checks.py index c3fc977201e3..c328dc4e444c 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tests/tools/test_run_checks.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tests/tools/test_run_checks.py @@ -54,6 +54,13 @@ def run(label, command, env, cwd=None): return runner.main(), calls +def test_runner_uses_every_qualified_compiler_lane(runner): + from rocke.core.llvm_profile import LLVM_FLAVORS + + assert runner.FLAVORS is LLVM_FLAVORS + assert "llvm24" in runner.FLAVORS + + def test_default_runs_every_host_validation_gate_once(runner, monkeypatch): rc, calls = _run_default(runner, monkeypatch) assert rc == 0 diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tools/check_byte_identity.py b/dnn-providers/hip-kernel-provider/rocke/platform/tools/check_byte_identity.py index ce0121fdf1a6..a753b8f2caa2 100644 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tools/check_byte_identity.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tools/check_byte_identity.py @@ -6,9 +6,9 @@ # prove its LLVM-IR emission is byte-identical to the Python engine across every # kernel family. A green run means the dual-backend contract still holds. # -# Unless ROCKE_LLVM_FLAVOR is already llvm23, a second gating lane re-runs the -# gfx1250 family at llvm23, since its gated ops lower only at that flavor. The -# families every config of which needs llvm23 run in that lane only. +# When the selected emission profile lacks the LLVM23-generation target-op +# capability, a second lane re-runs the affected families at llvm23. Profiles +# that already carry the capability (llvm23 and llvm24) run them directly. # # Cross-platform (Windows + Linux) replacement for the legacy check_byte_identity.sh. # All paths are derived relative to this file so the rocke/platform/ tree stays copy-able. @@ -37,7 +37,20 @@ # Families whose every config uses an llvm23-gated op (their kernels move data # with TDM). Under another flavor both engines reject all of them, which the # gate reads as ALL_REJECTED, so they are compared in the llvm23 lane only. -LLVM23_ONLY_FAMILIES = ("conv_direct_dgrad_wmma",) +TARGET_OP_PROFILE_FAMILIES = ("conv_direct_dgrad_wmma",) + + +def _selected_profile_supports_target_ops() -> bool: + """Resolve the selected lane once and query its structural profile.""" + python_root = ROCKE / "python" + if str(python_root) not in sys.path: + sys.path.insert(0, str(python_root)) + from rocke.core.lower_llvm import ( + _resolve_llvm_flavor, + _supports_llvm23_target_ops, + ) + + return _supports_llvm23_target_ops(_resolve_llvm_flavor()) def _cxx() -> str | None: @@ -177,11 +190,11 @@ def run_gate( # A dashboard per lane, beside the archive it describes: one shared path # meant the diagnostic ir run overwrote the gating run's JSON. - llvm23 = os.environ.get("ROCKE_LLVM_FLAVOR") == "llvm23" + supports_target_ops = _selected_profile_supports_target_ops() only_subs = [s for s in args.only.split(",") if s] llvm23_families = [ f - for f in LLVM23_ONLY_FAMILIES + for f in TARGET_OP_PROFILE_FAMILIES if not only_subs or any(s in f for s in only_subs) ] # Under another flavor the default lane leaves the llvm23-only families @@ -190,18 +203,21 @@ def run_gate( "LLVM-IR (the contract)", str(build_root / "dashboard_ll.json"), ["--mode", "ll"] - + ([] if llvm23 else ["--exclude", ",".join(LLVM23_ONLY_FAMILIES)]), + + ( + [] + if supports_target_ops + else ["--exclude", ",".join(TARGET_OP_PROFILE_FAMILIES)] + ), ) - # The gfx1250-only ops (prefetch, clusters, async stores, tensor moves, ...) - # lower only under llvm23. Under any other flavor both engines reject those - # configs, which reads as BOTH_REJECTED and passes without comparing a - # byte. Re-run the gfx1250 families at llvm23 so every invocation of this - # gate covers them, whatever flavor the host resolves to. + # The gfx1250-only ops need the LLVM23-generation target-op profile. Under + # an older profile both engines reject those configs, which reads as + # BOTH_REJECTED and passes without comparing a byte. Re-run affected + # families at llvm23 only when the selected profile lacks that capability. llvm23_only = [s for s in only_subs if s in GFX1250_FAMILY] if not args.only: llvm23_only = [GFX1250_FAMILY] llvm23_only += llvm23_families - if not llvm23 and llvm23_only: + if not supports_target_ops and llvm23_only: env = dict(os.environ, ROCKE_LLVM_FLAVOR="llvm23") status |= run_gate( "LLVM-IR, gfx1250 families at llvm23", diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tools/gen_arch_domain.py b/dnn-providers/hip-kernel-provider/rocke/platform/tools/gen_arch_domain.py index 2d6d148b9eac..60e7ab6f79a9 100755 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tools/gen_arch_domain.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tools/gen_arch_domain.py @@ -978,19 +978,12 @@ def _assemble( def _decl_table(flavor: str) -> dict[str, str]: """The decls a _Lowerer would resolve for this flavor. - Mirrors `_Lowerer.__init__` exactly -- base table, then the per-flavor - override dict. Duplicating the merge here rather than importing a private - helper keeps the tool honest about what it measured, but it is a mirror and - must be updated if the resolution rule gains a rung. + Uses the lowerer's profile-aware resolver directly so a new compiler lane + cannot silently fall back to the LLVM20 declaration shapes. """ from rocke.core import lower_llvm as L - decls = dict(L._INTRINSIC_DECLS) - if flavor == L.LLVM_FLAVOR_LLVM22: - decls.update(L._INTRINSIC_DECLS_LLVM22_OVERRIDES) - elif flavor == L.LLVM_FLAVOR_LLVM23: - decls.update(L._INTRINSIC_DECLS_LLVM23_OVERRIDES) - return decls + return L._decls_for_flavor(flavor) def _drift(committed: str, fresh: str) -> str | None: @@ -1361,6 +1354,16 @@ def main() -> int: return 2 flavor = L._resolve_llvm_flavor() + out = args.out or default_out(flavor) + if args.check and args.out is None and not out.is_file(): + print("rocKE intrinsic arch-domain generator") + print(f" flavor : {flavor}") + print( + f"\nUNVALIDATED: no committed column for {flavor} " + f"({out.name}); nothing to check. Run without --check to add one." + ) + return _unvalidated_exit(args.unvalidated_exit_code, 0) + clang = _llvm_tool("clang") opt = _llvm_tool("opt") @@ -1447,7 +1450,6 @@ def main() -> int: print(f" arches : {', '.join(arches)}") print(f" keys : {len(keys)}") - out = args.out or default_out(flavor) expected_cells: dict[str, dict[str, dict[str, str]]] = {} if args.check and out.is_file(): try: @@ -1787,8 +1789,8 @@ def record( if args.check: if not out.is_file(): - # Not a failure: a host can only measure its own flavor, so - # failing here would red every CI machine on a newer ROCm. + # A custom --out path still validates toolchain consistency before + # reporting that there is no baseline to compare. print( f"\nUNVALIDATED: no committed column for {flavor} " f"({out.name}); nothing to check. Run without --check to add one." diff --git a/dnn-providers/hip-kernel-provider/rocke/platform/tools/gen_arch_domain_cpp.py b/dnn-providers/hip-kernel-provider/rocke/platform/tools/gen_arch_domain_cpp.py index af7a22cef8d8..d4c638d4f921 100755 --- a/dnn-providers/hip-kernel-provider/rocke/platform/tools/gen_arch_domain_cpp.py +++ b/dnn-providers/hip-kernel-provider/rocke/platform/tools/gen_arch_domain_cpp.py @@ -151,6 +151,20 @@ def render(domain: ModuleType) -> str: lines.append(f" {{{c_string(flavor)}, {name}, {count}}},") lines.append("};") lines.append("") + # Match domain.load(): an alias applies only while its lane has no column + # of its own and its source has a committed column. + aliases = sorted( + (lane, source) + for lane, source in getattr(domain, "COLUMN_ALIASES", {}).items() + if lane not in flavors and source in flavors + ) + lines.append("/* domain.COLUMN_ALIASES: lanes enforcing another lane's column. */") + lines.append("const column_alias_t ROCKE_ARCH_DOMAIN_ALIASES[] = {") + for lane, source in aliases: + lines.append(f" {{{c_string(lane)}, {c_string(source)}}},") + lines.append(" {nullptr, nullptr},") + lines.append("};") + lines.append("") return "\n".join(lines) diff --git a/dnn-providers/hip-kernel-provider/rocke/tools/run_checks.py b/dnn-providers/hip-kernel-provider/rocke/tools/run_checks.py index 51a91a8cbe68..d1ac6f813e6d 100644 --- a/dnn-providers/hip-kernel-provider/rocke/tools/run_checks.py +++ b/dnn-providers/hip-kernel-provider/rocke/tools/run_checks.py @@ -58,7 +58,12 @@ PLATFORM_PYROOT = PLATFORM / "python" EMIT_COMMON_DIR = PLATFORM / "tests" / "instances" / "parity" -FLAVORS = ("llvm20", "llvm22", "llvm23") +# The lowerer's compiler-lane registry is the source of truth. Importing it here +# prevents a newly qualified lane from being silently omitted by the top-level +# gate or rejected by --flavor. +sys.path.insert(0, str(PLATFORM_PYROOT)) +from rocke.core.llvm_profile import LLVM_FLAVORS as FLAVORS # noqa: E402 + STAGES = ( "guard", "gate",