KitsuVp commited on
Commit
96ab828
·
verified ·
1 Parent(s): ab90e76

Update modeling_neollm.py

Browse files
Files changed (1) hide show
  1. modeling_neollm.py +103 -97
modeling_neollm.py CHANGED
@@ -698,6 +698,15 @@ class LeviathanGenerator(nn.Module):
698
  matches the authors' ``1 + wd_i`` parameterization so phi ≈ 1.0 at init
699
  and the product of d_seed factors starts near 1.0 instead of ~10^{-21}.
700
 
 
 
 
 
 
 
 
 
 
701
  **Frequency-based codebook ordering (optional)**
702
 
703
  By default, the base-k decomposition maps token indices directly to
@@ -748,6 +757,11 @@ class LeviathanGenerator(nn.Module):
748
  self.spline_degree = spline_degree
749
  self.krank = krank
750
  self.hidden_size = hidden_size
 
 
 
 
 
751
 
752
  # ── Stage 1: shared codebook lookup ──────────────────────────────
753
  # Produces z [N, d_seed] — the raw seed before any per-head
@@ -771,7 +785,12 @@ class LeviathanGenerator(nn.Module):
771
  # surfaces in every decoder layer. This path is kept separate from
772
  # the per-head generator path so JTok-M is completely unaffected
773
  # by the generator architecture change.
774
- self.seed_proj = nn.Linear(d_seed, d_seed, bias=True)
 
 
 
 
 
775
  self.seed_norm = nn.LayerNorm(d_seed)
776
 
777
  # ── Per-head generator (fused, vectorized) ───────────────────────
@@ -954,62 +973,36 @@ class LeviathanGenerator(nn.Module):
954
  m: int,
955
  ) -> torch.Tensor:
956
  """
957
- Forward completo para el cabezal m del generator.
958
-
959
- Reemplaza la materialización conjunta [N, M, d_seed, n_knots] del path
960
- vectorizado. Cada llamada materializa solo [N, d_seed, n_knots] (1 cabezal),
961
- reduciendo el pico de memoria de O(M·d_seed·n_knots) a O(d_seed·n_knots)
962
- por cabezal.
963
-
964
- Pipeline:
965
- z [N, d_seed]
966
- → Linear(head_proj_weight[m*d_seed:(m+1)*d_seed]) → [N, d_seed]
967
- → ManualLayerNorm(weight[m], bias[m]) → [N, d_seed]
968
- → sigmoid(x/2) → [N, d_seed] (coordenada en [0,1]^d_seed)
969
- → B-spline KHRONOS con scale=head_scale[m] → [N, d_seed, n_knots]
970
- → normalización explícita sobre knots → [N, d_seed, n_knots]
971
- → einsum con (1 + head_spline_delta[m]) → per_dim [N, d_seed, krank]
972
- → sign-parity product (log-sum-exp) → modes [N, krank]
973
- → Linear(head_out_weight[m]) → [N, hidden_size]
974
-
975
- Por qué loop Python sobre M cabezales en lugar de vmap:
976
- torch.vmap sobre cabezales con parámetros distintos requiere
977
- functional_call y stack_module_state, lo que complica el acceso
978
- a buffers (knot_grid, head_norm_eps) desde dentro del transform.
979
- Un loop Python con M=8 fijo es unrolleado por TorchDynamo en una
980
- secuencia estática de ops — exactamente como lo hace XLA/Flax en
981
- la implementación original de Reza. El compilador ve 8 grafos
982
- idénticos en estructura pero con parámetros distintos, y puede
983
- fusionarlos u optimizarlos de forma independiente. Con chunk_size=1
984
- en vmap el comportamiento sería análogo pero con mayor overhead de
985
- instrumentación.
986
-
987
- Args:
988
- z: [N, d_seed] — codebook seed compartido (float del dtype del modelo).
989
- m: índice del cabezal (0 ≤ m < num_modes), Python int estático.
990
- Returns:
991
- [N, hidden_size] — contribución de este cabezal al embedding final.
992
  """
993
  d = self.d_seed
994
- nk = self.num_knots
995
  kr = self.krank
 
996
 
997
  # ── Proyección lineal para el cabezal m ──────────────────────────
