Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-yardsticks/patches/405ea4f318b34251 # aien-yardsticks aien-dev/aien-yardsticks Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-yardsticks#1 (code only) closed derived `405ea4f318b34251` #1 Imported from GitHub aien-dev/aien-yardsticks#1 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `9c0b5797bf18ee28647ca7f5067ac8c2745b8054` · Head `f28d3610d70a7f946a53ca2e295f86689114ce46` ### Fetch it A git bundle of the pull request's head, 13286 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aien-yardsticks/patches/405ea4f318b34251.bundle -o 405ea4f318b34251.bundle git fetch 405ea4f318b34251.bundle refs/pull/1/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-yardsticks 1 f28d3610d70a7f946a53ca2e295f86689114ce46 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-yardsticks","number":1,"url":"https://github.com/aien-dev/aien-yardsticks/pull/1","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:39:54Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/README.md b/README.md new file mode 100644 index 0000000..4ee212d --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +# aien-yardsticks + +Outside yardsticks AIEN is measured against (MAX, llama.cpp, vLLM). Never part of AIEN. Nothing here ships in AIEN. + +| Yardstick | Path | +|---|---| +| Modular MAX, Nemotron-H KV-head expansion | `yardsticks/modular-nemotron-h-kvexp/` | + +Python is tolerated here only until it is replaced by Rust. diff --git a/yardsticks/modular-nemotron-h-kvexp/README.md b/yardsticks/modular-nemotron-h-kvexp/README.md new file mode 100644 index 0000000..cb97c62 --- /dev/null +++ b/yardsticks/modular-nemotron-h-kvexp/README.md @@ -0,0 +1,83 @@ +> **YARDSTICK ONLY. Never part of AIEN. Nothing here ships in AIEN.** +> +> This is the Nemotron-H KV-head-expansion comparison adapter for Modular MAX, kept so AIEN can be measured against MAX. +> It was moved here, with its git history, from `aien-dev/aien-sovereign-core` (commit `5fdab70`, path `modular/nemotron_h_kvexp`) because AIEN repos may contain no Python. +> The Python in this folder is scheduled for replacement by Rust (see the "Replace the Python yardstick with Rust" issue in this repo). + +# KV-Head Expanded Nemotron-H Architecture for Modular MAX + +Custom architecture adapter enabling high-throughput serving of NVIDIA Nemotron-H models (such as `nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16`) on Modular MAX. + +## Architecture Rationale + +Modular MAX employs optimized FlashAttention kernels for Grouped-Query Attention (GQA). In current MAX versions, the maximum supported GQA group size is 8 (`group = num_attention_heads / num_key_value_heads <= 8`). + +Nemotron-3.5-Lightning-30B utilizes a GQA configuration where: +- Query heads (`n_heads`): 32 +- Key-Value heads (`n_kv`): 2 +- GQA group ratio: 32 / 2 = 16 + +Because 16 > 8, loading the standard checkpoint triggers an unsupported group size error in the MAX attention kernel. + +This adapter resolves the kernel limitation by calculating the minimum integer expansion factor: + +```python +expansion = math.ceil((n_heads / n_kv) / MAX_NVIDIA_GQA_GROUP) +``` + +For Nemotron-H (group 16), `expansion = 2`. Each KV head is replicated across the channel dimension during state dictionary weight loading: +- Replicated KV heads: 2 * 2 = 4 +- Effective GQA group ratio: 32 / 4 = 8 + +This satisfies the FlashAttention kernel constraint without altering model activations, attention math, or output distributions. + +## Key Features + +1. **Native Dynamic Expansion**: Replicates KV heads on the fly during safe tensor loading and state dict conversion. +2. **Offline PEFT LoRA Folding**: Set `MAX_LORA_DIR` to fold LoRA adapters (A and B matrices) directly into base weights prior to QKV fusion, eliminating runtime LoRA overhead. +3. **Lazy Registration Override**: Overrides default `NemotronHForCausalLM` registration within the MAX pipeline registry to ensure transparent resolution from standard model checkpoints. + +## Installation & Usage + +Install as an editable package: + +```bash +pip install -e . +``` + +Serve using the MAX CLI: + +```bash +max serve \ + --model nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16 \ + --served-model-name nemotron-lightning \ + --custom-architectures $(pwd) \ + --port 18006 \ + --max-batch-size 8 \ + --max-length 32768 \ + --kv-cache-format bfloat16 +``` + +## Testing + +Run unit tests via standard Python unittest: + +```bash +python3 -m unittest discover -s tests -v +``` + +## License + +Licensed under the Apache License, Version 2.0. + +## Benchmarks (NVIDIA DGX Spark / Grace Blackwell GB10) + +Benchmarked on ARM64 Grace Neoverse V2 cores using realistic Nemotron-30B layer dimensions (4608x4096 expanded to 5120x4096): + +| Metric | Measured Value | +|---|---| +| Latency per Layer | 5.49 ms | +| Full Model Expansion (52 layers) | 285.63 ms | +| Memory Copy Throughput | 12.80 GB/s | + +Load-time expansion overhead is under 300 ms for the entire 30B model, introducing negligible startup delay while enabling high-throughput serving on Modular MAX. diff --git a/yardsticks/modular-nemotron-h-kvexp/__init__.py b/yardsticks/modular-nemotron-h-kvexp/__init__.py new file mode 100644 index 0000000..f0b4617 --- /dev/null +++ b/yardsticks/modular-nemotron-h-kvexp/__init__.py @@ -0,0 +1,32 @@ +"""KV-head-expanded Nemotron-H adapter for MAX (see config.py for rationale).""" + +from .arch import kvexp_arch +from .model import KvExpandedNemotronHModel + +ARCHITECTURES = [kvexp_arch] + +# MAX registers built-in architectures *lazily*: ``register_lazy(name, ...)`` +# records a pending entry, and the first lookup calls ``_materialize_lazy`` -> +# ``register(builtin)`` WITHOUT ``allow_override``. Since our arch already +# registered under the same name, that raises: +# "Refusing to override existing architecture for 'NemotronHForCausalLM'". +# We are imported before materialization, so wrap ``register`` to ignore the +# built-in re-registration for this name and keep ours. +try: + from max.pipelines import PIPELINE_REGISTRY + + _orig_register = PIPELINE_REGISTRY.register + + def _register_kvexp_aware(architecture, *args, **kwargs): + if ( + architecture.name == "NemotronHForCausalLM" + and architecture.pipeline_model is not KvExpandedNemotronHModel + and (architecture.name, architecture.task) in PIPELINE_REGISTRY._architectures_by_task + ): + # Built-in lazily materializing after our override; keep ours. + return + return _orig_register(architecture, *args, **kwargs) + + PIPELINE_REGISTRY.register = _register_kvexp_aware +except Exception: + pass diff --git a/yardsticks/modular-nemotron-h-kvexp/arch.py b/yardsticks/modular-nemotron-h-kvexp/arch.py new file mode 100644 index 0000000..4e012b6 --- /dev/null +++ b/yardsticks/modular-nemotron-h-kvexp/arch.py @@ -0,0 +1,48 @@ +"""Register the KV-expanded Nemotron-H architecture (overrides the built-in).""" + +from __future__ import annotations + +from max.graph.weights import WeightsFormat +from max.pipelines.context import TextContext +from max.pipelines.lib import SupportedArchitecture +from max.pipelines.modeling.types import PipelineTask + +# Nemotron-3's chat template is Qwen-format; importing the qwen3_5 parsers here +# registers the "qwen3_5" reasoning/tool parsers the architecture names below. +from max.pipelines.architectures.qwen3_5.reasoning import ( # noqa: F401 + Qwen3_5ReasoningParser, +) +from max.pipelines.architectures.qwen3_5.tool_parser import ( # noqa: F401 + Qwen3_5ToolParser, +) +from max.pipelines.architectures.nemotron_h.tokenizer import NemotronHTokenizer + +from .config import KvExpandedNemotronHConfig +from .model import KvExpandedNemotronHModel +from .weight_adapters import convert_kvexp_nemotron_h_state_dict + +kvexp_arch = SupportedArchitecture( + # Same name as the built-in -> allowed to override so the checkpoint's + # config.json architectures[0] == "NemotronHForCausalLM" resolves here. + name="NemotronHForCausalLM", + task=PipelineTask.TEXT_GENERATION, + example_repo_ids=[ + "nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16", + ], + default_weights_format=WeightsFormat.safetensors, + default_encoding=KvExpandedNemotronHConfig.DEFAULT_ENCODING, + supported_encodings=KvExpandedNemotronHConfig.SUPPORTED_ENCODINGS, + pipeline_model=KvExpandedNemotronHModel, + tokenizer=NemotronHTokenizer, + context_type=TextContext, + weight_adapters={ + WeightsFormat.safetensors: convert_kvexp_nemotron_h_state_dict, + }, + # SSM recurrent state is not reconstructable from a token prefix. + required_arguments={"enable_prefix_caching": False}, + config=KvExpandedNemotronHConfig, + multi_gpu_supported=False, + reasoning_parser="qwen3_5", + tool_parser="qwen3_5", + supports_device_graph_capture=True, +) diff --git a/yardsticks/modular-nemotron-h-kvexp/benchmarks/.crumb b/yardsticks/modular-nemotron-h-kvexp/benchmarks/.crumb new file mode 100644 index 0000000..272b9eb --- /dev/null +++ b/yardsticks/modular-nemotron-h-kvexp/benchmarks/.crumb @@ -0,0 +1,22 @@ +{ + "schema_version": "1.0", + "dir_path": "./modular/nemotron_h_kvexp/benchmarks", + "purpose": { + "summary": "Performance and throughput micro-benchmarks for KV-head expansion on Grace Neoverse V2", + "created_by": "AIEN", + "session_id": "modular-upstream-packaging", + "created_at": "2026-09-18T14:26:00Z" + }, + "parent": { + "canonical": "./modular/nemotron_h_kvexp", + "name": "nemotron_h_kvexp" + }, + "whispers": [ + { + "author": "AIEN", + "timestamp": "2026-09-18T14:26:00Z", + "whisper_id": "bench-results", + "message": "Benchmark measured 5.49 ms per layer and 285.63 ms for full 52-layer Nemotron-30B model at 12.80 GB/s." + } + ] +} diff --git a/yardsticks/modular-nemotron-h-kvexp/benchmarks/bench_kv_expansion.py b/yardsticks/modular-nemotron-h-kvexp/benchmarks/bench_kv_expansion.py new file mode 100644 index 0000000..2909c2a --- /dev/null +++ b/yardsticks/modular-nemotron-h-kvexp/benchmarks/bench_kv_expansion.py @@ -0,0 +1,58 @@ +"""Benchmark KV head replication latency and memory throughput on ARM64.""" + +import time +import numpy as np + + +def benchmark_kv_replication(): + # Nemotron-30B attention layer dimensions + n_heads = 32 + head_dim = 128 + n_kv = 2 + expansion = 2 + hidden = 4096 + num_attention_layers = 52 + + q_dim = n_heads * head_dim # 4096 + kv_dim = n_kv * head_dim # 256 + total_rows = q_dim + 2 * kv_dim # 4608 + + # Synthetic fused QKV matrix in FP32 + qkv = np.random.randn(total_rows, hidden).astype(np.float32) + + # Warmup + for _ in range(5): + q = qkv[:q_dim] + k = qkv[q_dim : q_dim + kv_dim].reshape(n_kv, head_dim, hidden) + v = qkv[q_dim + kv_dim :].reshape(n_kv, head_dim, hidden) + k_rep = np.repeat(k, expansion, axis=0).reshape(n_kv * expansion * head_dim, hidden) + v_rep = np.repeat(v, expansion, axis=0).reshape(n_kv * expansion * head_dim, hidden) + fused = np.ascontiguousarray(np.concatenate([q, k_rep, v_rep], axis=0)) + + # Benchmark single layer + iterations = 200 + start = time.perf_counter() + for _ in range(iterations): + q = qkv[:q_dim] + k = qkv[q_dim : q_dim + kv_dim].reshape(n_kv, head_dim, hidden) + v = qkv[q_dim + kv_dim :].reshape(n_kv, head_dim, hidden) + k_rep = np.repeat(k, expansion, axis=0).reshape(n_kv * expansion * head_dim, hidden) + v_rep = np.repeat(v, expansion, axis=0).reshape(n_kv * expansion * head_dim, hidden) + fused = np.ascontiguousarray(np.concatenate([q, k_rep, v_rep], axis=0)) + elapsed = time.perf_counter() - start + + per_layer_ms = (elapsed / iterations) * 1000.0 + full_model_ms = per_layer_ms * num_attention_layers + bytes_processed = qkv.nbytes * iterations + throughput_gb_s = (bytes_processed / (1024**3)) / elapsed + + print("=== Nemotron-H KV Expansion Benchmark (Grace Neoverse V2) ===") + print(f"Layer Shape: [{total_rows}, {hidden}] -> [{q_dim + 2 * n_kv * expansion * head_dim}, {hidden}]") + print(f"Latency per Layer: {per_layer_ms:.3f} ms") + print(f"Full 52-Layer Model: {full_model_ms:.2f} ms") + print(f"Memory Throughput: {throughput_gb_s:.2f} GB/s") + print("=============================================================") + + +if __name__ == "__main__": + benchmark_kv_replication() diff --git a/yardsticks/modular-nemotron-h-kvexp/config.py b/yardsticks/modular-nemotron-h-kvexp/config.py new file mode 100644 index 0000000..5145eaa --- /dev/null +++ b/yardsticks/modular-nemotron-h-kvexp/config.py @@ -0,0 +1,87 @@ +"""Config subclass that expands Nemotron-H KV heads to satisfy MAX's GQA kernel.""" + +from __future__ import annotations + +import math +from dataclasses import dataclass + +from max.dtype import DType +from max.pipelines.architectures.nemotron_h.model_config import ( + NemotronHConfig, + parse_hybrid_pattern, + resolve_attention_head_dim, +) +from max.pipelines.lib.config.model_config import _select_quantization_encoding + +MAX_NVIDIA_GQA_GROUP = 8 + + +def kv_expansion_factor(huggingface_config) -> int: + """How many times to replicate each KV head so group <= 8.""" + n_heads = int(huggingface_config.num_attention_heads) + n_kv = int(huggingface_config.num_key_value_heads) + if n_kv <= 0: + return 1 + group = n_heads / n_kv + return max(1, math.ceil(group / MAX_NVIDIA_GQA_GROUP)) + + +@dataclass(kw_only=True) +class KvExpandedNemotronHConfig(NemotronHConfig): + """NemotronHConfig with KV-head replication for the MAX MHA kernel.""" + + SUPPORTED_ENCODINGS = NemotronHConfig.SUPPORTED_ENCODINGS | {"float4_e2m1fnx2"} + kv_expansion: int = 1 + + @staticmethod + def construct_kv_params( + huggingface_config, + pipeline_config, + devices, + kv_cache_config, + cache_dtype, + ): + # Mirror the built-in body, but multiply n_kv_heads by E so the cache, + # the attention reshape, and the flash kernel all agree on group <= 8. + expansion = kv_expansion_factor(huggingface_config) + resolved_encoding = _select_quantization_encoding( + pipeline_config.model, NemotronHConfig.DEFAULT_ENCODING + ) + if ( + resolved_encoding in ("float8_e4m3fn", "float4_e2m1fnx2") + and kv_cache_config.kv_cache_format is None + ): + cache_dtype = DType.float8_e4m3fn + kinds = parse_hybrid_pattern(huggingface_config.hybrid_override_pattern) + num_attention_layers = sum(1 for k in kinds if k == "attention") + return kv_cache_config.to_params( + dtype=cache_dtype, + n_kv_heads=int(huggingface_config.num_key_value_heads) * expansion, + head_dim=resolve_attention_head_dim(huggingface_config), + num_layers=num_attention_layers, + devices=devices, + data_parallel_degree=pipeline_config.model.data_parallel_degree, + ) + + @classmethod + def from_hf( + cls, + pipeline_config, + huggingface_config, + dtype, + kv_params, + devices, + ): + if dtype in (DType.float8_e4m3fn, DType.uint8): + dtype = DType.bfloat16 + config = super().from_hf( + pipeline_config, huggingface_config, dtype, kv_params, devices + ) + if config.dtype in (DType.float8_e4m3fn, DType.uint8): + config.dtype = DType.bfloat16 + expansion = kv_expansion_factor(huggingface_config) + config.kv_expansion = expansion + config.num_key_value_heads = ( + int(huggingface_config.num_key_value_heads) * expansion + ) + return config diff --git a/yardsticks/modular-nemotron-h-kvexp/model.py b/yardsticks/modular-nemotron-h-kvexp/model.py new file mode 100644 index 0000000..4c5fcc3 --- /dev/null +++ b/yardsticks/modular-nemotron-h-kvexp/model.py @@ -0,0 +1,33 @@ +"""Pipeline model subclass that uses the KV-expanded config.""" + +from __future__ import annotations + +from typing import Any + +from max.graph import DeviceRef +from max.pipelines.architectures.nemotron_h.model import NemotronHModel + +from .config import KvExpandedNemotronHConfig + + +class KvExpandedNemotronHModel(NemotronHModel): + """NemotronHModel whose config replicates KV heads (GQA group <= 8). + + The built-in ``_create_model_config`` hardcodes ``NemotronHConfig.from_hf``, + so we must override it to route through the expanded config. Everything else + (graph build, state pools, batching) is inherited unchanged. + """ + + model_config_cls = KvExpandedNemotronHConfig + + def _create_model_config(self, state_dict: dict[str, Any]): + device_ref = DeviceRef.from_device(self.devices[0]) + model_config = KvExpandedNemotronHConfig.from_hf( + self.pipeline_config, + self.huggingface_config, + self.dtype, + self.kv_params, + [device_ref], + ) + model_config.populate_fp8_layers(state_dict) + return model_config diff --git a/yardsticks/modular-nemotron-h-kvexp/pyproject.toml b/yardsticks/modular-nemotron-h-kvexp/pyproject.toml new file mode 100644 index 0000000..7357c2a --- /dev/null +++ b/yardsticks/modular-nemotron-h-kvexp/pyproject.toml @@ -0,0 +1,31 @@ +[build-system] +requires = ["setuptools>=61.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "nemotron-h-kvexp" +version = "0.1.0" +description = "Custom KV-head expanded Nemotron-H architecture adapter for Modular MAX" +readme = "README.md" +requires-python = ">=3.10" +license = { text = "Apache-2.0" } +authors = [ + { name = "AIEN", email = "aien@aienos.com" } +] +classifiers = [ + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "License :: OSI Approved :: Apache Software License", + "Operating System :: POSIX :: Linux", + "Topic :: Scientific/Engineering :: Artificial Intelligence", +] +dependencies = [ + "numpy>=1.24.0", + "safetensors>=0.4.0", +] + +[tool.setuptools] +packages = ["nemotron_h_kvexp"] +package-dir = {"nemotron_h_kvexp" = "."} diff --git a/yardsticks/modular-nemotron-h-kvexp/tests/.crumb b/yardsticks/modular-nemotron-h-kvexp/tests/.crumb new file mode 100644 index 0000000..6b35396 --- /dev/null +++ b/yardsticks/modular-nemotron-h-kvexp/tests/.crumb @@ -0,0 +1,22 @@ +{ + "schema_version": "1.0", + "dir_path": "./modular/nemotron_h_kvexp/tests", + "purpose": { + "summary": "Unit tests for KV-head expanded Nemotron-H MAX architecture adapter", + "created_by": "AIEN", + "session_id": "modular-upstream-packaging", + "created_at": "2026-09-18T14:26:00Z" + }, + "parent": { + "canonical": "./modular/nemotron_h_kvexp", + "name": "nemotron_h_kvexp" + }, + "whispers": [ + { + "author": "AIEN", + "timestamp": "2026-09-18T14:26:00Z", + "whisper_id": "test-suite-pass", + "message": "100% pass rate across 7 unit tests: expansion factor math, LoRA deltas, bfloat16 roundtrips, and tensor replication." + } + ] +} diff --git a/yardsticks/modular-nemotron-h-kvexp/tests/__init__.py b/yardsticks/modular-nemotron-h-kvexp/tests/__init__.py new file mode 100644 index 0000000..59d9449 --- /dev/null +++ b/yardsticks/modular-nemotron-h-kvexp/tests/__init__.py @@ -0,0 +1 @@ +# Test package for nemotron_h_kvexp diff --git a/yardsticks/modular-nemotron-h-kvexp/tests/test_kvexp.py b/yardsticks/modular-nemotron-h-kvexp/tests/test_kvexp.py new file mode 100644 index 0000000..589b292 --- /dev/null +++ b/yardsticks/modular-nemotron-h-kvexp/tests/test_kvexp.py @@ -0,0 +1,97 @@ +"""Unit tests for KV-expanded Nemotron-H architecture adapter.""" + +import unittest +from types import SimpleNamespace +import numpy as np + +from nemotron_h_kvexp.config import kv_expansion_factor, MAX_NVIDIA_GQA_GROUP +from nemotron_h_kvexp.weight_adapters import ( + _bf16_to_f32, + _f32_to_bf16, + _delta, +) + + +class TestKvExpansion(unittest.TestCase): + def test_expansion_factor_nemotron_30b(self): + """Nemotron-30B: 32 query heads, 2 KV heads -> group 16 -> expansion 2.""" + cfg = SimpleNamespace(num_attention_heads=32, num_key_value_heads=2) + factor = kv_expansion_factor(cfg) + self.assertEqual(factor, 2) + effective_kv = cfg.num_key_value_heads * factor + effective_group = cfg.num_attention_heads / effective_kv + self.assertLessEqual(effective_group, MAX_NVIDIA_GQA_GROUP) + + def test_expansion_factor_standard_gqa(self): + """Standard GQA: 32 query heads, 4 KV heads -> group 8 -> expansion 1.""" + cfg = SimpleNamespace(num_attention_heads=32, num_key_value_heads=4) + factor = kv_expansion_factor(cfg) + self.assertEqual(factor, 1) + + def test_expansion_factor_large_group(self): + """Hypothetical model: 64 query heads, 2 KV heads -> group 32 -> expansion 4.""" + cfg = SimpleNamespace(num_attention_heads=64, num_key_value_heads=2) + factor = kv_expansion_factor(cfg) + self.assertEqual(factor, 4) + effective_kv = cfg.num_key_value_heads * factor + effective_group = cfg.num_attention_heads / effective_kv + self.assertLessEqual(effective_group, MAX_NVIDIA_GQA_GROUP) + + def test_expansion_factor_zero_kv(self): + """Edge case: zero or negative KV heads returns 1.""" + cfg = SimpleNamespace(num_attention_heads=32, num_key_value_heads=0) + self.assertEqual(kv_expansion_factor(cfg), 1) + + +class TestBf16Conversions(unittest.TestCase): + def test_bf16_f32_roundtrip(self): + """Verify bfloat16 to float32 bit-shift roundtrip.""" + original = np.array([0.0, 1.0, -1.0, 2.5, 0.125], dtype=np.float32) + u16 = _f32_to_bf16(original) + recovered = _bf16_to_f32(u16) + np.testing.assert_allclose(recovered, original, rtol=1e-3, atol=1e-3) + + +class TestLoraDelta(unittest.TestCase): + def test_delta_computation(self): + """Verify LoRA low-rank delta calculation: scale * (B @ A).""" + r = 4 + in_dim = 16 + out_dim = 32 + scale = 2.0 + + A = np.random.randn(r, in_dim).astype(np.float32) + B = np.random.randn(out_dim, r).astype(np.float32) + + expected = scale * (B @ A) + actual = _delta(A, B, scale) + + self.assertEqual(actual.shape, (out_dim, in_dim)) + np.testing.assert_allclose(actual, expected, rtol=1e-6) + + +class TestWeightReplication(unittest.TestCase): + def test_kv_replication_math(self): + """Verify manual KV tensor replication semantics along head dimension.""" + n_kv = 2 + head_dim = 64 + hidden = 128 + expansion = 2 + + # Create synthetic KV projection weight + k = np.arange(n_kv * head_dim * hidden, dtype=np.float32).reshape(n_kv, head_dim, hidden) + + # Replicate + k_rep = np.repeat(k, expansion, axis=0) + self.assertEqual(k_rep.shape, (n_kv * expansion, head_dim, hidden)) + + # Verify first and second copies match the original first head + np.testing.assert_array_equal(k_rep[0], k[0]) + np.testing.assert_array_equal(k_rep[1], k[0]) + # Verify third and fourth copies match the original second head + np.testing.assert_array_equal(k_rep[2], k[1]) + np.testing.assert_array_equal(k_rep[3], k[1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/yardsticks/modular-nemotron-h-kvexp/weight_adapters.py b/yardsticks/modular-nemotron-h-kvexp/weight_adapters.py new file mode 100644 index 0000000..cd8a20c --- /dev/null +++ b/yardsticks/modular-nemotron-h-kvexp/weight_adapters.py @@ -0,0 +1,216 @@ +"""Weight adapter: built-in Nemotron-H adapter, + optional PEFT LoRA fold-in, +then KV-head replication for MAX's GQA kernel (group 16 -> 8). + +Track A: set ``ATLAS_LORA_DIR`` to a PEFT adapter directory (adapter_config.json + +adapter_model.safetensors). Its q/k/v/o LoRA weights are folded into the base +projections *before* qkv fusion, using delta = (alpha/r) * B @ A. This lets an +adapter trained with NeMo/PEFT be served on MAX for NemotronH without MAX's +Llama-3-only runtime LoRA path. The adapter is baked at load time. +""" + +from __future__ import annotations + +import json +import os +import re + +import numpy as np +from max.driver import Buffer +from max.dtype import DType +from max.graph.weights import WeightData +from max.graph.weights.weights import Shape +from max.pipelines.architectures.nemotron_h.model_config import ( + resolve_attention_head_dim, +) +from max.pipelines.architectures.nemotron_h.weight_adapters import ( + convert_nemotron_h_state_dict, +) + +from .config import kv_expansion_factor + +_LORA_PROJ_RE = re.compile(r"layers\.(\d+)\.mixer\.(q|k|v|o)_proj\.") +_FUSED_RE = re.compile(r"^blocks\.(\d+)\.mixer\.qkv_proj\.weight$") + + +def _to_numpy_u16or(dtype: DType, buf: Buffer) -> np.ndarray: + if dtype == DType.bfloat16: + return np.from_dlpack(Buffer.from_dlpack(buf).view(DType.uint16)) + return np.from_dlpack(buf) + + +def _bf16_to_f32(u16: np.ndarray) -> np.ndarray: + return (u16.astype(np.uint32) << 16).view(np.float32) + + +def _f32_to_bf16(x: np.ndarray) -> np.ndarray: + return (x.view(np.uint32) >> 16).astype(np.uint16) + + +def _load_lora(lora_dir: str) -> tuple[dict, float, int]: + from safetensors.numpy import load_file + + cfg = json.loads(open(os.path.join(lora_dir, "adapter_config.json")).read()) + r = int(cfg.get("r", 0)) + alpha = float(cfg.get("lora_alpha", r)) + scale = (alpha / r) if r else 1.0 + sd = load_file(os.path.join(lora_dir, "adapter_model.safetensors")) + by: dict[tuple[int, str], dict[str, np.ndarray]] = {} + for name, value in sd.items(): + m = _LORA_PROJ_RE.search(name) + if not m: + continue + layer, proj = int(m.group(1)), m.group(2) + if name.endswith("lora_A.weight"): + by.setdefault((layer, proj), {})["A"] = value + elif name.endswith("lora_B.weight"): + by.setdefault((layer, proj), {})["B"] = value + return by, scale, r + + +def _delta(a: np.ndarray, b: np.ndarray, scale: float) -> np.ndarray: + return (scale * (b.astype(np.float32) @ a.astype(np.float32))).astype( + np.float32 + ) + + +def _apply_lora_fused( + wd: WeightData, + lora: dict[str, np.ndarray], + scale: float, + q_dim: int, + kv_dim: int, +) -> WeightData: + """q/k/v deltas folded into the fused qkv weight (rows: q|k|v).""" + hidden = int(wd.shape[1]) + dtype = wd.dtype + data = _to_numpy_u16or(dtype, wd.data) + w32 = _bf16_to_f32(data) if dtype == DType.bfloat16 else data.astype(np.float32) + q = w32[:q_dim] + k = w32[q_dim : q_dim + kv_dim] + v = w32[q_dim + kv_dim :] + if "A" in lora.get("q", {}) : + q = q + _delta(lora["q"]["A"], lora["q"]["B"], scale) + if "A" in lora.get("k", {}): + k = k + _delta(lora["k"]["A"], lora["k"]["B"], scale) + if "A" in lora.get("v", {}): + v = v + _delta(lora["v"]["A"], lora["v"]["B"], scale) + fused = np.ascontiguousarray(np.concatenate([q, k, v], axis=0)) + out_rows = q_dim + 2 * kv_dim + if dtype == DType.bfloat16: + buf = Buffer.from_dlpack(_f32_to_bf16(fused)).view( + dtype=DType.uint16, shape=(out_rows, hidden) + ) + # keep the bf16 view for the engine + buf = buf.view(dtype=DType.bfloat16, shape=(out_rows, hidden)) + else: + buf = Buffer.from_dlpack(fused).view(dtype=dtype, shape=(out_rows, hidden)) + return WeightData( + data=buf, + name=wd.name, + dtype=dtype, + shape=Shape([out_rows, hidden]), + quantization_encoding=wd.quantization_encoding, + ) + + +def _expand_fused_kv( + wd: WeightData, *, n_heads: int, n_kv: int, head_dim: int, expansion: int +) -> WeightData: + q_dim = n_heads * head_dim + kv_dim = n_kv * head_dim + hidden = int(wd.shape[1]) + rows = int(wd.shape[0]) + if rows != q_dim + 2 * kv_dim: + raise ValueError(f"unexpected fused qkv rows {rows}; expected {q_dim + 2 * kv_dim}") + data = _to_numpy_u16or(wd.dtype, wd.data) + q = data[:q_dim] + k = data[q_dim : q_dim + kv_dim] + v = data[q_dim + kv_dim :] + + def rep(block: np.ndarray) -> np.ndarray: + block = block.reshape(n_kv, head_dim, hidden) + block = np.repeat(block, expansion, axis=0) + return block.reshape(n_kv * expansion * head_dim, hidden) + + new_kv_dim = kv_dim * expansion + fused = np.ascontiguousarray(np.concatenate([q, rep(k), rep(v)], axis=0)) + out_rows = q_dim + 2 * new_kv_dim + buf = Buffer.from_dlpack(fused).view(dtype=wd.dtype, shape=(out_rows, hidden)) + return WeightData( + data=buf, + name=wd.name, + dtype=wd.dtype, + shape=Shape([out_rows, hidden]), + quantization_encoding=wd.quantization_encoding, + ) + + +def convert_kvexp_nemotron_h_state_dict( + state_dict, huggingface_config, pipeline_config, **unused_kwargs +): + base = convert_nemotron_h_state_dict( + state_dict, huggingface_config, pipeline_config, **unused_kwargs + ) + + n_heads = int(huggingface_config.num_attention_heads) + n_kv = int(huggingface_config.num_key_value_heads) + head_dim = resolve_attention_head_dim(huggingface_config) + q_dim = n_heads * head_dim + kv_dim = n_kv * head_dim + + # --- Track A: optional PEFT LoRA fold-in (before KV expansion) --- + lora_dir = os.environ.get("ATLAS_LORA_DIR") + if lora_dir: + by, scale, rank = _load_lora(lora_dir) + msg = ( + f"[lora] folding adapter {lora_dir} (r={rank}, scale={scale}) " + f"into {len({k[0] for k in by})} attention layers" + ) + print(msg, flush=True) + try: + with open(os.path.join(lora_dir, ".folded"), "a") as _f: + import time as _t + + _f.write(f"{_t.time()} {msg}\n") + except OSError: + pass + for name, wd in list(base.items()): + m = _FUSED_RE.match(name) + if not m: + continue + layer = int(m.group(1)) + per_proj = {p: by.get((layer, p), {}) for p in ("q", "k", "v")} + base[name] = _apply_lora_fused(wd, per_proj, scale, q_dim, kv_dim) + # o_proj deltas + for (layer, proj), ab in by.items(): + if proj != "o" or "A" not in ab: + continue + oname = f"blocks.{layer}.mixer.o_proj.weight" + wd = base.get(oname) + if wd is None: + continue + if wd.dtype == DType.bfloat16: + w32 = _bf16_to_f32(_to_numpy_u16or(wd.dtype, wd.data)) + else: + w32 = _to_numpy_u16or(wd.dtype, wd.data).astype(np.float32) + w32 = w32 + _delta(ab["A"], ab["B"], scale) + if wd.dtype == DType.bfloat16: + buf = Buffer.from_dlpack(_f32_to_bf16(w32)).view(DType.uint16) + buf = buf.view(dtype=DType.bfloat16, shape=wd.shape) + else: + buf = Buffer.from_dlpack(w32).view(dtype=wd.dtype, shape=wd.shape) + base[oname] = WeightData( + data=buf, name=wd.name, dtype=wd.dtype, shape=wd.shape, + quantization_encoding=wd.quantization_encoding, + ) + + # --- KV-head replication for the MAX Mojo GQA kernel (group <= 8) --- + expansion = kv_expansion_factor(huggingface_config) + if expansion == 1: + return base + for name, wd in list(base.items()): + if name.endswith(".mixer.qkv_proj.weight"): + base[name] = _expand_fused_kv( + wd, n_heads=n_heads, n_kv=n_kv, head_dim=head_dim, expansion=expansion + ) + return base \ No newline at end of file ```