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-sovereign-core-mv/patches/8974796859ddca07 # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-sovereign-core-mv#178 (code only) closed derived `8974796859ddca07` #178 Imported from GitHub aien-dev/aien-sovereign-core-mv#178 (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 `5fdab70b943443a6e0b3f9a4a45438e632d11623` · Head `25efa00c4999f5e71397b01ec52e80b0c9dffc63` ### Apply it ``` git checkout -b patch-8974796859ddca07 5fdab70b943443a6e0b3f9a4a45438e632d11623 curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/8974796859ddca07.patch | git am ``` Raw patch (mbox) · 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-sovereign-core-mv 178 25efa00c4999f5e71397b01ec52e80b0c9dffc63 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":178,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/178","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:12Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/README.md b/README.md index cf3d6f73..832a4735 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,8 @@ The earlier **Linux-hosted** AIEN runtime, written in Rust: agent CLI, persisten **This repository is legacy.** AIEN's own stack (the [aienos](https://github.com/aien-dev/aienos) kernel, the [omega](https://github.com/aien-dev/omega) runtime, [physics](https://github.com/aien-dev/physics) FORGE) is replacing it. Under [ADR 0024](https://github.com/aien-dev/aien-architecture/blob/main/docs/adr/0024-rust-scaffolding-omega-destination.md), working Rust here is kept as temporary scaffolding, not rewritten into C: it stays behind language-neutral boundaries and Omega replaces components one at a time after passing the same conformance tests. New Rust is allowed where it is not hardware-bound (for example the DEV-MODEL-0 program, a local development model on AIEN-owned inference). Component ownership (for example the Cortex now owned by omega, per ADR 0022) is recorded in [aien-architecture](https://github.com/aien-dev/aien-architecture); here `crates/cortex-rs` is non-authoritative and to be retired, not ported. +Outside yardsticks (Modular MAX and others) live in [aien-yardsticks](https://github.com/aien-dev/aien-yardsticks), not here. No Python in this repo. + > SUPERSEDED 2026-10-01 by [ADR 0024](https://github.com/aien-dev/aien-architecture/blob/main/docs/adr/0024-rust-scaffolding-omega-destination.md). Previous text, kept as history: **This repository is legacy.** The project's target language is C, and AIEN's own stack (the [aienos](https://github.com/aien-dev/aienos) kernel, the [omega](https://github.com/aien-dev/omega) runtime, [physics](https://github.com/aien-dev/physics) FORGE) is replacing it. No new Rust is added here, with one declared exception: the DEV-MODEL-0 program (a local development model on AIEN-owned inference) may temporarily extend this Rust substrate while the C replacements are built. Component ownership (for example the Cortex now owned by omega, per ADR 0022) is recorded in [aien-architecture](https://github.com/aien-dev/aien-architecture); here `crates/cortex-rs` is non-authoritative and to be retired, not ported. ## Current state diff --git a/crates/aien-cli/src/walkthrough.rs b/crates/aien-cli/src/walkthrough.rs index f2f85821..faec3c2e 100644 --- a/crates/aien-cli/src/walkthrough.rs +++ b/crates/aien-cli/src/walkthrough.rs @@ -306,7 +306,7 @@ graph TD - [x] **Phase 1: Workspace Sanitation & Model Alignment** - Reclaimed 74 GB of NVMe disk space; 501 GB available. - - Locked inference strictly to Modular MAX on port `18006` serving NVIDIA-native `nemotron_h_kvexp` (`atlas-lightning-omni`). + - Locked inference strictly to Modular MAX on port `18006` serving NVIDIA-native `nemotron_h_kvexp` (`atlas-lightning-omni`; the adapter now lives in the aien-yardsticks repo). - [x] **Phase 2: Native AIEN Terminal CLI (`aien-cli`)** - High-performance Rust binary installed to `~/.local/bin/aien`. - ANSI streaming, collapsible tool widgets, GB10 GPU telemetry status footer, persistent history. diff --git a/docs/dev-model-0/DEV_MODEL_0_CODE_AUDIT.md b/docs/dev-model-0/DEV_MODEL_0_CODE_AUDIT.md index 99883bb9..8993b769 100644 --- a/docs/dev-model-0/DEV_MODEL_0_CODE_AUDIT.md +++ b/docs/dev-model-0/DEV_MODEL_0_CODE_AUDIT.md @@ -91,7 +91,7 @@ Sampling happens on host after full logits are read back (`transformer_backend.r Python files in repo: 11 (confirmed). None is imported or shelled out to from the inference path. - `scripts/generate_tinyllama_oracle.py`: offline HF Transformers/torch oracle generator for the TinyLlama fixtures (`abi/fixtures/tinyllama_oracle*`). Offline tool, precedent for brief section 4. Violates the no-Python rule if kept in-repo; Phase E should replace by C/shell tooling or keep outside the repo with only artifacts committed. - `scripts/aien_drive.py`, `scripts/browser_mirror_test.py`: agent driver and browser test harness. `crates/aien-cli/src/sandbox.rs:363-374` and `platform.rs:87-91` shell out to `python`/`browser_mirror_test.py`; `commands.rs:184,202` calls `basecamp/aien-dream/dream_engine.py` (outside repo). None in the inference path. -- `modular/nemotron_h_kvexp/{__init__,arch,config,model,weight_adapters}.py`, `tests/{__init__,test_kvexp}.py`, `benchmarks/bench_kv_expansion.py`: a MAX architecture plugin for Nemotron-H. Not referenced by any Rust crate. +- `modular/nemotron_h_kvexp` (a MAX architecture plugin for Nemotron-H, not referenced by any Rust crate): MOVED 2026-10-04 out of this repo to https://github.com/aien-dev/aien-yardsticks (`yardsticks/modular-nemotron-h-kvexp`), history preserved. - Python also appears inside shell scripts (`scripts/golden_path.sh`, `mac-platform-proxy.sh`, `sync-standalone-repos.sh:127`). Out of scope for DM0 but they are Python-in-shell, relevant to the standing rule. Mojo kernels present: `abi/mojo/lib.mojo` (299), `abi/mojo/qwen3_moe/{kernels,lib}.mojo`, `abi/mojo/qwencoder_serve/{qwencoder_kernels,qwencoder_serve,test_kernels}.mojo`, `crates/spark-max-cabi/mojo/spark_max_bridge.mojo`, `crates/spark-aegis/mojo/simd_matcher.mojo`, `imprints/en2-trinity/mojo/en2_kv_adapter.mojo`. Built by `abi/mojo/build.sh` with `mojo build --emit shared-lib`. diff --git a/modular/nemotron_h_kvexp/README.md b/modular/nemotron_h_kvexp/README.md deleted file mode 100644 index e1281372..00000000 --- a/modular/nemotron_h_kvexp/README.md +++ /dev/null @@ -1,77 +0,0 @@ -# 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/modular/nemotron_h_kvexp/__init__.py b/modular/nemotron_h_kvexp/__init__.py deleted file mode 100644 index f0b4617a..00000000 --- a/modular/nemotron_h_kvexp/__init__.py +++ /dev/null @@ -1,32 +0,0 @@ -"""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/modular/nemotron_h_kvexp/arch.py b/modular/nemotron_h_kvexp/arch.py deleted file mode 100644 index 4e012b6d..00000000 --- a/modular/nemotron_h_kvexp/arch.py +++ /dev/null @@ -1,48 +0,0 @@ -"""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/modular/nemotron_h_kvexp/benchmarks/.crumb b/modular/nemotron_h_kvexp/benchmarks/.crumb deleted file mode 100644 index 272b9eba..00000000 --- a/modular/nemotron_h_kvexp/benchmarks/.crumb +++ /dev/null @@ -1,22 +0,0 @@ -{ - "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/modular/nemotron_h_kvexp/benchmarks/bench_kv_expansion.py b/modular/nemotron_h_kvexp/benchmarks/bench_kv_expansion.py deleted file mode 100644 index 2909c2a0..00000000 --- a/modular/nemotron_h_kvexp/benchmarks/bench_kv_expansion.py +++ /dev/null @@ -1,58 +0,0 @@ -"""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/modular/nemotron_h_kvexp/config.py b/modular/nemotron_h_kvexp/config.py deleted file mode 100644 index 5145eaa9..00000000 --- a/modular/nemotron_h_kvexp/config.py +++ /dev/null @@ -1,87 +0,0 @@ -"""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/modular/nemotron_h_kvexp/model.py b/modular/nemotron_h_kvexp/model.py deleted file mode 100644 index 4c5fcc39..00000000 --- a/modular/nemotron_h_kvexp/model.py +++ /dev/null @@ -1,33 +0,0 @@ -"""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/modular/nemotron_h_kvexp/pyproject.toml b/modular/nemotron_h_kvexp/pyproject.toml deleted file mode 100644 index 7357c2a4..00000000 --- a/modular/nemotron_h_kvexp/pyproject.toml +++ /dev/null @@ -1,31 +0,0 @@ -[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/modular/nemotron_h_kvexp/tests/.crumb b/modular/nemotron_h_kvexp/tests/.crumb deleted file mode 100644 index 6b353960..00000000 --- a/modular/nemotron_h_kvexp/tests/.crumb +++ /dev/null @@ -1,22 +0,0 @@ -{ - "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/modular/nemotron_h_kvexp/tests/__init__.py b/modular/nemotron_h_kvexp/tests/__init__.py deleted file mode 100644 index 59d9449d..00000000 --- a/modular/nemotron_h_kvexp/tests/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# Test package for nemotron_h_kvexp diff --git a/modular/nemotron_h_kvexp/tests/test_kvexp.py b/modular/nemotron_h_kvexp/tests/test_kvexp.py deleted file mode 100644 index 589b292a..00000000 --- a/modular/nemotron_h_kvexp/tests/test_kvexp.py +++ /dev/null @@ -1,97 +0,0 @@ -"""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/modular/nemotron_h_kvexp/weight_adapters.py b/modular/nemotron_h_kvexp/weight_adapters.py deleted file mode 100644 index cd8a20ce..00000000 --- a/modular/nemotron_h_kvexp/weight_adapters.py +++ /dev/null @@ -1,216 +0,0 @@ -"""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 diff --git a/scripts/start_max_lightning_18006.sh b/scripts/start_max_lightning_18006.sh index 936fdb4a..9b0aadac 100755 --- a/scripts/start_max_lightning_18006.sh +++ b/scripts/start_max_lightning_18006.sh @@ -18,7 +18,7 @@ exec /home/drakestapleton/max-env/bin/max serve \ --model nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16 \ "${WEIGHT_ARGS[@]}" \ --served-model-name atlas-lightning-omni \ - --custom-architectures /home/drakestapleton/nemotron_h_kvexp \ + --custom-architectures /home/drakestapleton/workspace/aien-yardsticks/yardsticks/modular-nemotron-h-kvexp \ --port 18006 \ --max-batch-size 8 \ --max-length 32768 \ diff --git a/skills/modular-upstream/SKILL.md b/skills/modular-upstream/SKILL.md index a59876b4..29ee0df6 100644 --- a/skills/modular-upstream/SKILL.md +++ b/skills/modular-upstream/SKILL.md @@ -9,12 +9,12 @@ Use this skill when developing, testing, packaging, or submitting pull requests ## Sovereign Mission & Upstream Invariant -1. **The Upstream Invariant ("Drop != Delete")**: Any modification, patch, or novel architecture developed on our Grace Blackwell GB10 stack (such as `nemotron_h_kvexp` or MAX custom kernel pipelines) must be contributed back upstream to Modular. +1. **The Upstream Invariant ("Drop != Delete")**: Any modification, patch, or novel architecture developed on our Grace Blackwell GB10 stack (such as `nemotron_h_kvexp`, now in the aien-yardsticks repo, or MAX custom kernel pipelines) must be contributed back upstream to Modular. 2. **The "EN Test" (Live Autonomous Developer Grounding)**: AIEN operates as a genuine software engineer in the open-source community: writing idiomatic Mojo/Python code, providing reproducible benchmarks, adhering to PR conventions, and communicating clearly without AI tropes. ## Workspace & Subsystems -- `nemotron_h_kvexp`: Our custom MAX architecture loader for Nemotron 30B KV-cache expansion. +- `nemotron_h_kvexp`: Our custom MAX architecture loader for Nemotron 30B KV-cache expansion. It is a yardstick and lives outside AIEN in https://github.com/aien-dev/aien-yardsticks (path `yardsticks/modular-nemotron-h-kvexp`). - `max-env` / `max-dev-env`: Modular MAX Python 3.12 virtual environments with `max` CLI and `modular` SDK. - `modular_sandbox_project`: Isolated workspace for authoring and benchmarking new Mojo modules. @@ -23,8 +23,8 @@ Use this skill when developing, testing, packaging, or submitting pull requests ### 1. Inspect Local Custom Architectures Examine how custom architecture interfaces, model configs, and weight adapters hook into MAX: ```bash -ls -la ~/nemotron_h_kvexp -cat ~/nemotron_h_kvexp/arch.py +ls -la ~/workspace/aien-yardsticks/yardsticks/modular-nemotron-h-kvexp +cat ~/workspace/aien-yardsticks/yardsticks/modular-nemotron-h-kvexp/arch.py ``` ### 2. Verify MAX Serving & Pipelines ```