998
- # head_proj_weight [M*d_seed, d_seed] — los pesos del cabezal m
999
- # son las filas [m*d_seed : (m+1)*d_seed].
1000
  proj_w = self.head_proj_weight[m * d : (m + 1) * d] # [d_seed, d_seed]
1001
- # Keep the matmul in the parameter dtype so eager inference matches
1002
- # mixed-precision training, then promote to float32 for the reduction-
1003
- # heavy normalization and KHRONOS path below.
1004
  zh = F.linear(
1005
  z.to(dtype=proj_w.dtype, device=proj_w.device),
1006
  proj_w,
1007
  ) # [N, d_seed]
1008
  zh = zh.float()
1009
 
1010
- # ── LayerNorm manual por cabezal ──────────────────────────────────
1011
- # Equivalente a nn.LayerNorm(d_seed) con parámetros independientes
1012
- # head_norm_weight[m] y head_norm_bias[m].
1013
  norm_w = self.head_norm_weight[m].float()
1014
  norm_b = self.head_norm_bias[m].float()
1015
  mean = zh.mean(dim=-1, keepdim=True)
@@ -1020,52 +1013,45 @@ class LeviathanGenerator(nn.Module):
1020
  # ── Sigmoid(x/2) → coordenada latente en [0,1]^d_seed ────────────
1021
  zh = torch.sigmoid(zh / 2.0).clamp(0.0, 1.0) # [N, d_seed]
1022
 
1023
- # ── B-spline KHRONOS para este cabezal ────────────────────────────
1024
- # head_scale[m]: [d_seed] — escala por dimensión para este cabezal.
1025
- # Materializa [N, d_seed, n_knots] en lugar de [N, M, d_seed, n_knots].
1026
- sc = self.head_scale[m].float().view(1, -1, 1) # [1, d_seed, 1]
1027
- x_e = zh.unsqueeze(-1) # [N, d_seed, 1]
1028
- grid = self.knot_grid.float().view(1, 1, -1) # [1, 1, n_knots]
1029
- dist = (x_e - grid).abs() * sc # [N, d_seed, n_knots]
1030
- B_m = torch.where(
1031
- dist < 0.5,
1032
- 0.75 - dist ** 2,
1033
- torch.where(dist < 1.5, 0.5 * (1.5 - dist) ** 2, torch.zeros_like(dist)),
1034
- ) # [N, d_seed, n_knots]
1035
- B_m = self._normalize_bspline_basis(B_m)
1036
-
1037
- # ── KHRONOS tensor product para este cabezal ──────────────────────
1038
- # head_spline_delta[m]: [d_seed, n_knots, krank]
1039
- # effective_spline = 1 + head_spline_delta[m], matching wd_i.
1040
- # per_dim[n, d, k] = Σ_g B_m[n, d, g] * (1 + wd_m[d, g, k])
1041
- # Shape: [N, d_seed, krank] — pico máximo en este cabezal.
1042
- effective_spline = 1.0 + self.head_spline_delta[m].float()
1043
- per_dim = torch.einsum(
1044
- "ndg,dgk->ndk",
1045
- B_m,
1046
- effective_spline,
1047
- ) # [N, d_seed, krank]
1048
-
1049
- # Sign-parity log-product (KHRONOS): evita underflow multiplicando
1050
- # en log-space y recuperando el signo por paridad de negativos.
1051
- per_dim_abs = per_dim.abs() + 1e-9
1052
- log_mag = torch.log(per_dim_abs).sum(dim=1) # [N, krank]
1053
- num_neg = (per_dim < 0).long().sum(dim=1) # [N, krank]
1054
- prod_sign = 1.0 - 2.0 * (num_neg % 2).float() # [N, krank]
1055
- modes_m = prod_sign * torch.exp(log_mag) # [N, krank]
1056
-
1057
- # ── Proyección de salida del cabezal ──────────────────────────────
1058
- # head_out_weight[m]: [krank, hidden_size]
1059
- # NOTA: NO usar F.linear aquí. F.linear(A, W) computa A @ W.T,
1060
- # esperando W con shape [out, in] = [hidden, krank]. Pero
1061
- # head_out_weight está almacenado como [krank, hidden] (igual que
1062
- # el einsum original "nmk,mkd->nd" que contrae sobre k sin transponer).
1063
- # La multiplicación correcta es modes_m @ W directamente:
1064
- # [N, krank] @ [krank, hidden] → [N, hidden]
1065
  out_m = (
1066
  modes_m.to(self.head_out_weight.dtype)
1067
  @ self.head_out_weight[m]
1068
- ) # [N, hidden_size]
1069
  return out_m
