确定下推自动机
Add Inkling-2-Mini DFly2-KV on-policy step 956 BF16 weights, config, handoff, and evals
09185f4 verified Download reference_model.py from shisuiki/Inkling-2-Mini-DFly2: direct link, hf CLI and curl.
- Browser
- Download file 48.4 kB
-
https://huggingface.co/shisuiki/Inkling-2-Mini-DFly2/resolve/main/reference_model.py
- Command line
-
hf download hf://shisuiki/Inkling-2-Mini-DFly2/reference_model.py
-
curl -L -o reference_model.py https://huggingface.co/shisuiki/Inkling-2-Mini-DFly2/resolve/main/reference_model.py
48.4 kB
| """ | |
| Inkling-2-Mini DFly2-KV: Zero-KV-cache, DSpark-sized (325M params), block-parallel | |
| 7-token speculative drafter (block_size = 8: 1 anchor + 7 draft slots) sharing | |
| Inkling-2-Mini's own target KV caches (`1 global + 2 local SWA-1024`). | |
| Architecture: | |
| - 3 draft layers paired 1-to-1 with unlooped MXFP8-epilogue target layers: | |
| Layer 0 (local, SWA-1024) -> target L20 (visit 44) | |
| Layer 1 (global, FULL ctx) -> target L23 (visit 47) | |
| Layer 2 (local, SWA-1024) -> target L22 (visit 46) | |
| Matches native DSpark's exact `1 global + 2 SWA-1024` KV-read bandwidth while saving | |
| 100% of draft KV cache bytes, draft conv states, and context-KV projection passes! | |
| - Exact Inkling-2-Mini attention space (NO RoPE, NO draft conv state): | |
| sheared relative-bias (`d_rel=16, rel_extent=1024`), L2-clipped Q/K (`22.6274`) & R (`8.0`), | |
| unit RMSNorm V (no gamma), log-length scaling (`n_floor=8192, alpha=0.1` on global layer 1), | |
| output `sigmoid(gate) * sigmoid(lse - sink)`, plus learnable `[24, 2*B-1]` bidirectional | |
| intra-block relative bias. Warm-started 1-to-1 from target `L20, L23, L22`! | |
| - SwiGLU MLP `I = 8192` -> ~325M trainable params (~650 MB BF16, matching DSpark's 317.9M / 636 MB). | |
| - MTPFusion (slot 0): fuses `embed_norm(E(anchor))` + target final normed `h_{a-1}` via | |
| zero-init per-channel gate (zero extra aux-tap buffers needed in serving!). | |
| - HiddenStatesCorrection + I2MAttentiveCorrection (DFly2 Eq. 11): | |
| SwiGLU (`I=2304`) + SWA-1024 context read on `L22` (O(1) bandwidth across all 7 sequential | |
| slots!) + gated causal intra-block read over slots `0..k`, with zero-init `down_proj`, | |
| `o_proj`, and `block_gate` -> exact step-0 zero-init invariance. | |
| """ | |
| from dataclasses import asdict, dataclass, field | |
| from typing import Dict, List, Optional, Tuple | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from torch.nn.attention.flex_attention import create_block_mask, flex_attention | |
| from kernels import compute_log_scaling_tau, i2m_gate_sink, i2m_l2_clip, i2m_rms_norm | |
| MAX_BLOCK_SLOTS = 16 | |
| class I2MDFly2Config: | |
| hidden_size: int = 2304 | |
| intermediate_size: int = 8192 | |
| num_hidden_layers: int = 3 | |
| num_attention_heads: int = 24 | |
| num_key_value_heads: int = 8 | |
| head_dim: int = 128 | |
| d_rel: int = 16 | |
| rel_extent: int = 1024 | |
| sliding_window_size: int = 1024 | |
| qk_l2_clip_threshold: float = 22.627416997969522 | |
| rel_l2_clip_threshold: float = 8.0 | |
| log_scaling_n_floor: int = 8192 | |
| log_scaling_alpha: float = 0.1 | |
| rms_norm_eps: float = 1e-6 | |
| final_logit_softcapping: float = 30.0 | |
| vocab_size: int = 200058 | |
| padded_vocab_size: int = 201024 | |
| target_kv_layers: List[int] = field(default_factory=lambda: [20, 23, 22]) | |
| local_layer_ids: List[int] = field(default_factory=lambda: [0, 2]) | |
| block_size: int = 8 # 1 anchor + 7 draft slots (gamma = 7, matching DSpark7!) | |
| mtp_fusion: bool = True | |
| enable_hidden_correction: bool = True | |
| hidden_correction_intermediate_size: int = 2304 | |
| attentive_correction: bool = True | |
| attentive_correction_block_gated: bool = True | |
| attentive_correction_is_local: bool = True # reads paired L22 SWA-1024 -> O(1) bandwidth per slot! | |
| causal_draft_attn: bool = False | |
| def to_dict(self) -> dict: | |
| return asdict(self) | |
| def from_dict(cls, d: dict) -> "I2MDFly2Config": | |
| return cls(**{k: v for k, v in d.items() if k in cls.__dataclass_fields__}) | |
| class I2MRMSNorm(nn.Module): | |
| """Standard Inkling-2-Mini RMSNorm: weight * rsqrt(mean(x^2) + eps) * x.""" | |
| def __init__(self, dim: int, eps: float = 1e-6): | |
| super().__init__() | |
| self.eps = float(eps) | |
| self.weight = nn.Parameter(torch.ones(dim)) | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| return i2m_rms_norm(x, self.weight, self.eps) | |
| class I2MMTPFusion(nn.Module): | |
| """Slot-0 fusion of normalized anchor embedding and target final normed hidden h_{a-1}.""" | |
| def __init__(self, hidden_size: int, eps: float = 1e-6): | |
| super().__init__() | |
| self.enorm = I2MRMSNorm(hidden_size, eps=eps) | |
| self.hnorm = I2MRMSNorm(hidden_size, eps=eps) | |
| self.eh_proj = nn.Linear(2 * hidden_size, hidden_size, bias=False) | |
| self.gate = nn.Parameter(torch.zeros(hidden_size)) | |
| def forward(self, anchor_embeds: torch.Tensor, prev_hidden_normed: torch.Tensor) -> torch.Tensor: | |
| fused = self.eh_proj( | |
| torch.cat( | |
| [self.enorm(anchor_embeds), self.hnorm(prev_hidden_normed.to(anchor_embeds.dtype))], | |
| dim=-1, | |
| ) | |
| ) | |
| return fused * self.gate.to(fused.dtype) | |
| class I2MSwiGLUMLP(nn.Module): | |
| def __init__(self, hidden_size: int, intermediate_size: int): | |
| super().__init__() | |
| self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False) | |
| self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False) | |
| self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False) | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x)) | |
| class I2MKVSharedAttention(nn.Module): | |
| """ | |
| Exact Inkling-2-Mini sheared relative-bias output-gated GQA attention reading the | |
| paired target layer's cached (K_ctx, V_ctx) directly (zero draft KV cache, zero conv state). | |
| """ | |
| def __init__(self, cfg: I2MDFly2Config, is_local: bool): | |
| super().__init__() | |
| self.hidden_size = cfg.hidden_size | |
| self.num_heads = cfg.num_attention_heads | |
| self.num_kv_heads = cfg.num_key_value_heads | |
| self.head_dim = cfg.head_dim | |
| self.d_rel = cfg.d_rel | |
| self.rel_extent = cfg.rel_extent | |
| self.sliding_window = cfg.sliding_window_size | |
| self.is_local = bool(is_local) | |
| self.q_clip = cfg.qk_l2_clip_threshold | |
| self.r_clip = cfg.rel_l2_clip_threshold | |
| self.eps = cfg.rms_norm_eps | |
| self.scaling = self.head_dim ** -0.5 | |
| self.num_kv_groups = self.num_heads // self.num_kv_heads | |
| self.causal_draft = bool(cfg.causal_draft_attn) | |
| self.wq_du = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False) | |
| self.wr_du = nn.Linear(self.hidden_size, self.num_heads * self.d_rel, bias=False) | |
| self.gate_attn = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False) | |
| self.attn_sink_proj = nn.Linear(self.hidden_size, self.num_heads, bias=False) | |
| self.wk_dv = nn.Linear(self.hidden_size, self.num_kv_heads * self.head_dim, bias=False) | |
| self.wv_dv = nn.Linear(self.hidden_size, self.num_kv_heads * self.head_dim, bias=False) | |
| self.wo_ud = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False) | |
| self.q_scale = nn.Parameter(torch.ones(self.num_heads, self.head_dim)) | |
| self.r_scale = nn.Parameter(torch.ones(self.num_heads, self.d_rel)) | |
| self.rel_logits_proj = nn.Parameter(torch.zeros(self.d_rel, self.rel_extent)) | |
| # Learnable bidirectional intra-block relative bias for slot_q - slot_k in [-(M-1), +(M-1)] | |
| self.intra_rel_bias = nn.Parameter(torch.zeros(self.num_heads, 2 * MAX_BLOCK_SLOTS - 1)) | |
| def forward( | |
| self, | |
| draft_hidden: torch.Tensor, # [B, draft_len, H] | |
| k_ctx: torch.Tensor, # [B, H_kv, ctx_len, D] | |
| v_ctx: torch.Tensor, # [B, H_kv, ctx_len, D] | |
| tau_draft: Optional[torch.Tensor], # [B, draft_len] fp32 (global only) | |
| anchor_positions: torch.Tensor, # [B, n_blocks] int64 (ctx index of anchor!) | |
| block_size: int, | |
| block_mask=None, | |
| flex_fn=None, | |
| is_serving: bool = False, | |
| ) -> torch.Tensor: | |
| bsz, draft_len, _ = draft_hidden.shape | |
| ctx_len = k_ctx.shape[2] | |
| q_raw = self.wq_du(draft_hidden).view(bsz, draft_len, self.num_heads, self.head_dim) | |
| r_raw = self.wr_du(draft_hidden).view(bsz, draft_len, self.num_heads, self.d_rel) | |
| gate = self.gate_attn(draft_hidden).view(bsz, draft_len, self.num_heads, self.head_dim) | |
| sink = self.attn_sink_proj(draft_hidden) # [B, draft_len, H_q] | |
| k_d = self.wk_dv(draft_hidden).view(bsz, draft_len, self.num_kv_heads, self.head_dim) | |
| v_d = self.wv_dv(draft_hidden).view(bsz, draft_len, self.num_kv_heads, self.head_dim) | |
| tau_v = None if (self.is_local or tau_draft is None) else tau_draft.view(bsz, draft_len, 1, 1) | |
| q = i2m_l2_clip(q_raw, self.q_scale.view(1, 1, self.num_heads, self.head_dim), self.q_clip, self.eps, tau_v) | |
| r = i2m_l2_clip(r_raw, self.r_scale.view(1, 1, self.num_heads, self.d_rel), self.r_clip, self.eps, tau_v) | |
| k_d = i2m_l2_clip(k_d, None, self.q_clip, self.eps, None) | |
| v_d = i2m_rms_norm(v_d, None, self.eps) | |
| q_b = q.transpose(1, 2).contiguous() # [B, H_q, draft_len, D] | |
| k_d_b = k_d.transpose(1, 2) # [B, H_kv, draft_len, D] | |
| v_d_b = v_d.transpose(1, 2) # [B, H_kv, draft_len, D] | |
| r_b = r.transpose(1, 2) # [B, H_q, draft_len, 16] | |
| rel_all = torch.matmul(r_b, self.rel_logits_proj) # [B, H_q, draft_len, 1024] | |
| e_rel = self.rel_extent | |
| intra_bias = self.intra_rel_bias | |
| half_m = MAX_BLOCK_SLOTS - 1 | |
| if block_mask is not None and q_b.is_cuda: | |
| attn_fn = flex_fn if flex_fn is not None else flex_attention | |
| # Part A: Frozen context-KV FlexAttention ONLY (k_ctx, v_ctx have requires_grad=False -> | |
| # FlexAttention backward skips dK/dV completely AND zero atomicAdd on intra_rel_bias!) | |
| def ctx_score_mod(score, b, h, q_idx, kv_idx): | |
| q_blk = q_idx // block_size | |
| q_slot = q_idx - q_blk * block_size | |
| anchor = anchor_positions[b, q_blk] | |
| dist_ctx = (anchor + q_slot) - kv_idx | |
| in_rel = (dist_ctx >= 0) & (dist_ctx < e_rel) | |
| safe_d = torch.where(in_rel, dist_ctx, 0) | |
| return score + torch.where(in_rel, rel_all[b, h, q_idx, safe_d], 0.0) | |
| ao_ctx, lse_ctx = attn_fn( | |
| q_b, k_ctx.to(q_b.dtype), v_ctx.to(q_b.dtype), | |
| score_mod=ctx_score_mod, | |
| block_mask=block_mask, | |
| scale=self.scaling, | |
| enable_gqa=True, | |
| return_lse=True, | |
| ) # ao_ctx: [B, H_q, S, D], lse_ctx: [B, H_q, S] (natural log) | |
| # Part B: Exact batched [B, H_q, n_blocks, B_blk, B_blk] intra-block attention (zero atomicAdd!) | |
| n_blocks = draft_len // block_size | |
| G = self.num_kv_groups | |
| q_g = q_b.float().view(bsz, self.num_heads, n_blocks, block_size, self.head_dim) | |
| k_g = k_d_b.repeat_interleave(G, dim=1).float().view(bsz, self.num_heads, n_blocks, block_size, self.head_dim) | |
| v_g = v_d_b.repeat_interleave(G, dim=1).float().view(bsz, self.num_heads, n_blocks, block_size, self.head_dim) | |
| s_blk = torch.einsum("bhgqd,bhgkd->bhgqk", q_g, k_g) * self.scaling | |
| steps = torch.arange(block_size, device=q_b.device) | |
| rel_s = steps[:, None] - steps[None, :] # [bs, bs] | |
| rel_slice = rel_all[..., :block_size].float().view(bsz, self.num_heads, n_blocks, block_size, block_size) | |
| idx_c = rel_s.clamp(0, block_size - 1).view(1, 1, 1, block_size, block_size).expand(bsz, self.num_heads, n_blocks, -1, -1) | |
| b_blk_rel = torch.gather(rel_slice, 4, idx_c) | |
| b_blk_rel = torch.where((rel_s >= 0).view(1, 1, 1, block_size, block_size), b_blk_rel, 0.0) | |
| b_blk_intra = intra_bias.float()[:, (rel_s + half_m).clamp(0, 2 * half_m)].view(1, self.num_heads, 1, block_size, block_size) | |
| s_blk = s_blk + b_blk_rel + b_blk_intra | |
| if self.causal_draft: | |
| s_blk = s_blk.masked_fill((rel_s < 0).view(1, 1, 1, block_size, block_size), float("-inf")) | |
| lse_blk = torch.logsumexp(s_blk, dim=-1) # [B, H_q, n_blocks, bs] | |
| p_blk = torch.softmax(s_blk, dim=-1) | |
| ao_blk = torch.einsum("bhgqk,bhgkd->bhgqd", p_blk, v_g).reshape(bsz, self.num_heads, draft_len, self.head_dim) | |
| lse_blk_flat = lse_blk.reshape(bsz, self.num_heads, draft_len) | |
| # Exact online-softmax LogSumExp merge (mathematically identical to joint [ctx | blk] attention!) | |
| lse_b = torch.logaddexp(lse_ctx.float(), lse_blk_flat) | |
| w_ctx = torch.exp(lse_ctx.float() - lse_b).unsqueeze(-1) | |
| w_blk = torch.exp(lse_blk_flat - lse_b).unsqueeze(-1) | |
| ao_b = (ao_ctx.float() * w_ctx + ao_blk * w_blk).to(q_b.dtype) | |
| else: | |
| # Exact single-block serving path (is_serving=True) or multi-block CPU fallback | |
| G = self.num_kv_groups | |
| n_blocks = draft_len // block_size | |
| if is_serving and self.is_local and n_blocks == 1 and ctx_len > self.sliding_window: | |
| c_start = ctx_len - self.sliding_window | |
| k_ctx_w = k_ctx[:, :, c_start:, :].to(k_d.dtype) | |
| v_ctx_w = v_ctx[:, :, c_start:, :].to(v_d.dtype) | |
| k_full = torch.cat([k_ctx_w, k_d_b], dim=2).repeat_interleave(G, dim=1) | |
| v_full = torch.cat([v_ctx_w, v_d_b], dim=2).repeat_interleave(G, dim=1) | |
| eff_ctx = k_ctx_w.shape[2] | |
| else: | |
| c_start = 0 | |
| k_full = torch.cat([k_ctx.to(k_d.dtype), k_d_b], dim=2).repeat_interleave(G, dim=1) | |
| v_full = torch.cat([v_ctx.to(v_d.dtype), v_d_b], dim=2).repeat_interleave(G, dim=1) | |
| eff_ctx = ctx_len | |
| scores = torch.einsum("bhqd,bhkd->bhqk", q_b.float(), k_full.float()) * self.scaling | |
| q_idx = torch.arange(draft_len, device=q_b.device) | |
| q_blk = q_idx // block_size | |
| q_slot = q_idx % block_size | |
| anc = anchor_positions[:, q_blk] # [B, draft_len] | |
| kv_ctx = c_start + torch.arange(eff_ctx, device=q_b.device) # [eff_ctx] | |
| dist_ctx = (anc + q_slot.unsqueeze(0)).unsqueeze(-1) - kv_ctx.view(1, 1, eff_ctx) | |
| vis_ctx = kv_ctx.view(1, 1, eff_ctx) < anc.unsqueeze(-1) | |
| if self.is_local: | |
| vis_ctx = vis_ctx & (dist_ctx < self.sliding_window) | |
| in_ext = vis_ctx & (dist_ctx >= 0) & (dist_ctx < e_rel) | |
| b_ctx = torch.gather( | |
| rel_all.float(), 3, dist_ctx.clamp(0, e_rel - 1).unsqueeze(1).expand(-1, self.num_heads, -1, -1) | |
| ) | |
| scores[:, :, :, :eff_ctx] = scores[:, :, :, :eff_ctx] + torch.where(in_ext.unsqueeze(1), b_ctx, 0.0) | |
| scores[:, :, :, :eff_ctx] = scores[:, :, :, :eff_ctx].masked_fill(~vis_ctx.unsqueeze(1), float("-inf")) | |
| kv_blk = q_blk # [draft_len] | |
| kv_slot = q_slot | |
| same_blk = (q_blk[:, None] == kv_blk[None, :]) # [draft_len, draft_len] | |
| rel_s = q_slot[:, None] - kv_slot[None, :] | |
| b_blk_c = torch.gather( | |
| rel_all.float(), 3, rel_s.clamp(0, e_rel - 1).view(1, 1, draft_len, draft_len).expand(bsz, self.num_heads, -1, -1) | |
| ) | |
| b_blk_c = torch.where((same_blk & (rel_s >= 0)).view(1, 1, draft_len, draft_len), b_blk_c, 0.0) | |
| b_blk_i = intra_bias.float()[:, (rel_s + half_m).clamp(0, 2 * half_m)].unsqueeze(0) | |
| scores[:, :, :, eff_ctx:] = scores[:, :, :, eff_ctx:] + b_blk_c + torch.where(same_blk.view(1, 1, draft_len, draft_len), b_blk_i, 0.0) | |
| scores[:, :, :, eff_ctx:] = scores[:, :, :, eff_ctx:].masked_fill(~same_blk.view(1, 1, draft_len, draft_len), float("-inf")) | |
| lse_b = torch.logsumexp(scores, dim=-1) | |
| probs = torch.softmax(scores, dim=-1).nan_to_num(0.0) | |
| ao_b = torch.einsum("bhqk,bhkd->bhqd", probs, v_full.float()).to(q_b.dtype) | |
| ao = ao_b.transpose(1, 2).contiguous() # [B, draft_len, H_q, D] | |
| lse = lse_b.transpose(1, 2).contiguous() # [B, draft_len, H_q] | |
| ao_gated = i2m_gate_sink(ao, gate, lse, sink).reshape(bsz, draft_len, self.num_heads * self.head_dim) | |
| return self.wo_ud(ao_gated) | |
| class I2MDFly2DecoderLayer(nn.Module): | |
| def __init__(self, cfg: I2MDFly2Config, layer_idx: int): | |
| super().__init__() | |
| self.layer_idx = layer_idx | |
| self.is_local = layer_idx in set(cfg.local_layer_ids) | |
| self.input_layernorm = I2MRMSNorm(cfg.hidden_size, eps=cfg.rms_norm_eps) | |
| self.self_attn = I2MKVSharedAttention(cfg, is_local=self.is_local) | |
| self.post_attention_layernorm = I2MRMSNorm(cfg.hidden_size, eps=cfg.rms_norm_eps) | |
| self.mlp = I2MSwiGLUMLP(cfg.hidden_size, cfg.intermediate_size) | |
| def forward( | |
| self, | |
| draft_hidden: torch.Tensor, | |
| k_ctx: torch.Tensor, | |
| v_ctx: torch.Tensor, | |
| tau_draft: Optional[torch.Tensor], | |
| anchor_positions: torch.Tensor, | |
| block_size: int, | |
| block_mask=None, | |
| flex_fn=None, | |
| is_serving: bool = False, | |
| ) -> torch.Tensor: | |
| residual = draft_hidden | |
| h = self.input_layernorm(draft_hidden) | |
| h = self.self_attn( | |
| h, k_ctx, v_ctx, tau_draft, anchor_positions, block_size, | |
| block_mask=block_mask, flex_fn=flex_fn, is_serving=is_serving, | |
| ) | |
| draft_hidden = residual + h | |
| residual = draft_hidden | |
| h = self.post_attention_layernorm(draft_hidden) | |
| h = self.mlp(h) | |
| return residual + h | |
| class I2MAttentiveCorrection(nn.Module): | |
| """ | |
| DFly2 Eq. 11 context-reading + gated causal intra-block attentive correction in | |
| Inkling-2-Mini's sheared relative-bias space (NO RoPE, NO output sigmoid gate). | |
| Reads paired target L22 (SWA-1024 -> O(1) bandwidth across all 7 sequential slots!) | |
| plus gated causal attention over block slots 0..k. Zero-init o_proj & block_gate -> exact 0 at step 0. | |
| """ | |
| def __init__(self, cfg: I2MDFly2Config): | |
| super().__init__() | |
| self.hidden_size = cfg.hidden_size | |
| self.num_heads = cfg.num_attention_heads | |
| self.num_kv_heads = cfg.num_key_value_heads | |
| self.head_dim = cfg.head_dim | |
| self.d_rel = cfg.d_rel | |
| self.rel_extent = cfg.rel_extent | |
| self.sliding_window = cfg.sliding_window_size | |
| self.is_local = bool(cfg.attentive_correction_is_local) | |
| self.q_clip = cfg.qk_l2_clip_threshold | |
| self.r_clip = cfg.rel_l2_clip_threshold | |
| self.eps = cfg.rms_norm_eps | |
| self.num_kv_groups = self.num_heads // self.num_kv_heads | |
| self.scaling = self.head_dim ** -0.5 | |
| self.block_gated = bool(cfg.attentive_correction_block_gated) | |
| self.q_in = nn.Linear(2 * self.hidden_size, self.num_heads * self.head_dim, bias=False) | |
| self.r_in = nn.Linear(2 * self.hidden_size, self.num_heads * self.d_rel, bias=False) | |
| self.q_scale = nn.Parameter(torch.ones(self.num_heads, self.head_dim)) | |
| self.r_scale = nn.Parameter(torch.ones(self.num_heads, self.d_rel)) | |
| self.rel_logits_proj = nn.Parameter(torch.zeros(self.d_rel, self.rel_extent)) | |
| self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False) | |
| nn.init.zeros_(self.o_proj.weight) | |
| if self.block_gated: | |
| self.k_blk_proj = nn.Linear(2 * self.hidden_size, self.num_kv_heads * self.head_dim, bias=False) | |
| self.v_blk_proj = nn.Linear(2 * self.hidden_size, self.num_kv_heads * self.head_dim, bias=False) | |
| self.block_sink = nn.Parameter(torch.zeros(self.num_heads)) | |
| self.block_rel_bias = nn.Parameter(torch.zeros(self.num_heads, MAX_BLOCK_SLOTS)) | |
| self.block_gate = nn.Linear(2 * self.hidden_size, self.num_heads, bias=False) | |
| nn.init.zeros_(self.block_gate.weight) | |
| self.block_gate_bias = nn.Parameter(torch.zeros(self.num_heads, MAX_BLOCK_SLOTS)) | |
| def init_from_target_attn(self, src: dict): | |
| h = self.hidden_size | |
| self.q_in.weight.zero_() | |
| self.q_in.weight[:, :h].copy_(src["wq"]) | |
| self.r_in.weight.zero_() | |
| self.r_in.weight[:, :h].copy_(src["wr"]) | |
| self.q_scale.copy_(src["q_sc"]) | |
| self.r_scale.copy_(src["r_sc"]) | |
| self.rel_logits_proj.copy_(src["rel_proj"]) | |
| self.o_proj.weight.zero_() | |
| if self.block_gated: | |
| self.k_blk_proj.weight.zero_() | |
| self.k_blk_proj.weight[:, :h].copy_(src["wk"]) | |
| self.v_blk_proj.weight.zero_() | |
| self.v_blk_proj.weight[:, :h].copy_(src["wv"]) | |
| self.block_gate.weight.zero_() | |
| self.block_gate_bias.zero_() | |
| self.block_sink.zero_() | |
| self.block_rel_bias.zero_() | |
| def _attend_block_gated( | |
| self, | |
| q: torch.Tensor, # [B, H_q, S, D] | |
| inputs: torch.Tensor, # [B, S, 2*H] | |
| block_size: int, | |
| ) -> torch.Tensor: | |
| bsz, _, slots, _ = q.shape | |
| n_blocks = slots // block_size | |
| k_b = i2m_l2_clip( | |
| self.k_blk_proj(inputs).view(bsz, slots, self.num_kv_heads, self.head_dim), | |
| None, self.q_clip, self.eps, None, | |
| ).transpose(1, 2) | |
| v_b = i2m_rms_norm( | |
| self.v_blk_proj(inputs).view(bsz, slots, self.num_kv_heads, self.head_dim), | |
| None, self.eps, | |
| ).transpose(1, 2) | |
| k_b = k_b.repeat_interleave(self.num_kv_groups, dim=1) | |
| v_b = v_b.repeat_interleave(self.num_kv_groups, dim=1) | |
| q_g = q.float().view(bsz, self.num_heads, n_blocks, block_size, self.head_dim) | |
| k_g = k_b.float().view(bsz, self.num_heads, n_blocks, block_size, self.head_dim) | |
| v_g = v_b.float().view(bsz, self.num_heads, n_blocks, block_size, self.head_dim) | |
| logits = torch.einsum("bhgqd,bhgkd->bhgqk", q_g, k_g) * self.scaling | |
| steps = torch.arange(block_size, device=q.device) | |
| back = steps.view(-1, 1) - steps.view(1, -1) | |
| rel = self.block_rel_bias.float()[:, back.clamp(min=0)] | |
| logits = logits + rel.view(1, self.num_heads, 1, block_size, block_size) | |
| logits = logits.masked_fill(back.view(1, 1, 1, block_size, block_size) < 0, float("-inf")) | |
| sink = self.block_sink.float().view(1, self.num_heads, 1, 1, 1) | |
| total = torch.logaddexp(torch.logsumexp(logits, dim=-1, keepdim=True), sink) | |
| probs = torch.exp(logits - total) | |
| read = torch.einsum("bhgqk,bhgkd->bhgqd", probs, v_g).reshape(bsz, self.num_heads, slots, self.head_dim) | |
| slot_idx = torch.arange(slots, device=q.device) % block_size | |
| gate = torch.tanh( | |
| self.block_gate(inputs).float() | |
| + self.block_gate_bias.float()[:, slot_idx].transpose(0, 1).unsqueeze(0) | |
| ) | |
| gate = gate.transpose(1, 2).unsqueeze(-1) | |
| return (read * gate).to(q.dtype) | |
| def forward( | |
| self, | |
| h_norm: torch.Tensor, # [B, S, H] | |
| e_norm: torch.Tensor, # [B, S, H] | |
| k_ctx: torch.Tensor, # [B, H_kv, ctx_len, D] | |
| v_ctx: torch.Tensor, # [B, H_kv, ctx_len, D] | |
| tau_draft: Optional[torch.Tensor], | |
| anchor_positions: torch.Tensor, | |
| block_size: int, | |
| ctx_block_mask=None, | |
| flex_fn=None, | |
| ) -> torch.Tensor: | |
| bsz, slots, _ = h_norm.shape | |
| inputs = torch.cat([h_norm, e_norm], dim=-1) | |
| tau_v = None if (self.is_local or tau_draft is None) else tau_draft.view(bsz, slots, 1, 1) | |
| q = i2m_l2_clip( | |
| self.q_in(inputs).view(bsz, slots, self.num_heads, self.head_dim), | |
| self.q_scale.view(1, 1, self.num_heads, self.head_dim), | |
| self.q_clip, self.eps, tau_v, | |
| ).transpose(1, 2).contiguous() | |
| r = i2m_l2_clip( | |
| self.r_in(inputs).view(bsz, slots, self.num_heads, self.d_rel), | |
| self.r_scale.view(1, 1, self.num_heads, self.d_rel), | |
| self.r_clip, self.eps, tau_v, | |
| ).transpose(1, 2) | |
| rel_all = torch.matmul(r, self.rel_logits_proj) # [B, H_q, S, 1024] | |
| e_rel = self.rel_extent | |
| if ctx_block_mask is not None and q.is_cuda: | |
| attn_fn = flex_fn if flex_fn is not None else flex_attention | |
| def score_mod(score, b, h, q_idx, kv_idx): | |
| q_blk = q_idx // block_size | |
| q_slot = q_idx - q_blk * block_size | |
| anchor = anchor_positions[b, q_blk] | |
| dist = (anchor + q_slot) - kv_idx | |
| in_ext = (dist >= 0) & (dist < e_rel) | |
| safe_d = torch.where(in_ext, dist, 0) | |
| return score + torch.where(in_ext, rel_all[b, h, q_idx, safe_d], 0.0) | |
| ctx_out = attn_fn( | |
| q, k_ctx.to(q.dtype), v_ctx.to(q.dtype), | |
| score_mod=score_mod, | |
| block_mask=ctx_block_mask, | |
| scale=self.scaling, | |
| enable_gqa=True, | |
| ) | |
| else: | |
| # Exact CPU fallback for unit tests | |
| G = self.num_kv_groups | |
| ctx_len = k_ctx.shape[2] | |
| scores = torch.einsum("bhqd,bhkd->bhqk", q.float(), k_ctx.repeat_interleave(G, dim=1).float()) * self.scaling | |
| q_idx = torch.arange(slots, device=q.device) | |
| q_blk = q_idx // block_size | |
| q_slot = q_idx % block_size | |
| anc = anchor_positions[:, q_blk] # [B, S] | |
| kv_idx = torch.arange(ctx_len, device=q.device).view(1, 1, ctx_len) | |
| dist = (anc + q_slot.unsqueeze(0)).unsqueeze(-1) - kv_idx # [B, S, ctx_len] | |
| vis = kv_idx < anc.unsqueeze(-1) | |
| if self.is_local: | |
| vis = vis & (dist < self.sliding_window) | |
| in_ext = vis & (dist >= 0) & (dist < e_rel) | |
| b_ctx = torch.gather( | |
| rel_all.float(), 3, dist.clamp(0, e_rel - 1).unsqueeze(1).expand(-1, self.num_heads, -1, -1) | |
| ) | |
| scores = scores + torch.where(in_ext.unsqueeze(1), b_ctx, 0.0) | |
| scores = scores.masked_fill(~vis.unsqueeze(1), float("-inf")) | |
| probs = torch.softmax(scores, dim=-1).nan_to_num(0.0) | |
| ctx_out = torch.einsum("bhqk,bhkd->bhqd", probs, v_ctx.repeat_interleave(G, dim=1).float()).to(q.dtype) | |
| if self.block_gated: | |
| blk_out = self._attend_block_gated(q, inputs, block_size) | |
| out = ctx_out + blk_out | |
| else: | |
| out = ctx_out | |
| out = out.transpose(1, 2).contiguous().reshape(bsz, slots, self.num_heads * self.head_dim) | |
| return self.o_proj(out) | |
| def forward_single_slot( | |
| self, | |
| h_norm_k: torch.Tensor, # [B, 1, H] | |
| e_norm_k: torch.Tensor, # [B, 1, H] | |
| k_ctx: torch.Tensor, # [B, H_kv, ctx_len, D] | |
| v_ctx: torch.Tensor, # [B, H_kv, ctx_len, D] | |
| tau_k: Optional[torch.Tensor], | |
| slot_idx: int, | |
| blk_k_cache: Optional[torch.Tensor], | |
| blk_v_cache: Optional[torch.Tensor], | |
| ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[torch.Tensor]]: | |
| """Exact single-slot serving path (O(1) SWA-1024 context read + causal block slots 0..slot_idx).""" | |
| bsz = h_norm_k.shape[0] | |
| inp = torch.cat([h_norm_k, e_norm_k], dim=-1) | |
| tau_v = None if (self.is_local or tau_k is None) else tau_k.view(bsz, 1, 1, 1) | |
| q = i2m_l2_clip( | |
| self.q_in(inp).view(bsz, 1, self.num_heads, self.head_dim), | |
| self.q_scale.view(1, 1, self.num_heads, self.head_dim), | |
| self.q_clip, self.eps, tau_v, | |
| ).transpose(1, 2) # [B, H_q, 1, D] | |
| r = i2m_l2_clip( | |
| self.r_in(inp).view(bsz, 1, self.num_heads, self.d_rel), | |
| self.r_scale.view(1, 1, self.num_heads, self.d_rel), | |
| self.r_clip, self.eps, tau_v, | |
| ).transpose(1, 2) # [B, H_q, 1, 16] | |
| rel_row = torch.matmul(r, self.rel_logits_proj) # [B, H_q, 1, 1024] | |
| ctx_len = k_ctx.shape[2] | |
| if self.is_local: | |
| # Visible context positions satisfy (ctx_len + slot_idx - j) < SWA => j > ctx_len + slot_idx - SWA | |
| c_start = max(0, ctx_len + slot_idx - (self.sliding_window - 1)) | |
| kc = k_ctx[:, :, c_start:, :] | |
| vc = v_ctx[:, :, c_start:, :] | |
| else: | |
| c_start = 0 | |
| kc, vc = k_ctx, v_ctx | |
| eff_c = kc.shape[2] | |
| G = self.num_kv_groups | |
| scores = torch.einsum("bhqd,bhkd->bhqk", q.float(), kc.repeat_interleave(G, dim=1).float()) * self.scaling | |
| dist = (ctx_len + slot_idx) - (c_start + torch.arange(eff_c, device=q.device)) # [eff_c] | |
| in_ext = (dist >= 0) & (dist < self.rel_extent) | |
| b_ctx = rel_row.float()[:, :, :, dist.clamp(0, self.rel_extent - 1)] | |
| scores = scores + torch.where(in_ext.view(1, 1, 1, eff_c), b_ctx, 0.0) | |
| probs = torch.softmax(scores, dim=-1) | |
| ctx_out = torch.einsum("bhqk,bhkd->bhqd", probs, vc.repeat_interleave(G, dim=1).float()).to(q.dtype) | |
| new_k_cache, new_v_cache = blk_k_cache, blk_v_cache | |
| if self.block_gated: | |
| kb = i2m_l2_clip( | |
| self.k_blk_proj(inp).view(bsz, 1, self.num_kv_heads, self.head_dim), | |
| None, self.q_clip, self.eps, None, | |
| ).transpose(1, 2) | |
| vb = i2m_rms_norm( | |
| self.v_blk_proj(inp).view(bsz, 1, self.num_kv_heads, self.head_dim), | |
| None, self.eps, | |
| ).transpose(1, 2) | |
| new_k_cache = kb if blk_k_cache is None else torch.cat([blk_k_cache, kb], dim=2) | |
| new_v_cache = vb if blk_v_cache is None else torch.cat([blk_v_cache, vb], dim=2) | |
| k_rep = new_k_cache.repeat_interleave(G, dim=1).float() | |
| v_rep = new_v_cache.repeat_interleave(G, dim=1).float() | |
| logits = torch.einsum("bhqd,bhkd->bhqk", q.float(), k_rep) * self.scaling | |
| back = slot_idx - torch.arange(slot_idx + 1, device=q.device) | |
| rel = self.block_rel_bias.float()[:, back].view(1, self.num_heads, 1, slot_idx + 1) | |
| logits = logits + rel | |
| sink = self.block_sink.float().view(1, self.num_heads, 1, 1) | |
| total = torch.logaddexp(torch.logsumexp(logits, dim=-1, keepdim=True), sink) | |
| p_blk = torch.exp(logits - total) | |
| read = torch.einsum("bhqk,bhkd->bhqd", p_blk, v_rep) | |
| gate = torch.tanh( | |
| self.block_gate(inp).float() + self.block_gate_bias.float()[:, slot_idx].view(1, 1, self.num_heads) | |
| ).transpose(1, 2).unsqueeze(-1) | |
| out = ctx_out + (read * gate).to(q.dtype) | |
| else: | |
| out = ctx_out | |
| out = out.transpose(1, 2).contiguous().reshape(bsz, 1, self.num_heads * self.head_dim) | |
| return self.o_proj(out), new_k_cache, new_v_cache | |
| class I2MHiddenStatesCorrection(nn.Module): | |
| """TreeFlash SwiGLU + Inkling-2-Mini SWA-1024 AttentiveCorrection (zero-init residual).""" | |
| def __init__(self, cfg: I2MDFly2Config): | |
| super().__init__() | |
| self.hidden_norm = I2MRMSNorm(cfg.hidden_size, eps=cfg.rms_norm_eps) | |
| self.embed_norm = I2MRMSNorm(cfg.hidden_size, eps=cfg.rms_norm_eps) | |
| inter = cfg.hidden_correction_intermediate_size or cfg.hidden_size | |
| self.gate_proj = nn.Linear(2 * cfg.hidden_size, inter, bias=False) | |
| self.up_proj = nn.Linear(2 * cfg.hidden_size, inter, bias=False) | |
| self.down_proj = nn.Linear(inter, cfg.hidden_size, bias=False) | |
| nn.init.zeros_(self.down_proj.weight) | |
| self.attention = I2MAttentiveCorrection(cfg) if cfg.attentive_correction else None | |
| def forward( | |
| self, | |
| hidden_states: torch.Tensor, | |
| prev_embeds: torch.Tensor, | |
| k_ctx: Optional[torch.Tensor] = None, | |
| v_ctx: Optional[torch.Tensor] = None, | |
| tau_draft: Optional[torch.Tensor] = None, | |
| anchor_positions: Optional[torch.Tensor] = None, | |
| block_size: int = 8, | |
| ctx_block_mask=None, | |
| flex_fn=None, | |
| ) -> torch.Tensor: | |
| h_n = self.hidden_norm(hidden_states) | |
| e_n = self.embed_norm(prev_embeds.to(hidden_states.dtype)) | |
| cat = torch.cat([h_n, e_n], dim=-1) | |
| delta = self.down_proj(F.silu(self.gate_proj(cat)) * self.up_proj(cat)).to(hidden_states.dtype) | |
| if self.attention is not None and k_ctx is not None: | |
| attn_delta = self.attention( | |
| h_n, e_n, k_ctx, v_ctx, tau_draft, anchor_positions, | |
| block_size=block_size, ctx_block_mask=ctx_block_mask, flex_fn=flex_fn, | |
| ) | |
| delta = delta + attn_delta.to(hidden_states.dtype) | |
| return hidden_states + delta | |
| def forward_single_slot( | |
| self, | |
| h_k: torch.Tensor, | |
| e_prev: torch.Tensor, | |
| k_ctx: torch.Tensor, | |
| v_ctx: torch.Tensor, | |
| tau_k: Optional[torch.Tensor], | |
| slot_idx: int, | |
| blk_k_cache: Optional[torch.Tensor], | |
| blk_v_cache: Optional[torch.Tensor], | |
| ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[torch.Tensor]]: | |
| h_n = self.hidden_norm(h_k) | |
| e_n = self.embed_norm(e_prev.to(h_k.dtype)) | |
| cat = torch.cat([h_n, e_n], dim=-1) | |
| delta = self.down_proj(F.silu(self.gate_proj(cat)) * self.up_proj(cat)).to(h_k.dtype) | |
| new_k, new_v = blk_k_cache, blk_v_cache | |
| if self.attention is not None: | |
| attn_delta, new_k, new_v = self.attention.forward_single_slot( | |
| h_n, e_n, k_ctx, v_ctx, tau_k, slot_idx, blk_k_cache, blk_v_cache | |
| ) | |
| delta = delta + attn_delta.to(h_k.dtype) | |
| return h_k + delta, new_k, new_v | |
| def build_i2m_draft_block_masks( | |
| anchor_positions: torch.Tensor, # [B, n_blocks] | |
| block_keep_mask: torch.Tensor, # [B, n_blocks] bool | |
| ctx_doc_ids: torch.Tensor, # [B, ctx_len] int32 | |
| ctx_len: int, | |
| block_size: int, | |
| swa: int = 1024, | |
| causal_draft: bool = False, | |
| ): | |
| """ | |
| Build 2 reusable context-only FlexAttention BlockMasks for I2M DFly2-KV: | |
| 1) ctx_global_mask: Q=[S], KV=[ctx_len] (same-doc ctx < anchor; kv_idx==0 fallback for padded blocks) | |
| 2) ctx_local_mask: Q=[S], KV=[ctx_len] (same-doc ctx in SWA-1024; reused by L0, L2, AND AttentiveCorrection!) | |
| """ | |
| bsz, n_blocks = anchor_positions.shape | |
| draft_len = n_blocks * block_size | |
| device = anchor_positions.device | |
| def ctx_global_mask_mod(b, h, q_idx, kv_idx): | |
| q_blk = q_idx // block_size | |
| anchor = anchor_positions[b, q_blk] | |
| keep = block_keep_mask[b, q_blk] | |
| a_doc = ctx_doc_ids[b, anchor] | |
| kv_doc = ctx_doc_ids[b, kv_idx] | |
| valid_ctx = (kv_idx < anchor) & (a_doc >= 0) & (kv_doc == a_doc) | |
| return (keep & valid_ctx) | ((~keep) & (kv_idx == 0)) | |
| def ctx_local_mask_mod(b, h, q_idx, kv_idx): | |
| q_blk = q_idx // block_size | |
| q_slot = q_idx - q_blk * block_size | |
| anchor = anchor_positions[b, q_blk] | |
| keep = block_keep_mask[b, q_blk] | |
| a_doc = ctx_doc_ids[b, anchor] | |
| kv_doc = ctx_doc_ids[b, kv_idx] | |
| dist_ctx = (anchor + q_slot) - kv_idx | |
| valid_ctx = (kv_idx < anchor) & (dist_ctx < swa) & (a_doc >= 0) & (kv_doc == a_doc) | |
| return (keep & valid_ctx) | ((~keep) & (kv_idx == 0)) | |
| comp = device.type == "cuda" | |
| ctx_global = create_block_mask(ctx_global_mask_mod, B=bsz, H=None, Q_LEN=draft_len, KV_LEN=ctx_len, device=device, _compile=comp) | |
| ctx_local = create_block_mask(ctx_local_mask_mod, B=bsz, H=None, Q_LEN=draft_len, KV_LEN=ctx_len, device=device, _compile=comp) | |
| return ctx_global, ctx_local | |
| def sample_anchors( | |
| seq_len: int, | |
| loss_mask: torch.Tensor, | |
| doc_ids: torch.Tensor, | |
| block_size: int, | |
| num_anchors: int, | |
| injected_anchors: Optional[torch.Tensor] = None, | |
| injected_keep_mask: Optional[torch.Tensor] = None, | |
| ) -> Tuple[torch.Tensor, torch.Tensor]: | |
| bsz = loss_mask.shape[0] | |
| device = loss_mask.device | |
| if injected_anchors is not None: | |
| keep = ( | |
| injected_keep_mask.to(device=device, dtype=torch.bool) | |
| if injected_keep_mask is not None | |
| else torch.ones_like(injected_anchors, dtype=torch.bool, device=device) | |
| ) | |
| return torch.where(keep, injected_anchors.to(device=device, dtype=torch.long), 0), keep | |
| max_anchor = max(seq_len - block_size, 0) | |
| if max_anchor <= 1: | |
| return ( | |
| torch.zeros(bsz, num_anchors, dtype=torch.long, device=device), | |
| torch.zeros(bsz, num_anchors, dtype=torch.bool, device=device), | |
| ) | |
| valid = torch.zeros(bsz, max_anchor + 1, dtype=torch.bool, device=device) | |
| has_sup = (loss_mask[:, 1 : max_anchor + 1] > 0.5) | (loss_mask[:, 2 : max_anchor + 2] > 0.5) | |
| head_doc = doc_ids[:, 1 : max_anchor + 1] | |
| prev_doc = doc_ids[:, 0:max_anchor] | |
| tail_doc = doc_ids[:, block_size : max_anchor + block_size] | |
| same_doc = (head_doc >= 0) & (head_doc == prev_doc) & (head_doc == tail_doc) | |
| valid[:, 1 : max_anchor + 1] = has_sup & same_doc | |
| valid_counts = valid.sum(dim=1) | |
| indices = torch.arange(max_anchor + 1, device=device).unsqueeze(0).expand(bsz, -1) | |
| masked_idx = torch.where(valid, indices, seq_len + 1) | |
| rand_vals = torch.where(valid, torch.rand(bsz, max_anchor + 1, device=device), 2.0) | |
| _, order = rand_vals.sort(dim=1) | |
| gathered = torch.gather(masked_idx, 1, order) | |
| take_n = min(num_anchors, gathered.shape[1]) | |
| selected = gathered[:, :take_n].sort(dim=1).values | |
| if take_n < num_anchors: | |
| selected = torch.cat( | |
| [selected, torch.zeros(bsz, num_anchors - take_n, dtype=torch.long, device=device)], | |
| dim=1, | |
| ) | |
| keep_mask = torch.arange(num_anchors, device=device).unsqueeze(0) < valid_counts.unsqueeze(1).clamp(max=num_anchors) | |
| anchors = torch.where(keep_mask, selected, 0) | |
| return anchors, keep_mask | |
| class I2MDFly2DraftModel(nn.Module): | |
| def __init__(self, cfg: I2MDFly2Config): | |
| super().__init__() | |
| assert len(cfg.target_kv_layers) == cfg.num_hidden_layers | |
| self.config = cfg | |
| self.mtp_fusion = I2MMTPFusion(cfg.hidden_size, cfg.rms_norm_eps) if cfg.mtp_fusion else None | |
| self.layers = nn.ModuleList([I2MDFly2DecoderLayer(cfg, i) for i in range(cfg.num_hidden_layers)]) | |
| self.norm = I2MRMSNorm(cfg.hidden_size, eps=cfg.rms_norm_eps) | |
| self.hidden_correction = I2MHiddenStatesCorrection(cfg) if cfg.enable_hidden_correction else None | |
| self.mask_embedding = nn.Parameter(torch.zeros(cfg.hidden_size)) | |
| self._compiled_flex = None | |
| def set_compiled_flex(self, compiled_flex): | |
| self._compiled_flex = compiled_flex | |
| def init_from_teacher(self, teacher): | |
| """Warm-start all 3 draft attention blocks, norms, AttentiveCorrection, and mask_embedding from I2M teacher.""" | |
| for i, tgt_idx in enumerate(self.config.target_kv_layers): | |
| src = teacher.layers[tgt_idx]["init_attn"] | |
| dst = self.layers[i] | |
| dst.input_layernorm.weight.copy_(src["attn_nw"]) | |
| dst.post_attention_layernorm.weight.copy_(src["mlp_nw"]) | |
| a = dst.self_attn | |
| a.wq_du.weight.copy_(src["wq"]) | |
| a.wr_du.weight.copy_(src["wr"]) | |
| a.gate_attn.weight.copy_(src["wgate"]) | |
| a.attn_sink_proj.weight.copy_(src["wsink"]) | |
| a.wk_dv.weight.copy_(src["wk"]) | |
| a.wv_dv.weight.copy_(src["wv"]) | |
| a.wo_ud.weight.copy_(src["wo"]) | |
| a.q_scale.copy_(src["q_sc"]) | |
| a.r_scale.copy_(src["r_sc"]) | |
| a.rel_logits_proj.copy_(src["rel_proj"]) | |
| a.intra_rel_bias.zero_() | |
| self.norm.weight.copy_(teacher.out_norm_w) | |
| if self.hidden_correction is not None and self.hidden_correction.attention is not None: | |
| last_src = teacher.layers[self.config.target_kv_layers[-1]]["init_attn"] | |
| self.hidden_correction.attention.init_from_target_attn(last_src) | |
| if self.mtp_fusion is not None: | |
| self.mtp_fusion.gate.zero_() | |
| # Initialize mask_embedding to mean normalized embedding vector | |
| sample_emb = teacher.embed_normalized( | |
| torch.arange(min(65536, self.config.vocab_size), device=teacher.device), out_dtype=torch.float32 | |
| ) | |
| self.mask_embedding.copy_(sample_emb.mean(dim=0).to(self.mask_embedding.dtype)) | |
| def forward_train( | |
| self, | |
| input_ids: torch.Tensor, # [B, L] | |
| loss_mask: torch.Tensor, # [B, L] | |
| doc_ids: torch.Tensor, # [B, L] | |
| position_ids: torch.Tensor, # [B, L] | |
| target_kvs: List[Tuple[torch.Tensor, torch.Tensor]], # 3 x ([B, 8, L, 128], ...) | |
| target_last_hidden_normed: torch.Tensor, # [B, L, H] | |
| embed_norm_fn, # callable(ids) -> [..., H] BF16 | |
| num_anchors: int = 512, | |
| injected_anchors: Optional[torch.Tensor] = None, | |
| injected_keep_mask: Optional[torch.Tensor] = None, | |
| ) -> dict: | |
| bsz, seq_len = input_ids.shape | |
| bs = self.config.block_size | |
| device = input_ids.device | |
| anchors, keep_mask = sample_anchors( | |
| seq_len, loss_mask, doc_ids, bs, num_anchors, | |
| injected_anchors=injected_anchors, injected_keep_mask=injected_keep_mask, | |
| ) | |
| n_blocks = anchors.shape[1] | |
| anchor_toks = torch.gather(input_ids, 1, anchors.clamp(0, seq_len - 1)) # [B, n_blocks] | |
| anchor_embeds = embed_norm_fn(anchor_toks) # [B, n_blocks, H] | |
| noise = self.mask_embedding.to(anchor_embeds.dtype).view(1, 1, 1, -1).expand(bsz, n_blocks, bs, -1).clone() | |
| noise[:, :, 0, :] = anchor_embeds | |
| if self.mtp_fusion is not None: | |
| prev_pos = (anchors - 1).clamp(min=0) | |
| prev_h = torch.gather( | |
| target_last_hidden_normed, 1, | |
| prev_pos.unsqueeze(-1).expand(-1, -1, self.config.hidden_size), | |
| ) | |
| valid_prev = keep_mask & (anchors > 0) & ( | |
| torch.gather(doc_ids, 1, prev_pos) == torch.gather(doc_ids, 1, anchors.clamp(0, seq_len - 1)) | |
| ) | |
| delta0 = self.mtp_fusion(anchor_embeds, prev_h) * valid_prev.unsqueeze(-1).to(anchor_embeds.dtype) | |
| noise[:, :, 0, :] = noise[:, :, 0, :] + delta0 | |
| h = noise.reshape(bsz, n_blocks * bs, self.config.hidden_size) | |
| # Draft doc-local position_ids & log-scaling tau (for global layer 1) | |
| offsets = torch.arange(bs, device=device).view(1, 1, bs) | |
| anchor_base_pos = torch.gather(position_ids, 1, anchors.clamp(0, seq_len - 1)) | |
| draft_pos_ids = (anchor_base_pos.unsqueeze(-1) + offsets).reshape(bsz, n_blocks * bs) | |
| tau_draft = compute_log_scaling_tau( | |
| draft_pos_ids, self.config.log_scaling_n_floor, self.config.log_scaling_alpha | |
| ) | |
| if h.is_cuda: | |
| ctx_global, ctx_local = build_i2m_draft_block_masks( | |
| anchors, keep_mask, doc_ids, ctx_len=seq_len, block_size=bs, | |
| swa=self.config.sliding_window_size, causal_draft=self.config.causal_draft_attn, | |
| ) | |
| else: | |
| ctx_global = ctx_local = None | |
| for i, layer in enumerate(self.layers): | |
| k_ctx, v_ctx = target_kvs[i] | |
| bm = ctx_local if layer.is_local else ctx_global | |
| h = layer( | |
| h, k_ctx, v_ctx, tau_draft, anchors, bs, | |
| block_mask=bm, flex_fn=self._compiled_flex, | |
| ) | |
| h = self.norm(h) | |
| abs_pos = anchors.unsqueeze(-1) + offsets | |
| label_valid = abs_pos < seq_len | |
| safe_pos = abs_pos.clamp(0, seq_len - 1) | |
| target_ids = torch.gather(input_ids.unsqueeze(1).expand(-1, n_blocks, -1), 2, safe_pos) | |
| label_loss_mask = torch.gather(loss_mask.unsqueeze(1).expand(-1, n_blocks, -1), 2, safe_pos) | |
| prev_pos_slots = (abs_pos - 1).clamp(0, seq_len - 1) | |
| prev_token_ids = torch.gather(input_ids.unsqueeze(1).expand(-1, n_blocks, -1), 2, prev_pos_slots) | |
| prev_token_ids[:, :, 0] = target_ids[:, :, 0] | |
| if self.hidden_correction is not None: | |
| prev_embeds = embed_norm_fn(prev_token_ids.reshape(bsz, n_blocks * bs)) | |
| k_last, v_last = target_kvs[-1] # L22 (SWA-1024!) | |
| h_corr = self.hidden_correction( | |
| h, prev_embeds, | |
| k_ctx=k_last, v_ctx=v_last, tau_draft=tau_draft, | |
| anchor_positions=anchors, block_size=bs, | |
| ctx_block_mask=ctx_local, flex_fn=self._compiled_flex, | |
| ) | |
| else: | |
| h_corr = h | |
| flat_prev = prev_pos_slots.reshape(bsz, n_blocks * bs) | |
| teacher_h_at_labels = torch.gather( | |
| target_last_hidden_normed, 1, | |
| flat_prev.unsqueeze(-1).expand(-1, -1, self.config.hidden_size), | |
| ).reshape(bsz, n_blocks, bs, self.config.hidden_size) | |
| return { | |
| "corrected_hidden": h_corr, | |
| "raw_hidden": h, | |
| "target_ids": target_ids, | |
| "prev_token_ids": prev_token_ids, | |
| "block_keep_mask": keep_mask, | |
| "label_valid": label_valid, | |
| "label_loss_mask": label_loss_mask, | |
| "teacher_hidden_at_labels": teacher_h_at_labels, | |
| "anchors": anchors, | |
| } | |
| def draft_one_block( | |
| self, | |
| anchor_token_id: torch.Tensor, # [B] int64 at pos = ctx_len | |
| prev_hidden_normed: torch.Tensor, # [B, H] target final normed hidden at ctx_len - 1 | |
| target_kvs: List[Tuple[torch.Tensor, torch.Tensor]], # 3 x ([B, 8, ctx_len, 128], ...) | |
| anchor_pos: int, | |
| embed_norm_fn, | |
| lm_head_weight: torch.Tensor, # [V_unpad, H] | |
| temperature: float = 0.0, | |
| ) -> Tuple[torch.Tensor, torch.Tensor]: | |
| """Draft gamma = 7 tokens in ONE 3-layer pass + 7 lightweight O(1) SWA correction slots.""" | |
| bsz = anchor_token_id.shape[0] | |
| bs = self.config.block_size | |
| device = anchor_token_id.device | |
| anchor_emb = embed_norm_fn(anchor_token_id) # [B, H] | |
| noise = self.mask_embedding.to(anchor_emb.dtype).view(1, 1, -1).expand(bsz, bs, -1).clone() | |
| noise[:, 0, :] = anchor_emb | |
| if self.mtp_fusion is not None: | |
| noise[:, 0, :] = noise[:, 0, :] + self.mtp_fusion( | |
| anchor_emb.unsqueeze(1), prev_hidden_normed.unsqueeze(1) | |
| ).squeeze(1) | |
| draft_pos_ids = (torch.arange(bs, device=device) + anchor_pos).unsqueeze(0).expand(bsz, -1) | |
| tau_draft = compute_log_scaling_tau( | |
| draft_pos_ids, self.config.log_scaling_n_floor, self.config.log_scaling_alpha | |
| ) | |
| anc_tensor = torch.full((bsz, 1), anchor_pos, dtype=torch.long, device=device) | |
| h = noise | |
| for i, layer in enumerate(self.layers): | |
| k_ctx, v_ctx = target_kvs[i] | |
| h = layer(h, k_ctx, v_ctx, tau_draft, anc_tensor, bs, block_mask=None, is_serving=True) | |
| h = self.norm(h) | |
| k_last, v_last = target_kvs[-1] # L22 (SWA-1024) | |
| blk_k_cache = blk_v_cache = None | |
| if self.hidden_correction is not None and self.hidden_correction.attention is not None: | |
| _, blk_k_cache, blk_v_cache = self.hidden_correction.forward_single_slot( | |
| h[:, 0:1, :], anchor_emb.unsqueeze(1), | |
| k_last, v_last, tau_draft[:, 0:1], | |
| slot_idx=0, blk_k_cache=None, blk_v_cache=None, | |
| ) | |
| soft_cap = self.config.final_logit_softcapping | |
| draft_ids = [] | |
| draft_logits = [] | |
| prev_tok = anchor_token_id | |
| for slot in range(1, bs): | |
| h_k = h[:, slot : slot + 1, :] | |
| if self.hidden_correction is not None: | |
| e_prev = embed_norm_fn(prev_tok).unsqueeze(1) | |
| h_k, blk_k_cache, blk_v_cache = self.hidden_correction.forward_single_slot( | |
| h_k, e_prev, k_last, v_last, tau_draft[:, slot : slot + 1], | |
| slot_idx=slot, blk_k_cache=blk_k_cache, blk_v_cache=blk_v_cache, | |
| ) | |
| logits = F.linear(h_k.squeeze(1).to(lm_head_weight.dtype), lm_head_weight).float() | |
| if soft_cap > 0.0: | |
| logits = soft_cap * torch.tanh(logits / soft_cap) | |
| if temperature > 0.0: | |
| probs = F.softmax(logits / temperature, dim=-1) | |
| tok = torch.multinomial(probs, num_samples=1).squeeze(-1) | |
| else: | |
| tok = logits.argmax(dim=-1) | |
| draft_ids.append(tok) | |
| draft_logits.append(logits) | |
| prev_tok = tok | |
| return torch.stack(draft_ids, dim=1), torch.stack(draft_logits, dim=1) | |