interplane.Get Omega
Read in your language

aien-sovereign-core

Autonomous sovereign intelligence engine and runtime core for NVIDIA DGX Spark

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core / modular / nemotron_h_kvexp / weight_adapters.py

216 lines · 7985 bytes Raw Blame History
1"""Weight adapter: built-in Nemotron-H adapter, + optional PEFT LoRA fold-in,
2then KV-head replication for MAX's GQA kernel (group 16 -> 8).
3
4Track A: set ``MAX_LORA_DIR`` to a PEFT adapter directory (adapter_config.json +
5adapter_model.safetensors). Its q/k/v/o LoRA weights are folded into the base
6projections *before* qkv fusion, using delta = (alpha/r) * B @ A. This lets an
7adapter trained with NeMo/PEFT be served on MAX for NemotronH without MAX's
8Llama-3-only runtime LoRA path. The adapter is baked at load time.
9"""
10
11from __future__ import annotations
12
13import json
14import os
15import re
16
17import numpy as np
18from max.driver import Buffer
19from max.dtype import DType
20from max.graph.weights import WeightData
21from max.graph.weights.weights import Shape
22from max.pipelines.architectures.nemotron_h.model_config import (
23 resolve_attention_head_dim,
24)
25from max.pipelines.architectures.nemotron_h.weight_adapters import (
26 convert_nemotron_h_state_dict,
27)
28
29from .config import kv_expansion_factor
30
31_LORA_PROJ_RE = re.compile(r"layers\.(\d+)\.mixer\.(q|k|v|o)_proj\.")
32_FUSED_RE = re.compile(r"^blocks\.(\d+)\.mixer\.qkv_proj\.weight$")
33
34
35def _to_numpy_u16or(dtype: DType, buf: Buffer) -> np.ndarray:
36 if dtype == DType.bfloat16:
37 return np.from_dlpack(Buffer.from_dlpack(buf).view(DType.uint16))
38 return np.from_dlpack(buf)
39
40
41def _bf16_to_f32(u16: np.ndarray) -> np.ndarray:
42 return (u16.astype(np.uint32) << 16).view(np.float32)
43
44
45def _f32_to_bf16(x: np.ndarray) -> np.ndarray:
46 return (x.view(np.uint32) >> 16).astype(np.uint16)
47
48
49def _load_lora(lora_dir: str) -> tuple[dict, float, int]:
50 from safetensors.numpy import load_file
51
52 cfg = json.loads(open(os.path.join(lora_dir, "adapter_config.json")).read())
53 r = int(cfg.get("r", 0))
54 alpha = float(cfg.get("lora_alpha", r))
55 scale = (alpha / r) if r else 1.0
56 sd = load_file(os.path.join(lora_dir, "adapter_model.safetensors"))
57 by: dict[tuple[int, str], dict[str, np.ndarray]] = {}
58 for name, value in sd.items():
59 m = _LORA_PROJ_RE.search(name)
60 if not m:
61 continue
62 layer, proj = int(m.group(1)), m.group(2)
63 if name.endswith("lora_A.weight"):
64 by.setdefault((layer, proj), {})["A"] = value
65 elif name.endswith("lora_B.weight"):
66 by.setdefault((layer, proj), {})["B"] = value
67 return by, scale, r
68
69
70def _delta(a: np.ndarray, b: np.ndarray, scale: float) -> np.ndarray:
71 return (scale * (b.astype(np.float32) @ a.astype(np.float32))).astype(
72 np.float32
73 )
74
75
76def _apply_lora_fused(
77 wd: WeightData,
78 lora: dict[str, np.ndarray],
79 scale: float,
80 q_dim: int,
81 kv_dim: int,
82) -> WeightData:
83 """q/k/v deltas folded into the fused qkv weight (rows: q|k|v)."""
84 hidden = int(wd.shape[1])
85 dtype = wd.dtype
86 data = _to_numpy_u16or(dtype, wd.data)
87 w32 = _bf16_to_f32(data) if dtype == DType.bfloat16 else data.astype(np.float32)
88 q = w32[:q_dim]
89 k = w32[q_dim : q_dim + kv_dim]
90 v = w32[q_dim + kv_dim :]
91 if "A" in lora.get("q", {}) :
92 q = q + _delta(lora["q"]["A"], lora["q"]["B"], scale)
93 if "A" in lora.get("k", {}):
94 k = k + _delta(lora["k"]["A"], lora["k"]["B"], scale)
95 if "A" in lora.get("v", {}):
96 v = v + _delta(lora["v"]["A"], lora["v"]["B"], scale)
97 fused = np.ascontiguousarray(np.concatenate([q, k, v], axis=0))
98 out_rows = q_dim + 2 * kv_dim
99 if dtype == DType.bfloat16:
100 buf = Buffer.from_dlpack(_f32_to_bf16(fused)).view(
101 dtype=DType.uint16, shape=(out_rows, hidden)
102 )
103 # keep the bf16 view for the engine
104 buf = buf.view(dtype=DType.bfloat16, shape=(out_rows, hidden))
105 else:
106 buf = Buffer.from_dlpack(fused).view(dtype=dtype, shape=(out_rows, hidden))
107 return WeightData(
108 data=buf,
109 name=wd.name,
110 dtype=dtype,
111 shape=Shape([out_rows, hidden]),
112 quantization_encoding=wd.quantization_encoding,
113 )
114
115
116def _expand_fused_kv(
117 wd: WeightData, *, n_heads: int, n_kv: int, head_dim: int, expansion: int
118) -> WeightData:
119 q_dim = n_heads * head_dim
120 kv_dim = n_kv * head_dim
121 hidden = int(wd.shape[1])
122 rows = int(wd.shape[0])
123 if rows != q_dim + 2 * kv_dim:
124 raise ValueError(f"unexpected fused qkv rows {rows}; expected {q_dim + 2 * kv_dim}")
125 data = _to_numpy_u16or(wd.dtype, wd.data)
126 q = data[:q_dim]
127 k = data[q_dim : q_dim + kv_dim]
128 v = data[q_dim + kv_dim :]
129
130 def rep(block: np.ndarray) -> np.ndarray:
131 block = block.reshape(n_kv, head_dim, hidden)
132 block = np.repeat(block, expansion, axis=0)
133 return block.reshape(n_kv * expansion * head_dim, hidden)
134
135 new_kv_dim = kv_dim * expansion
136 fused = np.ascontiguousarray(np.concatenate([q, rep(k), rep(v)], axis=0))
137 out_rows = q_dim + 2 * new_kv_dim
138 buf = Buffer.from_dlpack(fused).view(dtype=wd.dtype, shape=(out_rows, hidden))
139 return WeightData(
140 data=buf,
141 name=wd.name,
142 dtype=wd.dtype,
143 shape=Shape([out_rows, hidden]),
144 quantization_encoding=wd.quantization_encoding,
145 )
146
147
148def convert_kvexp_nemotron_h_state_dict(
149 state_dict, huggingface_config, pipeline_config, **unused_kwargs
150):
151 base = convert_nemotron_h_state_dict(
152 state_dict, huggingface_config, pipeline_config, **unused_kwargs
153 )
154
155 n_heads = int(huggingface_config.num_attention_heads)
156 n_kv = int(huggingface_config.num_key_value_heads)
157 head_dim = resolve_attention_head_dim(huggingface_config)
158 q_dim = n_heads * head_dim
159 kv_dim = n_kv * head_dim
160
161 # --- Track A: optional PEFT LoRA fold-in (before KV expansion) ---
162 lora_dir = os.environ.get("MAX_LORA_DIR") or os.environ.get("ATLAS_LORA_DIR")
163 if lora_dir:
164 by, scale, rank = _load_lora(lora_dir)
165 msg = (
166 f"[lora] folding adapter {lora_dir} (r={rank}, scale={scale}) "
167 f"into {len({k[0] for k in by})} attention layers"
168 )
169 print(msg, flush=True)
170 try:
171 with open(os.path.join(lora_dir, ".folded"), "a") as _f:
172 import time as _t
173
174 _f.write(f"{_t.time()} {msg}\n")
175 except OSError:
176 pass
177 for name, wd in list(base.items()):
178 m = _FUSED_RE.match(name)
179 if not m:
180 continue
181 layer = int(m.group(1))
182 per_proj = {p: by.get((layer, p), {}) for p in ("q", "k", "v")}
183 base[name] = _apply_lora_fused(wd, per_proj, scale, q_dim, kv_dim)
184 # o_proj deltas
185 for (layer, proj), ab in by.items():
186 if proj != "o" or "A" not in ab:
187 continue
188 oname = f"blocks.{layer}.mixer.o_proj.weight"
189 wd = base.get(oname)
190 if wd is None:
191 continue
192 if wd.dtype == DType.bfloat16:
193 w32 = _bf16_to_f32(_to_numpy_u16or(wd.dtype, wd.data))
194 else:
195 w32 = _to_numpy_u16or(wd.dtype, wd.data).astype(np.float32)
196 w32 = w32 + _delta(ab["A"], ab["B"], scale)
197 if wd.dtype == DType.bfloat16:
198 buf = Buffer.from_dlpack(_f32_to_bf16(w32)).view(DType.uint16)
199 buf = buf.view(dtype=DType.bfloat16, shape=wd.shape)
200 else:
201 buf = Buffer.from_dlpack(w32).view(dtype=wd.dtype, shape=wd.shape)
202 base[oname] = WeightData(
203 data=buf, name=wd.name, dtype=wd.dtype, shape=wd.shape,
204 quantization_encoding=wd.quantization_encoding,
205 )
206
207 # --- KV-head replication for the MAX Mojo GQA kernel (group <= 8) ---
208 expansion = kv_expansion_factor(huggingface_config)
209 if expansion == 1:
210 return base
211 for name, wd in list(base.items()):
212 if name.endswith(".mixer.qkv_proj.weight"):
213 base[name] = _expand_fused_kv(
214 wd, n_heads=n_heads, n_kv=n_kv, head_dim=head_dim, expansion=expansion
215 )
216 return base