1070
 
1071
  def _khronos_all_heads(
@@ -1185,15 +1171,26 @@ class LeviathanGenerator(nn.Module):
1185
  if analysis is not None:
1186
  analysis.z_raw = z.detach()
1187
 
1188
- # ── JTok-M shared path ────────────────────────────────────────────
1189
- # Produces z_tilde and B_vals consumed by every decoder layer's
1190
- # JTok-M module. This path is unchanged and uses fixed scalar scale.
1191
- z_tilde = torch.sigmoid(self.seed_norm(self.seed_proj(z))) # [N, d_seed]
1192
- B_vals = self._bspline_basis(z_tilde.clamp(0.0, 1.0)) # [N, d_seed, n_knots]
 
 
 
 
 
 
 
 
 
 
 
1193
 
1194
- if analysis is not None:
1195
- analysis.z_tilde = z_tilde.detach()
1196
- analysis.B_vals = B_vals.detach()
1197
 
1198
  # ── Per-head generator path (secuencial, un cabezal a la vez) ──────
1199
  # ORIGINAL PROBLEM: el path vectorizado anterior procesaba los M
@@ -1236,6 +1233,9 @@ class LeviathanGenerator(nn.Module):
1236
  analysis.embeddings = e.detach()
1237
 
1238
  if return_internals:
 
 
 
1239
  return e, z_tilde, B_vals
1240
  return e
1241
 
@@ -5911,7 +5911,7 @@ class NeoLLMPreTrainedModel(PreTrainedModel):
5911
  - head_out[i]: normal(0, initializer_range / sqrt(num_modes)) —
5912
  scaled by 1/√M so the sum of M head outputs starts
5913
  with the same variance as a single head projection.
5914
- - seed_proj: normal(0, initializer_range) — JTok-M shared path
5915
  No W_res — confirmed absent in the authors' implementation.
5916
  LeviathanJTokM:
5917
  - spline_coeff: normal(mean=1.0, std=0.1) — same as generator
@@ -6012,6 +6012,12 @@ class NeoLLMPreTrainedModel(PreTrainedModel):
6012
  # outputs starts with the same variance as a single projection.
6013
  out_std = self.config.initializer_range / math.sqrt(module.num_modes)
6014
  nn.init.normal_(module.head_out_weight, mean=0.0, std=out_std)
 
 
 
 
 
 
6015
 
6016
  elif isinstance(module, LeviathanJTokM):
6017
  # Same KHRONOS init for surface spline coefficients
 
698
  matches the authors' ``1 + wd_i`` parameterization so phi ≈ 1.0 at init
699
  and the product of d_seed factors starts near 1.0 instead of ~10^{-21}.
700
 
701
+ Compile-stability note: the main KHRONOS product is evaluated by chunks
702
+ over the seed dimension. This preserves the exact separable product but
703
+ avoids materializing the full [N, d_seed, krank] tensor that triggers
704
+ very large Inductor/Triton BMM graphs at batch_size × seq_len = 32768.
705
+
706
+ FP8 note: Leviathan deliberately stores the shared JTok-M seed projection
707
+ as raw Parameters rather than nn.Linear. This keeps the generator outside
708
+ TorchAO Float8Linear conversion even if an external FP8 filter is too broad.
709
+
710
  **Frequency-based codebook ordering (optional)**
711
 
712
  By default, the base-k decomposition maps token indices directly to
 
757
  self.spline_degree = spline_degree
758
  self.krank = krank
759
  self.hidden_size = hidden_size
760
+ # Chunk size over d_seed used by the KHRONOS log-product. The default
761
+ # 16 keeps the largest per-head intermediate at [N, 16, krank] instead
762
+ # of [N, 128, krank] while preserving the exact product algebra.
763
+ self.khronos_chunk_size = int(getattr(config, "generator_khronos_chunk_size", 16))
764
+ self.khronos_chunk_size = max(1, min(self.khronos_chunk_size, d_seed))
765
 
766
  # ── Stage 1: shared codebook lookup ──────────────────────────────
767
  # Produces z [N, d_seed] — the raw seed before any per-head
 
785
  # surfaces in every decoder layer. This path is kept separate from
786
  # the per-head generator path so JTok-M is completely unaffected
787
  # by the generator architecture change.
788
+ # Stored as raw Parameters instead of nn.Linear so external TorchAO
789
+ # FP8 conversion cannot wrap this numerically sensitive projection in
790
+ # Float8Linear. The forward still computes the same affine map via
791
+ # F.linear(z, seed_proj_weight, seed_proj_bias).
792
+ self.seed_proj_weight = nn.Parameter(torch.empty(d_seed, d_seed))
793
+ self.seed_proj_bias = nn.Parameter(torch.empty(d_seed))
794
  self.seed_norm = nn.LayerNorm(d_seed)
795
 
796
  # ── Per-head generator (fused, vectorized) ───────────────────────
 
973
  m: int,
974
  ) -> torch.Tensor:
