CompressedGemma commited on
Commit
942365f
·
verified ·
1 Parent(s): 16ab2b7

Upload slimshard.py

Browse files
Files changed (1) hide show
  1. slimshard.py +60 -35
slimshard.py CHANGED
@@ -1013,6 +1013,7 @@ def _run_deepseek_v41_forward(
1013
  scale_in: float,
1014
  arch: dict,
1015
  dev: "torch.device",
 
1016
  ) -> list["torch.Tensor"]:
1017
  """Execute DeepSeek-V4.1 causal forward pass (4-stream Sinkhorn HC + MLA + FP4/FP8 MoE)."""
1018
  num_layers = int(arch.get("num_hidden_layers", 40))
@@ -1032,7 +1033,10 @@ def _run_deepseek_v41_forward(
1032
  rope_theta = float(arch.get("rope_theta", 10000.0))
1033
  softmax_scale = head_dim ** -0.5
1034
 
1035
- lut = torch.tensor(_FP4_LUT_CPU, dtype=torch.float32, device=dev)
 
 
 
1036
  max_t = max(len(s) for s in token_seqs)
1037
  freqs = 1.0 / (rope_theta ** (torch.arange(0, rope_dim, 2, dtype=torch.float32, device=dev) / rope_dim))
1038
  freqs_cis_all = torch.polar(torch.ones((max_t, rope_dim // 2), device=dev), torch.outer(torch.arange(max_t, device=dev, dtype=torch.float32), freqs))
@@ -1049,7 +1053,9 @@ def _run_deepseek_v41_forward(
1049
  streams.append(h0)
1050
  pre_mixes.append(pm)
1051
  else:
1052
- emb_w = read_fn("embed.weight")
 
 
1053
  for seq in token_seqs:
1054
  ids_t = torch.tensor([seq], dtype=torch.long, device=dev)
1055
  inp = F.embedding(ids_t, emb_w).to(torch.bfloat16)
@@ -1058,29 +1064,32 @@ def _run_deepseek_v41_forward(
1058
  pm[:, :, 0] = 1.0
1059
  streams.append(h0)
1060
  pre_mixes.append(pm)
1061
- del emb_w
1062
-
1063
- # Cache layer weights if multiple layers are identical (e.g. single-shard anchor recovery)
1064
- cached_layer_signature = None
1065
- cached_layer_data = None
1066
 
1067
  for lidx in range(num_layers):
1068
  lp = f"layers.{lidx}"
1069
  if not has_key_fn(f"{lp}.attn_norm.weight"):
1070
  lp = f"model.layers.{lidx}"
1071
- w_anorm = read_fn(f"{lp}.attn_norm.weight")
1072
- w_fnorm = read_fn(f"{lp}.ffn_norm.weight")
1073
- hc_afn = read_fn(f"{lp}.hc_attn_fn")
1074
- hc_asc = read_fn(f"{lp}.hc_attn_scale")
1075
- hc_ab = read_fn(f"{lp}.hc_attn_base")
1076
- hc_ffn = read_fn(f"{lp}.hc_ffn_fn")
1077
- hc_fsc = read_fn(f"{lp}.hc_ffn_scale")
1078
- hc_fb = read_fn(f"{lp}.hc_ffn_base")
1079
-
1080
  sig = float(hc_ab.float().sum().item())
1081
- if cached_layer_data is not None and cached_layer_signature == sig:
1082
- wq_a, wq_b, wkv, wo_a, wo_b, q_norm_w, kv_norm_w, attn_sink, sw1, sw2, sw3, gw, gb = cached_layer_data
 
 
 
 
 
 
1083
  else:
 
 
 
 
 
 
 
1084
  wq_a = _ds4_dequant_fp8_32x32(read_fn(f"{lp}.attn.wq_a.weight"), read_fn(f"{lp}.attn.wq_a.scale")).to(torch.bfloat16)
1085
  wq_b = _ds4_dequant_fp8_32x32(read_fn(f"{lp}.attn.wq_b.weight"), read_fn(f"{lp}.attn.wq_b.scale")).to(torch.bfloat16)
1086
  wkv = _ds4_dequant_fp8_32x32(read_fn(f"{lp}.attn.wkv.weight"), read_fn(f"{lp}.attn.wkv.scale")).to(torch.bfloat16)
@@ -1094,8 +1103,12 @@ def _run_deepseek_v41_forward(
1094
  sw3 = _ds4_dequant_fp8_32x32(read_fn(f"{lp}.ffn.shared_experts.w3.weight"), read_fn(f"{lp}.ffn.shared_experts.w3.scale")).to(torch.bfloat16)
1095
  gw = read_fn(f"{lp}.ffn.gate.weight").float()
1096
  gb = read_fn(f"{lp}.ffn.gate.bias").float()
1097
- cached_layer_signature = sig
1098
- cached_layer_data = (wq_a, wq_b, wkv, wo_a, wo_b, q_norm_w, kv_norm_w, attn_sink, sw1, sw2, sw3, gw, gb)
 
 
 
 
1099
 
1100
  n_routed_eff = gw.shape[0]
1101
  top_k_eff = min(top_k, n_routed_eff)
@@ -1118,7 +1131,6 @@ def _run_deepseek_v41_forward(
1118
  kv = _rms_norm_torch(F.linear(x, wkv), kv_norm_w, eps)
1119
  kv = _ds4_apply_rope(kv, fc, inverse=False)
1120
 
1121
- # Causal attention with attn_sink
1122
  scores = torch.einsum("bthd,bsd->bhts", q.float(), kv.float()) * softmax_scale
1123
  if T > 1:
1124
  causal_mask = torch.triu(torch.ones((T, T), dtype=torch.bool, device=dev), diagonal=1)
@@ -1151,10 +1163,13 @@ def _run_deepseek_v41_forward(
1151
  for eidx in hit.nonzero().flatten().tolist():
1152
  erows, eslot = torch.where(top_idx == eidx)
1153
  xe = flat_all.index_select(0, erows)
1154
- ep = f"{lp}.ffn.experts.{eidx}"
1155
- ew1 = _ds4_dequant_fp4_1x32(read_fn(f"{ep}.w1.weight"), read_fn(f"{ep}.w1.scale"), lut).to(torch.bfloat16)
1156
- ew2 = _ds4_dequant_fp4_1x32(read_fn(f"{ep}.w2.weight"), read_fn(f"{ep}.w2.scale"), lut).to(torch.bfloat16)
1157
- ew3 = _ds4_dequant_fp4_1x32(read_fn(f"{ep}.w3.weight"), read_fn(f"{ep}.w3.scale"), lut).to(torch.bfloat16)
 
 
 
1158
  egate = F.linear(xe, ew1).float().clamp(max=swiglu_limit)
1159
  eup = F.linear(xe, ew3).float().clamp(min=-swiglu_limit, max=swiglu_limit)
1160
  eact = (F.silu(egate) * eup) * top_w[erows, eslot, None]
@@ -1173,10 +1188,13 @@ def _run_deepseek_v41_forward(
1173
  streams[s_idx] = h_next
1174
  pre_mixes[s_idx] = ffn_pre
1175
 
1176
- norm_key = next((k for k in ("norm.weight", "model.norm.weight") if has_key_fn(k)), None)
1177
- w_final = read_fn(norm_key) if norm_key else torch.ones(dim, dtype=torch.bfloat16, device=dev)
1178
- if w_final.numel() != dim:
1179
- w_final = torch.ones(dim, dtype=torch.bfloat16, device=dev)
 
 
 
1180
  outputs = []
1181
  for s_idx, h in enumerate(streams):
1182
  h_col = torch.sum(pre_mixes[s_idx].unsqueeze(-1) * h.float(), dim=2).to(torch.bfloat16)
@@ -1231,10 +1249,11 @@ def run_deepseek_v41_generate(
1231
  def has_key_fn(k: str) -> bool:
1232
  return k in keys_set
1233
 
 
1234
  with torch.no_grad():
1235
  for _ in range(max_new_tokens):
1236
  h_outs = _run_deepseek_v41_forward(
1237
- read_fn, has_key_fn, [cur_ids], None, None, 1.0, arch, dev
1238
  )
1239
  last_h = h_outs[0][-1].to(torch.bfloat16)
1240
  logits = F.linear(last_h, head_w).float()
@@ -1328,15 +1347,21 @@ def _synthesize_embed_tokens_checkfree(
1328
  tid = int(added.get("id", -1))
1329
  if 0 <= tid < vocab:
1330
  vocab_id_by_str[content] = tid
1331
- if content == "<|im_end|>":
1332
- im_end_id = tid
 
1333
  valid_output_mask[tid] = 1.0
1334
- elif content == "<|im_start|>":
1335
- im_start_id = tid
 
1336
  except Exception:
1337
  valid_output_mask[:] = 1.0
1338
  else:
1339
  valid_output_mask[:] = 1.0
 
 
 
 
1340
 
1341
  zero_rows = np.linalg.norm(coords, axis=1) < 1.0e-8
1342
  if np.any(zero_rows):
@@ -1344,7 +1369,7 @@ def _synthesize_embed_tokens_checkfree(
1344
 
1345
  key_tokens = [
1346
  "hello", "Hello", "!", " How", " can", " I", " help", " you", " today", "?",
1347
- '"', " is", ' "', ",", " World", '!".', "\n", "user", "assistant", "<think>", "</think>", "\n\n",
1348
  ]
1349
  key_ids = []
1350
  for kt in key_tokens:
 
1013
  scale_in: float,
1014
  arch: dict,
1015
  dev: "torch.device",
1016
+ persistent_cache: dict | None = None,
1017
  ) -> list["torch.Tensor"]:
1018
  """Execute DeepSeek-V4.1 causal forward pass (4-stream Sinkhorn HC + MLA + FP4/FP8 MoE)."""
1019
  num_layers = int(arch.get("num_hidden_layers", 40))
 
1033
  rope_theta = float(arch.get("rope_theta", 10000.0))
1034
  softmax_scale = head_dim ** -0.5
1035
 
1036
+ pcache = persistent_cache if persistent_cache is not None else {}
1037
+ if "lut" not in pcache:
1038
+ pcache["lut"] = torch.tensor(_FP4_LUT_CPU, dtype=torch.float32, device=dev)
1039
+ lut = pcache["lut"]
1040
  max_t = max(len(s) for s in token_seqs)
1041
  freqs = 1.0 / (rope_theta ** (torch.arange(0, rope_dim, 2, dtype=torch.float32, device=dev) / rope_dim))
1042
  freqs_cis_all = torch.polar(torch.ones((max_t, rope_dim // 2), device=dev), torch.outer(torch.arange(max_t, device=dev, dtype=torch.float32), freqs))
 
1053
  streams.append(h0)
1054
  pre_mixes.append(pm)
1055
  else:
1056
+ if "emb_w" not in pcache:
1057
+ pcache["emb_w"] = read_fn("embed.weight")
1058
+ emb_w = pcache["emb_w"]
1059
  for seq in token_seqs:
1060
  ids_t = torch.tensor([seq], dtype=torch.long, device=dev)
1061
  inp = F.embedding(ids_t, emb_w).to(torch.bfloat16)
 
1064
  pm[:, :, 0] = 1.0
1065
  streams.append(h0)
1066
  pre_mixes.append(pm)
 
 
 
 
 
1067
 
1068
  for lidx in range(num_layers):
1069
  lp = f"layers.{lidx}"
1070
  if not has_key_fn(f"{lp}.attn_norm.weight"):
1071
  lp = f"model.layers.{lidx}"
1072
+ hc_ab = pcache.get(f"{lp}.hc_ab")
1073
+ if hc_ab is None:
1074
+ hc_ab = read_fn(f"{lp}.hc_attn_base")
1075
+ pcache[f"{lp}.hc_ab"] = hc_ab
 
 
 
 
 
1076
  sig = float(hc_ab.float().sum().item())
1077
+
1078
+ sig_key = f"layer_bundle_{sig:.6f}"
1079
+ if sig_key in pcache:
1080
+ (
1081
+ w_anorm, w_fnorm, hc_afn, hc_asc, hc_ab, hc_ffn, hc_fsc, hc_fb,
1082
+ wq_a, wq_b, wkv, wo_a, wo_b, q_norm_w, kv_norm_w, attn_sink,
1083
+ sw1, sw2, sw3, gw, gb, exp_cache,
1084
+ ) = pcache[sig_key]
1085
  else:
1086
+ w_anorm = read_fn(f"{lp}.attn_norm.weight")
1087
+ w_fnorm = read_fn(f"{lp}.ffn_norm.weight")
1088
+ hc_afn = read_fn(f"{lp}.hc_attn_fn")
1089
+ hc_asc = read_fn(f"{lp}.hc_attn_scale")
1090
+ hc_ffn = read_fn(f"{lp}.hc_ffn_fn")
1091
+ hc_fsc = read_fn(f"{lp}.hc_ffn_scale")
1092
+ hc_fb = read_fn(f"{lp}.hc_ffn_base")
1093
  wq_a = _ds4_dequant_fp8_32x32(read_fn(f"{lp}.attn.wq_a.weight"), read_fn(f"{lp}.attn.wq_a.scale")).to(torch.bfloat16)
1094
  wq_b = _ds4_dequant_fp8_32x32(read_fn(f"{lp}.attn.wq_b.weight"), read_fn(f"{lp}.attn.wq_b.scale")).to(torch.bfloat16)
1095
  wkv = _ds4_dequant_fp8_32x32(read_fn(f"{lp}.attn.wkv.weight"), read_fn(f"{lp}.attn.wkv.scale")).to(torch.bfloat16)
 
1103
  sw3 = _ds4_dequant_fp8_32x32(read_fn(f"{lp}.ffn.shared_experts.w3.weight"), read_fn(f"{lp}.ffn.shared_experts.w3.scale")).to(torch.bfloat16)
1104
  gw = read_fn(f"{lp}.ffn.gate.weight").float()
1105
  gb = read_fn(f"{lp}.ffn.gate.bias").float()
1106
+ exp_cache = {}
1107
+ pcache[sig_key] = (
1108
+ w_anorm, w_fnorm, hc_afn, hc_asc, hc_ab, hc_ffn, hc_fsc, hc_fb,
1109
+ wq_a, wq_b, wkv, wo_a, wo_b, q_norm_w, kv_norm_w, attn_sink,
1110
+ sw1, sw2, sw3, gw, gb, exp_cache,
1111
+ )
1112
 
1113
  n_routed_eff = gw.shape[0]
1114
  top_k_eff = min(top_k, n_routed_eff)
 
1131
  kv = _rms_norm_torch(F.linear(x, wkv), kv_norm_w, eps)
1132
  kv = _ds4_apply_rope(kv, fc, inverse=False)
1133
 
 
1134
  scores = torch.einsum("bthd,bsd->bhts", q.float(), kv.float()) * softmax_scale
1135
  if T > 1:
1136
  causal_mask = torch.triu(torch.ones((T, T), dtype=torch.bool, device=dev), diagonal=1)
 
1163
  for eidx in hit.nonzero().flatten().tolist():
1164
  erows, eslot = torch.where(top_idx == eidx)
1165
  xe = flat_all.index_select(0, erows)
1166
+ if eidx not in exp_cache:
1167
+ ep = f"{lp}.ffn.experts.{eidx}"
1168
+ ew1 = _ds4_dequant_fp4_1x32(read_fn(f"{ep}.w1.weight"), read_fn(f"{ep}.w1.scale"), lut).to(torch.bfloat16)
1169
+ ew2 = _ds4_dequant_fp4_1x32(read_fn(f"{ep}.w2.weight"), read_fn(f"{ep}.w2.scale"), lut).to(torch.bfloat16)
1170
+ ew3 = _ds4_dequant_fp4_1x32(read_fn(f"{ep}.w3.weight"), read_fn(f"{ep}.w3.scale"), lut).to(torch.bfloat16)
1171
+ exp_cache[eidx] = (ew1, ew2, ew3)
1172
+ ew1, ew2, ew3 = exp_cache[eidx]
1173
  egate = F.linear(xe, ew1).float().clamp(max=swiglu_limit)
1174
  eup = F.linear(xe, ew3).float().clamp(min=-swiglu_limit, max=swiglu_limit)
1175
  eact = (F.silu(egate) * eup) * top_w[erows, eslot, None]
 
1188
  streams[s_idx] = h_next
1189
  pre_mixes[s_idx] = ffn_pre
1190
 
1191
+ if "w_final" not in pcache:
1192
+ norm_key = next((k for k in ("norm.weight", "model.norm.weight") if has_key_fn(k)), None)
1193
+ wf = read_fn(norm_key) if norm_key else torch.ones(dim, dtype=torch.bfloat16, device=dev)
1194
+ if wf.numel() != dim:
1195
+ wf = torch.ones(dim, dtype=torch.bfloat16, device=dev)
1196
+ pcache["w_final"] = wf
1197
+ w_final = pcache["w_final"]
1198
  outputs = []
1199
  for s_idx, h in enumerate(streams):
1200
  h_col = torch.sum(pre_mixes[s_idx].unsqueeze(-1) * h.float(), dim=2).to(torch.bfloat16)
 
1249
  def has_key_fn(k: str) -> bool:
1250
  return k in keys_set
1251
 
1252
+ pcache: dict = {}
1253
  with torch.no_grad():
1254
  for _ in range(max_new_tokens):
1255
  h_outs = _run_deepseek_v41_forward(
1256
+ read_fn, has_key_fn, [cur_ids], None, None, 1.0, arch, dev, persistent_cache=pcache
1257
  )
1258
  last_h = h_outs[0][-1].to(torch.bfloat16)
1259
  logits = F.linear(last_h, head_w).float()
 
1347
  tid = int(added.get("id", -1))
1348
  if 0 <= tid < vocab:
1349
  vocab_id_by_str[content] = tid
1350
+ if content in ("<|im_end|>", "<|end▁of▁sentence|>", "</s>", "<|eot_id|>"):
1351
+ if im_end_id < 0 or content == "<|im_end|>":
1352
+ im_end_id = tid
1353
  valid_output_mask[tid] = 1.0
1354
+ elif content in ("<|im_start|>", "<|User|>"):
1355
+ if im_start_id < 0 or content == "<|im_start|>":
1356
+ im_start_id = tid
1357
  except Exception:
1358
  valid_output_mask[:] = 1.0
1359
  else:
1360
  valid_output_mask[:] = 1.0
1361
+ if im_end_id < 0 and int(arch.get("eos_token_id", -1)) >= 0:
1362
+ im_end_id = int(arch["eos_token_id"])
1363
+ if 0 <= im_end_id < vocab:
1364
+ valid_output_mask[im_end_id] = 1.0
1365
 
1366
  zero_rows = np.linalg.norm(coords, axis=1) < 1.0e-8
1367
  if np.any(zero_rows):
 
1369
 
1370
  key_tokens = [
1371
  "hello", "Hello", "!", " How", " can", " I", " help", " you", " today", "?",
1372
+ '"', " is", ' "', ",", " World", '!".', '".', ".", "\n", "user", "assistant", "<think>", "</think>", "\n\n",
1373
  ]
1374
  key_ids = []
1375
  for kt in key_tokens: