Kernels
TaehyunKim commited on
Commit
f9603cb
·
unverified ·
2 Parent(s): a85f310f0a2f2b

Merge pull request #36 from MotifTechnologies/fix/qk-clip-sharded-row-exponents

Browse files
test/test_qk_clip_sharded.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """QK-clip on the sharded Muon paths must scale each row by its sub-region's
2
+ exponent, as ``qk_clip`` does on the base path:
3
+
4
+ MHA q/k rows : √γ MLA q_nope : γ^(1-k_ratio) MLA q_pe : γ
5
+ MLA k_nope : γ^k_ratio MLA v rows : untouched
6
+
7
+ The parallel (all2all) and distributed_muon paths used to multiply every row
8
+ of a head by one value (the raw γ since compute_scales returns it), so the
9
+ value rows of wkv_b and the q_nope rows of wq_b were clipped too.
10
+
11
+ Each case runs Muon twice from the same weights and gradients, with and
12
+ without QK-clip, and checks clipped / unclipped row by row against the
13
+ exponents above, on the base path and on the sharded paths (shard boundaries
14
+ cut through heads). Two steps, so the second one goes through the cached
15
+ parallel state.
16
+
17
+ Run: torchrun --nproc-per-node=8 --local-ranks-filter=0 -m pytest test_qk_clip_sharded.py
18
+ or, on any number of GPUs: torchrun --nproc-per-node=4 test_qk_clip_sharded.py
19
+ """
20
+
21
+ import logging
22
+
23
+ import pytest
24
+ import torch
25
+ import torch.distributed as dist
26
+ from optimizer.muon import Muon
27
+ from optimizer.newton_schulz import set_ns_compile
28
+ from torch.distributed.tensor import Replicate, Shard, distribute_tensor
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+ THRESHOLD = 10.0
33
+ K_RATIO = 0.31
34
+ # 6 query heads in 2 KV groups of 3; heads 0, 2, 5 exceed the threshold.
35
+ LOGITS = [12.0, 5.0, 30.0, 8.0, 9.0, 20.0]
36
+ KV_OF_Q = [0, 0, 0, 1, 1, 1]
37
+ NOPE, ROPE, VDIM, MHA_HD, IN = 24, 8, 40, 16, 48
38
+
39
+
40
+ def _cases():
41
+ mla = dict(
42
+ names=[
43
+ "layers.0.attention.wq_b.weight", # 6 heads x (24 + 8) = 192 rows
44
+ "layers.0.attention.wkv_b.weight", # 2 heads x (24 + 40) = 128 rows
45
+ "layers.0.feed_forward.w1.weight", # control, never clipped
46
+ ],
47
+ shapes=[(6 * (NOPE + ROPE), IN), (2 * (NOPE + VDIM), IN), (96, IN)],
48
+ clip_config=dict(q_indices=list(range(6)),
49
+ k_indices=KV_OF_Q,
50
+ head_dim=NOPE + ROPE,
51
+ threshold=THRESHOLD,
52
+ is_mla=True,
53
+ qk_nope_head_dim=NOPE,
54
+ qk_rope_head_dim=ROPE,
55
+ v_head_dim=VDIM,
56
+ k_ratio=K_RATIO),
57
+ head_keys={
58
+ "wq_b": NOPE + ROPE,
59
+ "wkv_b": NOPE + VDIM
60
+ },
61
+ )
62
+ mha = dict(
63
+ names=[
64
+ "layers.0.self_attn.q_proj.weight", # 6 heads x 16 = 96 rows
65
+ "layers.0.self_attn.k_proj.weight",
66
+ "layers.0.mlp.up_proj.weight",
67
+ ],
68
+ shapes=[(6 * MHA_HD, IN), (6 * MHA_HD, IN), (96, IN)],
69
+ clip_config=dict(q_indices=list(range(6)),
70
+ k_indices=list(range(6)),
71
+ head_dim=MHA_HD,
72
+ threshold=THRESHOLD),
73
+ head_keys=None,
74
+ )
75
+ return {"mla": mla, "mha": mha}
76
+
77
+
78
+ def _expected_row_scales(kind):
79
+ """Row multipliers written out independently of the optimizer code."""
80
+ gq = [min(1.0, THRESHOLD / v) for v in LOGITS]
81
+ if kind == "mha":
82
+ q = torch.tensor(gq).sqrt().repeat_interleave(MHA_HD)
83
+ return [q, q.clone(), torch.ones(96)]
84
+ gkv = [min(g for g, j in zip(gq, KV_OF_Q) if j == kv) for kv in (0, 1)]
85
+ q_rows, kv_rows = [], []
86
+ for g in gq:
87
+ q_rows += [g**(1 - K_RATIO)] * NOPE + [g] * ROPE
88
+ for g in gkv:
89
+ kv_rows += [g**K_RATIO] * NOPE + [1.0] * VDIM
90
+ return [torch.tensor(q_rows), torch.tensor(kv_rows), torch.ones(96)]
91
+
92
+
93
+ def _group(params, names):
94
+ return [{
95
+ "params": params,
96
+ "names": names,
97
+ "use_muon": True,
98
+ "lr": 0.02,
99
+ "weight_decay": 0.01,
100
+ "momentum": 0.95,
101
+ "nesterov": True,
102
+ "ns_steps": 5,
103
+ "none_grad": False,
104
+ }]
105
+
106
+
107
+ def _run(case, fulls, grads, clip, mesh=None, placements=None, **kw):
108
+ if mesh is None:
109
+ params = [torch.nn.Parameter(t.clone()) for t in fulls]
110
+ else:
111
+ params = [
112
+ torch.nn.Parameter(distribute_tensor(t.clone(), mesh, placements))
113
+ for t in fulls
114
+ ]
115
+ optim = Muon(params=_group(params, list(case["names"])),
116
+ clip_config=case["clip_config"] if clip else None,
117
+ head_keys=case["head_keys"],
118
+ **kw)
119
+ logits = {0: torch.tensor(LOGITS, device="cuda")} if clip else None
120
+ for step_grads in grads:
121
+ for p, g in zip(params, step_grads):
122
+ p.grad = g.clone() if mesh is None else distribute_tensor(
123
+ g.clone(), mesh, p.data.placements)
124
+ optim.step(qk_logits=logits)
125
+ return [p.data if mesh is None else p.data.full_tensor() for p in params]
126
+
127
+
128
+ def _check(kind, mesh=None, placements=None, **kw):
129
+ """One step with and one without QK-clip from the same weights and
130
+ gradients: the clip is applied after the update, so clipped / unclipped
131
+ is exactly the row multiplier."""
132
+ case = _cases()[kind]
133
+ torch.manual_seed(0)
134
+ fulls = [torch.randn(s, device="cuda") for s in case["shapes"]]
135
+ grads = [[torch.randn(s, device="cuda") for s in case["shapes"]]]
136
+ clipped = _run(case, fulls, grads, True, mesh, placements, **kw)
137
+ plain = _run(case, fulls, grads, False, mesh, placements, **kw)
138
+ for name, c, u, want in zip(case["names"], clipped, plain,
139
+ _expected_row_scales(kind)):
140
+ got = (c / u).median(dim=1).values.cpu()
141
+ torch.testing.assert_close(got,
142
+ want,
143
+ rtol=1e-5,
144
+ atol=1e-6,
145
+ msg=lambda m: f"{kind} {name}: {m}")
146
+ torch.testing.assert_close(c.cpu(),
147
+ u.cpu() * want.view(-1, 1),
148
+ rtol=1e-5,
149
+ atol=1e-6,
150
+ msg=lambda m: f"{kind} {name}: {m}")
151
+
152
+
153
+ def _check_two_steps_match_base(kind, mesh, placements, **kw):
154
+ """Sharded result after two clipped steps equals the base path's."""
155
+ case = _cases()[kind]
156
+ torch.manual_seed(1)
157
+ fulls = [torch.randn(s, device="cuda") for s in case["shapes"]]
158
+ grads = [[torch.randn(s, device="cuda") for s in case["shapes"]]
159
+ for _ in range(2)]
160
+ base = _run(case, fulls, grads, True)
161
+ sharded = _run(case, fulls, grads, True, mesh, placements, **kw)
162
+ for name, b, s in zip(case["names"], base, sharded):
163
+ torch.testing.assert_close(s,
164
+ b,
165
+ rtol=1e-5,
166
+ atol=1e-6,
167
+ msg=lambda m: f"{kind} {name}: {m}")
168
+
169
+
170
+ def _shardings(world):
171
+ out = [((world, ), ("dp_shard", ), [Shard(0)], "fsdp"),
172
+ ((world, ), ("tp", ), [Shard(1)], "tp_row")]
173
+ if world % 2 == 0 and world >= 4:
174
+ out.append(((2, world // 2), ("dp_replicate", "dp_shard"),
175
+ [Replicate(), Shard(0)], "hsdp"))
176
+ out.append(
177
+ ((2, world // 2), ("dp_shard", "tp"), [Shard(0),
178
+ Shard(1)], "fsdp+tp_row"))
179
+ return out
180
+
181
+
182
+ SHARDING_CASES = [pytest.param(s[:3], id=s[3]) for s in _shardings(8)]
183
+
184
+
185
+ @pytest.mark.parametrize("kind", ["mla", "mha"])
186
+ def test_base_path_row_exponents(init_dist, kind):
187
+ set_ns_compile(False)
188
+ _check(kind)
189
+
190
+
191
+ @pytest.mark.parametrize("kind", ["mla", "mha"])
192
+ @pytest.mark.parametrize("sharding", SHARDING_CASES)
193
+ @pytest.mark.parametrize("use_distributed_muon", [False, True],
194
+ ids=["parallel", "distributed"])
195
+ def test_sharded_row_exponents(init_dist, kind, sharding,
196
+ use_distributed_muon):
197
+ set_ns_compile(False)
198
+ shape, dims, placements = sharding
199
+ mesh = dist.init_device_mesh("cuda", shape, mesh_dim_names=dims)
200
+ _check(kind, mesh, placements, use_distributed_muon=use_distributed_muon)
201
+ _check_two_steps_match_base(kind,
202
+ mesh,
203
+ placements,
204
+ use_distributed_muon=use_distributed_muon)
205
+
206
+
207
+ if __name__ == "__main__":
208
+ logging.basicConfig(level=logging.WARNING)
209
+ dist.init_process_group(backend="nccl")
210
+ torch.cuda.set_device(dist.get_rank() % torch.cuda.device_count())
211
+ world = dist.get_world_size()
212
+ set_ns_compile(False)
213
+ failed = 0
214
+ for kind in ("mla", "mha"):
215
+ runs = [("base", None, None, {})]
216
+ for shape, dims, placements, sid in _shardings(world):
217
+ mesh = dist.init_device_mesh("cuda", shape, mesh_dim_names=dims)
218
+ for dm in (False, True):
219
+ runs.append((f"{sid}/{'distributed' if dm else 'parallel'}",
220
+ mesh, placements, {
221
+ "use_distributed_muon": dm
222
+ }))
223
+ for rid, mesh, placements, kw in runs:
224
+ try:
225
+ _check(kind, mesh, placements, **kw)
226
+ if mesh is not None:
227
+ _check_two_steps_match_base(kind, mesh, placements, **kw)
228
+ status = "PASS"
229
+ except AssertionError as e:
230
+ failed += 1
231
+ status = "FAIL " + str(e).splitlines()[0][:300]
232
+ except Exception as e: # raised on every rank alike; go on
233
+ failed += 1
234
+ status = f"ERROR {type(e).__name__}: {str(e).splitlines()[0][:200]}"
235
+ if dist.get_rank() == 0:
236
+ print(f"{kind:4s} {rid:28s} {status}", flush=True)
237
+ dist.destroy_process_group()
238
+ raise SystemExit(1 if failed else 0)
torch-ext/optimizer/muon.py CHANGED
@@ -23,7 +23,8 @@ from .newton_schulz import (COMM_DTYPE, DEFAULT_CHUNK_SIZE_RATIO,
23
  zeropower_via_newtonschulz5_batched,
24
  zeropower_via_newtonschulz5_per_head)
25
  from .pipeline import muon_chunk_pipeline, prelaunch_first_gather
26
- from .qk_clip import compute_scales, get_qk_clip_info, qk_clip
 
27
 
28
  logger = logging.getLogger(__name__)
29
 
@@ -525,29 +526,17 @@ class Muon(torch.optim.Optimizer):
525
  qk_clip_state = get_qk_clip_info(
526
  self.clip_config, n, qk_logits)
527
  scales_full = compute_scales(
528
- p, qk_clip_state, n
529
- ) if qk_clip_state is not None else None
530
  if scales_full is not None:
531
- # scales_full is raw per-head γ; apply the content
532
- # exponent per head (MHA √γ, wq_b γ^(1-r), wkv_b
533
- # γ^r). NOTE: this per-head form cannot resolve the
534
- # MLA rotary/value sub-regions (q_pe → full γ, v
535
- # untouched) — see qk_clip; the sharded path scales
536
- # q_pe/v by the content exponent instead.
537
- if not qk_clip_state.is_mla:
538
- e = 0.5
539
- elif qk_clip_state.kind == 'wq_b':
540
- e = 1.0 - qk_clip_state.k_ratio
541
- else:
542
- e = qk_clip_state.k_ratio
543
- ratio = p.shape[0] // scales_full.shape[0]
544
  idx0 = local_indices[0]
545
  if isinstance(idx0, slice):
546
- start = idx0.start or 0
547
- idx0 = torch.arange(start,
548
- idx0.stop,
549
  device=scales_full.device)
550
- row_scales = (scales_full**e)[idx0 // ratio]
 
551
  p._local_tensor.mul_(row_scales.view(-1, 1))
552
 
553
  if not batch_params:
@@ -615,29 +604,17 @@ class Muon(torch.optim.Optimizer):
615
  qk_clip_state = get_qk_clip_info(
616
  self.clip_config, n, qk_logits)
617
  scales_full = compute_scales(
618
- p, qk_clip_state, n
619
- ) if qk_clip_state is not None else None
620
  if scales_full is not None:
621
- # scales_full is raw per-head γ; apply the content
622
- # exponent per head (MHA √γ, wq_b γ^(1-r), wkv_b
623
- # γ^r). NOTE: this per-head form cannot resolve the
624
- # MLA rotary/value sub-regions (q_pe → full γ, v
625
- # untouched) — see qk_clip; the sharded path scales
626
- # q_pe/v by the content exponent instead.
627
- if not qk_clip_state.is_mla:
628
- e = 0.5
629
- elif qk_clip_state.kind == 'wq_b':
630
- e = 1.0 - qk_clip_state.k_ratio
631
- else:
632
- e = qk_clip_state.k_ratio
633
- ratio = p.shape[0] // scales_full.shape[0]
634
  idx0 = local_indices[0]
635
  if isinstance(idx0, slice):
636
- start = idx0.start or 0
637
- idx0 = torch.arange(start,
638
- idx0.stop,
639
  device=scales_full.device)
640
- row_scales = (scales_full**e)[idx0 // ratio]
 
641
  p._local_tensor.mul_(row_scales.view(-1, 1))
642
 
643
  def _setup_parallel(self, names, params, group, qk_logits):
 
23
  zeropower_via_newtonschulz5_batched,
24
  zeropower_via_newtonschulz5_per_head)
25
  from .pipeline import muon_chunk_pipeline, prelaunch_first_gather
26
+ from .qk_clip import (compute_scales, expand_row_scales, get_qk_clip_info,
27
+ qk_clip)
28
 
29
  logger = logging.getLogger(__name__)
30
 
 
526
  qk_clip_state = get_qk_clip_info(
527
  self.clip_config, n, qk_logits)
528
  scales_full = compute_scales(
529
+ p, qk_clip_state,
530
+ n) if qk_clip_state is not None else None
531
  if scales_full is not None:
532
+ # raw per-head γ → per-row γ**exponent (MHA √γ, q_nope
533
+ # γ^(1-r), q_pe γ, k_nope γ^r, v rows untouched).
 
 
 
 
 
 
 
 
 
 
 
534
  idx0 = local_indices[0]
535
  if isinstance(idx0, slice):
536
+ idx0 = torch.arange(*idx0.indices(p.shape[0]),
 
 
537
  device=scales_full.device)
538
+ row_scales = expand_row_scales(
539
+ scales_full, qk_clip_state)[idx0]
540
  p._local_tensor.mul_(row_scales.view(-1, 1))
541
 
542
  if not batch_params:
 
604
  qk_clip_state = get_qk_clip_info(
605
  self.clip_config, n, qk_logits)
606
  scales_full = compute_scales(
607
+ p, qk_clip_state,
608
+ n) if qk_clip_state is not None else None
609
  if scales_full is not None:
610
+ # raw per-head γ → per-row γ**exponent (MHA √γ, q_nope
611
+ # γ^(1-r), q_pe γ, k_nope γ^r, v rows untouched).
 
 
 
 
 
 
 
 
 
 
 
612
  idx0 = local_indices[0]
613
  if isinstance(idx0, slice):
614
+ idx0 = torch.arange(*idx0.indices(p.shape[0]),
 
 
615
  device=scales_full.device)
616
+ row_scales = expand_row_scales(
617
+ scales_full, qk_clip_state)[idx0]
618
  p._local_tensor.mul_(row_scales.view(-1, 1))
619
 
620
  def _setup_parallel(self, names, params, group, qk_logits):
torch-ext/optimizer/pipeline.py CHANGED
@@ -9,7 +9,7 @@ from torch.profiler import record_function
9
  from .core import _muon_state, adjust_lr_for_muon
10
  from .newton_schulz import (COMM_DTYPE, zeropower_via_newtonschulz5,
11
  zeropower_via_newtonschulz5_per_head)
12
- from .qk_clip import compute_scales
13
 
14
  logger = logging.getLogger(__name__)
15
 
@@ -343,14 +343,15 @@ def _update_params(
343
  continue
344
  scales_full = compute_scales(p, state.qk_clip_state, state.name)
345
  if scales_full is not None:
346
- ratio = p.shape[0] // scales_full.shape[0]
 
 
347
  idx0 = state.rank_indices[rank][0]
348
  if isinstance(idx0, slice):
349
- start = idx0.start or 0
350
- idx0 = torch.arange(start,
351
- idx0.stop,
352
  device=scales_full.device)
353
- row_scales = scales_full[idx0 // ratio]
 
354
  p._local_tensor.mul_(row_scales.view(-1, 1))
355
 
356
 
 
9
  from .core import _muon_state, adjust_lr_for_muon
10
  from .newton_schulz import (COMM_DTYPE, zeropower_via_newtonschulz5,
11
  zeropower_via_newtonschulz5_per_head)
12
+ from .qk_clip import compute_scales, expand_row_scales
13
 
14
  logger = logging.getLogger(__name__)
15
 
 
343
  continue
344
  scales_full = compute_scales(p, state.qk_clip_state, state.name)
345
  if scales_full is not None:
346
+ # compute_scales returns raw per-head γ; expand_row_scales raises
347
+ # each row to its sub-region's exponent (MHA √γ, q_nope γ^(1-r),
348
+ # q_pe γ, k_nope γ^r, v rows untouched), as qk_clip does.
349
  idx0 = state.rank_indices[rank][0]
350
  if isinstance(idx0, slice):
351
+ idx0 = torch.arange(*idx0.indices(p.shape[0]),
 
 
352
  device=scales_full.device)
353
+ row_scales = expand_row_scales(scales_full,
354
+ state.qk_clip_state)[idx0]
355
  p._local_tensor.mul_(row_scales.view(-1, 1))
356
 
357
 
torch-ext/optimizer/qk_clip.py CHANGED
@@ -131,8 +131,9 @@ def compute_scales(p, qk_clip_state, name: str = ''):
131
  Returns a per-head tensor of γ (1.0 for heads under the threshold) if any
132
  head requires clipping, else None. The per-region exponent on γ is NOT
133
  applied here — it is applied at multiply time (``qk_clip`` for the whole
134
- tensor, or the sharded path in muon.py) so that one per-head γ can drive
135
- different sub-regions (q_nope, q_pe, k_nope, v) with different exponents.
 
136
 
137
  wkv_b with k_ratio=0 returns None: the whole reduction is placed on Q and
138
  the key projection is left unclipped.
@@ -178,6 +179,34 @@ def compute_scales(p, qk_clip_state, name: str = ''):
178
  return scales_full
179
 
180
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
  def qk_clip(p, scales, info):
182
  """Apply QK-clip to a Q/K projection weight; each sub-region is raised to
183
  its own exponent so every logit component is reduced by exactly γ.
@@ -200,14 +229,16 @@ def qk_clip(p, scales, info):
200
  r = info.k_ratio
201
 
202
  if not info.is_mla:
203
- W.view(-1, info.head_dim, W.shape[1]).mul_((scales**0.5).view(-1, 1, 1))
 
204
  return
205
 
206
  if info.kind == 'wq_b':
207
  qk_nope = info.qk_nope_head_dim
208
  qk_head_dim = qk_nope + info.qk_rope_head_dim
209
  W_3d = W.view(-1, qk_head_dim, W.shape[1]) # [H, qk_head_dim, in_dim]
210
- W_3d[:, :qk_nope, :].mul_((scales**(1.0 - r)).view(-1, 1, 1)) # q_nope → γ^(1-r)
 
211
  W_3d[:, qk_nope:, :].mul_(scales.view(-1, 1, 1)) # q_pe → γ (full)
212
 
213
  elif info.kind == 'wkv_b':
 
131
  Returns a per-head tensor of γ (1.0 for heads under the threshold) if any
132
  head requires clipping, else None. The per-region exponent on γ is NOT
133
  applied here — it is applied at multiply time (``qk_clip`` for the whole
134
+ tensor, ``expand_row_scales`` per row on the sharded paths) so that one
135
+ per-head γ can drive different sub-regions (q_nope, q_pe, k_nope, v) with
136
+ different exponents.
137
 
138
  wkv_b with k_ratio=0 returns None: the whole reduction is placed on Q and
139
  the key projection is left unclipped.
 
179
  return scales_full
180
 
181
 
182
+ def expand_row_scales(gamma, info):
183
+ """Per-head raw γ ([H]) → per-row multiplier ([H*stride]) = γ ** exponent, the
184
+ exponents of ``qk_clip`` laid out row by row so that a sharded path can index
185
+ them by global row:
186
+
187
+ MHA : √γ on every row.
188
+ MLA q_nope : γ^(1-k_ratio), k_nope : γ^k_ratio (content product = γ).
189
+ MLA q_pe : γ (full).
190
+ MLA v rows : γ^0 = 1, i.e. untouched.
191
+ """
192
+ r = info.k_ratio
193
+ if not info.is_mla:
194
+ exps = torch.full((info.head_dim, ), 0.5)
195
+ elif info.kind == 'wq_b':
196
+ exps = torch.cat([
197
+ torch.full((info.qk_nope_head_dim, ), 1.0 - r),
198
+ torch.ones(info.qk_rope_head_dim)
199
+ ])
200
+ else: # wkv_b
201
+ exps = torch.cat([
202
+ torch.full((info.qk_nope_head_dim, ), r),
203
+ torch.zeros(info.v_head_dim)
204
+ ])
205
+ exps = exps.to(gamma.device) # [stride]
206
+ return (gamma[:,
207
+ None]**exps[None, :]).reshape(-1) # [H*stride], head-major
208
+
209
+
210
  def qk_clip(p, scales, info):
211
  """Apply QK-clip to a Q/K projection weight; each sub-region is raised to
212
  its own exponent so every logit component is reduced by exactly γ.
 
229
  r = info.k_ratio
230
 
231
  if not info.is_mla:
232
+ W.view(-1, info.head_dim, W.shape[1]).mul_(
233
+ (scales**0.5).view(-1, 1, 1))
234
  return
235
 
236
  if info.kind == 'wq_b':
237
  qk_nope = info.qk_nope_head_dim
238
  qk_head_dim = qk_nope + info.qk_rope_head_dim
239
  W_3d = W.view(-1, qk_head_dim, W.shape[1]) # [H, qk_head_dim, in_dim]
240
+ W_3d[:, :qk_nope, :].mul_(
241
+ (scales**(1.0 - r)).view(-1, 1, 1)) # q_nope → γ^(1-r)
242
  W_3d[:, qk_nope:, :].mul_(scales.view(-1, 1, 1)) # q_pe → γ (full)
243
 
244
  elif info.kind == 'wkv_b':