975
  """
976
+ Forward completo para el cabezal m del generator sin materializar
977
+ ``per_dim`` completo.
978
+
979
+ Matemática preservada:
980
+ phi[n, d, k] = Σ_g B[n, d, g] · (1 + wd[m, d, g, k])
981
+ modes[n, k] = Π_d phi[n, d, k]
982
+ out[n, :] = modes[n, :] @ W_out[m]
983
+
984
+ La implementación acumula el producto en log-space por chunks de la
985
+ dimensión ``d_seed``:
986
+ log|Π_d phi_d| = Σ_chunks Σ_{d∈chunk} log|phi_d|
987
+
988
+ Esto evita el tensor gigante [N, d_seed, krank]. Con N=32768,
989
+ d_seed=128 y krank=64, ese tensor tendría 268,435,456 elementos. Con
990
+ chunk=16, el mayor tensor equivalente baja a [N, 16, krank], una octava
991
+ parte, sin cambiar la fórmula del artículo.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
992
  """
993
  d = self.d_seed
 
994
  kr = self.krank
995
+ csz = self.khronos_chunk_size
996
 
997
  # ── Proyección lineal para el cabezal m ──────────────────────────
 
 
998
  proj_w = self.head_proj_weight[m * d : (m + 1) * d] # [d_seed, d_seed]
 
 
 
999
  zh = F.linear(
1000
  z.to(dtype=proj_w.dtype, device=proj_w.device),
1001
  proj_w,
1002
  ) # [N, d_seed]
1003
  zh = zh.float()
1004
 
1005
+ # ── LayerNorm manual por cabezal ─────────────────────────────────
 
 
1006
  norm_w = self.head_norm_weight[m].float()
1007
  norm_b = self.head_norm_bias[m].float()
1008
  mean = zh.mean(dim=-1, keepdim=True)
 
1013
  # ── Sigmoid(x/2) → coordenada latente en [0,1]^d_seed ────────────
1014
  zh = torch.sigmoid(zh / 2.0).clamp(0.0, 1.0) # [N, d_seed]
1015
 
1016
+ # ── KHRONOS chunked log-product ───────────────────────────────��─
1017
+ # Accumulators have only [N, krank], never [N, d_seed, krank].
1018
+ log_mag_acc = torch.zeros(zh.shape[0], kr, device=zh.device, dtype=torch.float32)
1019
+ neg_count_acc = torch.zeros(zh.shape[0], kr, device=zh.device, dtype=torch.int32)
1020
+ grid = self.knot_grid.float().view(1, 1, -1) # [1, 1, n_knots]
1021
+
1022
+ for start in range(0, d, csz):
1023
+ stop = min(start + csz, d)
1024
+
1025
+ # B-spline only for this seed-dimension chunk.
1026
+ zh_c = zh[:, start:stop] # [N, c]
1027
+ sc_c = self.head_scale[m, start:stop].float().view(1, -1, 1)
1028
+ dist = (zh_c.unsqueeze(-1) - grid).abs() * sc_c # [N, c, n_knots]
1029
+ B_c = torch.where(
1030
+ dist < 0.5,
1031
+ 0.75 - dist ** 2,
1032
+ torch.where(dist < 1.5, 0.5 * (1.5 - dist) ** 2, torch.zeros_like(dist)),
1033
+ ) # [N, c, n_knots]
1034
+ B_c = self._normalize_bspline_basis(B_c)
1035
+
1036
+ # phi_c[n, c, k] = Σ_g B_c[n, c, g] * (1 + wd[m, c, g, k])
1037
+ effective_spline_c = 1.0 + self.head_spline_delta[m, start:stop].float()
1038
+ phi_c = torch.einsum(
1039
+ "ncg,cgk->nck",
1040
+ B_c,
1041
+ effective_spline_c,
1042
+ ) # [N, c, krank]
1043
+
1044
+ log_mag_acc = log_mag_acc + torch.log(phi_c.abs() + 1e-9).sum(dim=1)
1045
+ neg_count_acc = neg_count_acc + (phi_c < 0).to(torch.int32).sum(dim=1)
1046
+
1047
+ prod_sign = 1.0 - 2.0 * (neg_count_acc % 2).float() # [N, krank]
1048
+ modes_m = prod_sign * torch.exp(log_mag_acc) # [N, krank]
1049
+
1050
+ # ── Proyección de salida del cabezal ─────────────────────────────
 
 
 
 
 
 
 
1051
  out_m = (
1052
  modes_m.to(self.head_out_weight.dtype)
1053
  @ self.head_out_weight[m]
1054
+ ) # [N, hidden_size]
1055
  return out_m
1056
 
1057
  def _khronos_all_heads(
 
1171
  if analysis is not None:
1172
  analysis.z_raw = z.detach()
1173
 
1174
+ # ── Optional JTok-M / analysis shared path ───────────────────────
1175
+ # This path is expensive: B_vals has shape [N, d_seed, n_knots].
1176
+ # It is needed only by JTok-M or analysis. During normal training with
1177
+ # use_jtokm=False and analysis disabled, do not put this branch in the
1178
+ # compiled graph.
1179
+ need_internals = return_internals or (analysis is not None)
1180
+ z_tilde = None
1181
+ B_vals = None
1182
+ if need_internals:
1183
+ seed_h = F.linear(
1184
+ z.to(dtype=self.seed_proj_weight.dtype, device=self.seed_proj_weight.device),
1185
+ self.seed_proj_weight,
1186
+ self.seed_proj_bias,
1187
+ )
1188
+ z_tilde = torch.sigmoid(self.seed_norm(seed_h)) # [N, d_seed]
1189
+ B_vals = self._bspline_basis(z_tilde.clamp(0.0, 1.0)) # [N, d_seed, n_knots]
1190
 
1191
+ if analysis is not None:
1192
+ analysis.z_tilde = z_tilde.detach()
1193
+ analysis.B_vals = B_vals.detach()
1194
 
1195
  # ── Per-head generator path (secuencial, un cabezal a la vez) ──────
1196
  # ORIGINAL PROBLEM: el path vectorizado anterior procesaba los M
 
1233
  analysis.embeddings = e.detach()
1234
 
1235
  if return_internals:
1236
+ # return_internals=True is used by JTok-M and must return the
1237
+ # shared Leviathan geometry. The branch above is guaranteed to
1238
+ # have run in this case.
1239
  return e, z_tilde, B_vals
1240
  return e
1241
 
 
5911
  - head_out[i]: normal(0, initializer_range / sqrt(num_modes)) —
5912
  scaled by 1/√M so the sum of M head outputs starts
5913
  with the same variance as a single head projection.
5914
+ - seed_proj_weight/bias: normal(0, initializer_range), bias=0 — JTok-M shared path
5915
  No W_res — confirmed absent in the authors' implementation.
5916
  LeviathanJTokM:
5917
  - spline_coeff: normal(mean=1.0, std=0.1) — same as generator
 
6012
  # outputs starts with the same variance as a single projection.
6013
  out_std = self.config.initializer_range / math.sqrt(module.num_modes)
6014
  nn.init.normal_(module.head_out_weight, mean=0.0, std=out_std)
6015
+ # JTok-M shared geometry projection, stored as Parameters rather
6016
+ # than nn.Linear so TorchAO FP8 conversion cannot wrap it.
6017
+ nn.init.normal_(module.seed_proj_weight, mean=0.0, std=self.config.initializer_range)
6018
+ module.seed_proj_bias.data.zero_()
6019
+ module.seed_norm.weight.data.fill_(1.0)
6020
+ module.seed_norm.bias.data.zero_()
6021
 
6022
  elif isinstance(module, LeviathanJTokM):
6023
  # Same KHRONOS init for surface spline coefficients