"""第 04 章核心模块 03:在线解剖 Clover modeling_clover_moe.py 右卷积源码,手写零初始化右卷积 + 块内双向 GDN 融合桥。""" from __future__ import annotations import hashlib import json from pathlib import Path from typing import Any from huggingface_hub import hf_hub_download, list_repo_files import torch import torch.nn as nn import torch.nn.functional as F from gated_deltanet_wy_chunkwise import gated_deltanet_recurrent_ref CLOVER_REPO = "Diffuspace/Clover-35B-A3B-Preview" class BlockBoundedRightConv1d(nn.Module): """Clover 核心巧思:因果左卷积 + 严格限制在活跃块边界内的零初始化右向短卷积(conv_right_weight)。""" def __init__(self, channels: int, left_kernel: int = 4, right_kernel: int = 3, block_size: int = 16) -> None: super().__init__() self.channels = channels self.left_kernel = left_kernel self.right_kernel = right_kernel self.block_size = block_size self.conv_left = nn.Conv1d(channels, channels, kernel_size=left_kernel, groups=channels, bias=True) # 独立右向深度卷积参数:全零初始化保障 AR -> dLLM 热启动第 0 步输出 100.0% 恒等无震荡! self.conv_right_weight = nn.Parameter(torch.zeros((channels, 1, right_kernel))) def forward(self, x: torch.Tensor) -> torch.Tensor: """输入 x: [B, L, C](L 为 block_size 整数倍);输出融合局部因果与块内右邻上下文的激活 [B, L, C]。""" bsz, seq_len, channels = x.shape if seq_len % self.block_size != 0: raise ValueError(f"seq_len ({seq_len}) 必须为 block_size ({self.block_size}) 的整数倍") n_blocks = seq_len // self.block_size # 1. 标准全序列因果左卷积(允许跨历史块读取左侧上下文 [t - K_L + 1 .. t]) x_t = x.transpose(1, 2) # [B, C, L] left_padded = F.pad(x_t, (self.left_kernel - 1, 0)) out_left = self.conv_left(left_padded).transpose(1, 2) # [B, L, C] # 2. 块级隔离右卷积:先重排为 [B * N_blk, C, B_blk] 再在块右侧补零,物理断绝偷看下一块 b+1 的任何通路! x_blk = x.view(bsz * n_blocks, self.block_size, channels).transpose(1, 2) # [B*N_blk, C, B_blk] # 读取块内未来槽位 [t + 1 .. t + right_kernel]:先左移 1 位并在块尾补 right_kernel 个 0 x_shifted_right = F.pad(x_blk[:, :, 1:], (0, self.right_kernel)) out_right_blk = F.conv1d(x_shifted_right, self.conv_right_weight, groups=channels) out_right = out_right_blk.transpose(1, 2).reshape(bsz, seq_len, channels) return F.silu(out_left + out_right) class CloverBlockBidirectionalGDN(nn.Module): """Clover 混合线性层:历史块严格因果递推保前缀状态 S_prefix + 块内右卷积与零初始化反向 GDN 桥。""" def __init__( self, d_model: int = 128, n_heads: int = 4, block_size: int = 16, enable_right_conv: bool = True, enable_bidir_gdn: bool = True, ) -> None: super().__init__() self.d_model = d_model self.n_heads = n_heads self.head_dim = d_model // n_heads self.block_size = block_size self.enable_right_conv = enable_right_conv self.enable_bidir_gdn = enable_bidir_gdn self.norm1 = nn.RMSNorm(d_model) self.wqkv = nn.Linear(d_model, d_model * 3, bias=False) self.conv_qkv = BlockBoundedRightConv1d( channels=d_model * 3, left_kernel=4, right_kernel=3, block_size=block_size, ) self.w_beta = nn.Linear(d_model, n_heads, bias=True) self.w_g = nn.Linear(d_model, n_heads, bias=True) self.wo_causal = nn.Linear(d_model, d_model, bias=False) # 块内反向扫描融合投影:同样全零初始化,确保加载因果预训练权重时第 0 步零扰动 self.wo_bidir = nn.Linear(d_model, d_model, bias=False) nn.init.zeros_(self.wo_bidir.weight) self.norm2 = nn.RMSNorm(d_model) self.ffn = nn.Sequential( nn.Linear(d_model, d_model * 3, bias=False), nn.SiLU(), nn.Linear(d_model * 3, d_model, bias=False), ) def forward(self, x: torch.Tensor) -> torch.Tensor: bsz, seq_len, _ = x.shape n_blocks = seq_len // self.block_size h = self.norm1(x) qkv_raw = self.wqkv(h) if self.enable_right_conv: qkv_act = self.conv_qkv(qkv_raw) else: qkv_t = qkv_raw.transpose(1, 2) qkv_act = F.silu(self.conv_qkv.conv_left(F.pad(qkv_t, (self.conv_qkv.left_kernel - 1, 0))).transpose(1, 2)) q, k, v = qkv_act.chunk(3, dim=-1) q_h = F.normalize(q.view(bsz, seq_len, self.n_heads, self.head_dim).transpose(1, 2), dim=-1) k_h = F.normalize(k.view(bsz, seq_len, self.n_heads, self.head_dim).transpose(1, 2), dim=-1) v_h = v.view(bsz, seq_len, self.n_heads, self.head_dim).transpose(1, 2) g = -F.softplus(self.w_g(h).transpose(1, 2) - 2.0) beta = torch.sigmoid(self.w_beta(h).transpose(1, 2)) * 1.3 # 1. 全局因果前向 GDN:历史块状态 S_prefix 严格单向向右传递,绝不受未来块污染 out_fwd, _ = gated_deltanet_recurrent_ref(q_h, k_h, v_h, g, beta) out_merged = self.wo_causal(out_fwd.transpose(1, 2).reshape(bsz, seq_len, self.d_model)) # 2. 块内隔离反向 GDN:每个活跃块独立从 0 状态自右向左扫描,让左侧 [MASK] 看清块尾已揭秘锚点! if self.enable_bidir_gdn: q_rev = q_h.view(bsz, self.n_heads, n_blocks, self.block_size, self.head_dim).flip(dims=[3]) k_rev = k_h.view(bsz, self.n_heads, n_blocks, self.block_size, self.head_dim).flip(dims=[3]) v_rev = v_h.view(bsz, self.n_heads, n_blocks, self.block_size, self.head_dim).flip(dims=[3]) g_rev = g.view(bsz, self.n_heads, n_blocks, self.block_size).flip(dims=[3]) b_rev = beta.view(bsz, self.n_heads, n_blocks, self.block_size).flip(dims=[3]) # 将 (bsz * n_blocks) 折入 batch 维独立运行,物理保证块 b+1 的状态绝不流入块 b! q_rb = q_rev.permute(0, 2, 1, 3, 4).reshape(bsz * n_blocks, self.n_heads, self.block_size, self.head_dim) k_rb = k_rev.permute(0, 2, 1, 3, 4).reshape(bsz * n_blocks, self.n_heads, self.block_size, self.head_dim) v_rb = v_rev.permute(0, 2, 1, 3, 4).reshape(bsz * n_blocks, self.n_heads, self.block_size, self.head_dim) g_rb = g_rev.permute(0, 2, 1, 3).reshape(bsz * n_blocks, self.n_heads, self.block_size) b_rb = b_rev.permute(0, 2, 1, 3).reshape(bsz * n_blocks, self.n_heads, self.block_size) out_rb, _ = gated_deltanet_recurrent_ref(q_rb, k_rb, v_rb, g_rb, b_rb) out_rev = ( out_rb.view(bsz, n_blocks, self.n_heads, self.block_size, self.head_dim) .flip(dims=[3]) .permute(0, 1, 3, 2, 4) .reshape(bsz, seq_len, self.d_model) ) out_merged = out_merged + self.wo_bidir(out_rev) x = x + out_merged return x + self.ffn(self.norm2(x)) def inspect_clover_upstream_gdn_source() -> dict[str, Any]: """实验 3A:直接从 Hugging Face Hub 在线拉取 Clover-35B-A3B modeling_clover_moe.py 与权重索引核查 conv_right_weight。""" repo_files = list_repo_files(CLOVER_REPO) idx_path = Path(hf_hub_download(CLOVER_REPO, "model.safetensors.index.json")) weight_map: dict[str, str] = json.loads(idx_path.read_text(encoding="utf-8")).get("weight_map", {}) right_conv_keys = sorted([k for k in weight_map if "conv_right" in k or "right_conv" in k]) linear_attn_keys = [k for k in weight_map if "linear_attn" in k] modeling_audit: dict[str, Any] = {"found_modeling_py": "modeling_clover_moe.py" in repo_files} if modeling_audit["found_modeling_py"]: mod_path = Path(hf_hub_download(CLOVER_REPO, "modeling_clover_moe.py")) src = mod_path.read_text(encoding="utf-8") lines = src.splitlines() right_lines = [ln.strip() for ln in lines if "conv_right" in ln or "block_size" in ln] modeling_audit.update({ "line_count": len(lines), "mentions_conv_right_weight": "conv_right_weight" in src, "sample_lines": right_lines[:8], }) return { "upstream_repo": CLOVER_REPO, "conv_right_tensor_count_in_index": len(right_conv_keys), "sample_conv_right_tensor_names": right_conv_keys[:4], "total_linear_attn_tensors_in_index": len(linear_attn_keys), "modeling_source_audit": modeling_audit, } def verify_zero_shock_init_and_zero_leakage(device: torch.device) -> dict[str, Any]: """实验 3B:严格证明(1)零初始化第 0 步与纯因果 GDN 输出误差为 0.0;(2)第 1 步反向传播无死锁且未来块梯度严格为 0.0!""" torch.manual_seed(20260403) block_size = 16 seq_len = 64 # 4 个块:[0:16], [16:32], [32:48], [48:64] d_model = 128 layer_bi = CloverBlockBidirectionalGDN( d_model=d_model, n_heads=4, block_size=block_size, enable_right_conv=True, enable_bidir_gdn=True, ).to(device=device, dtype=torch.float32) x_probe = torch.randn((2, seq_len, d_model), dtype=torch.float32, device=device, requires_grad=True) # 1. 第 0 步热启动恒等性:对比开启双向组件(全零初始化)与强制走纯因果分支的输出差异 with torch.no_grad(): layer_bi.enable_right_conv = False layer_bi.enable_bidir_gdn = False out_pure_causal = layer_bi(x_probe) layer_bi.enable_right_conv = True layer_bi.enable_bidir_gdn = True out_zero_init_bi = layer_bi(x_probe) step0_warmstart_diff = float((out_pure_causal - out_zero_init_bi).abs().max().item()) # 2. 第 1 步反向梯度:验证上游主干特征非零时 conv_right_weight 与 wo_bidir 首步即获非零梯度(打破零初始化死锁误区) out_step1 = layer_bi(x_probe) loss_step1 = out_step1[:, 16:24, :].pow(2).sum() loss_step1.backward() step1_conv_right_grad_max = float(layer_bi.conv_qkv.conv_right_weight.grad.abs().max().item()) step1_wo_bidir_grad_max = float(layer_bi.wo_bidir.weight.grad.abs().max().item()) # 3. 更新一步非零参数后,对 Block 1 左半部分 [16:20] 求损失,审计全序列 4 个块的输入梯度分布! with torch.no_grad(): layer_bi.conv_qkv.conv_right_weight.normal_(mean=0.0, std=0.15) layer_bi.wo_bidir.weight.normal_(mean=0.0, std=0.15) layer_bi.zero_grad(set_to_none=True) x_audit = torch.randn((1, seq_len, d_model), dtype=torch.float32, device=device, requires_grad=True) out_audit = layer_bi(x_audit) # 仅取 Block 1(槽位 16..31)最左侧槽位 16..19 计算损失 loss_blk1_left = out_audit[:, 16:20, :].sum() loss_blk1_left.backward() assert x_audit.grad is not None g_in = x_audit.grad.abs() grad_prefix_blk0 = float(g_in[:, 0:16, :].max().item()) grad_intra_blk1_right = float(g_in[:, 20:32, :].max().item()) grad_future_blks23 = float(g_in[:, 32:64, :].max().item()) assert step0_warmstart_diff == 0.0, f"全零初始化第 0 步必须与纯因果模型逐位全等,实测误差: {step0_warmstart_diff}" assert step1_wo_bidir_grad_max > 0.0, "wo_bidir 首步梯度不应为零" assert grad_intra_blk1_right > 1e-4, "块内右侧锚点应当向同块左侧槽位传递反向梯度" assert grad_future_blks23 == 0.0, f"严禁泄漏任何未来块 (Block 2/3) 梯度,实测: {grad_future_blks23}" return { "step0_ar_warmstart_fp32_max_diff": step0_warmstart_diff, "step1_conv_right_grad_max": round(step1_conv_right_grad_max, 6), "step1_wo_bidir_grad_max": round(step1_wo_bidir_grad_max, 6), "block1_left_loss_autograd_audit": { "historical_prefix_block0_grad_max": round(grad_prefix_blk0, 6), "intra_block1_right_anchor_grad_max": round(grad_intra_blk1_right, 6), "future_blocks23_grad_max": grad_future_blks23, }, } class BlockSpanInfillModel(nn.Module): def __init__(self, vocab_size: int = 32, d_model: int = 128, block_size: int = 16, variant: str = "clover_full") -> None: super().__init__() use_rconv = variant in {"right_conv_only", "clover_full"} use_bidir = variant == "clover_full" self.emb = nn.Embedding(vocab_size, d_model) self.pos = nn.Embedding(32, d_model) self.l1 = CloverBlockBidirectionalGDN(d_model, 4, block_size, enable_right_conv=use_rconv, enable_bidir_gdn=use_bidir) self.l2 = CloverBlockBidirectionalGDN(d_model, 4, block_size, enable_right_conv=use_rconv, enable_bidir_gdn=use_bidir) self.norm = nn.RMSNorm(d_model) self.head = nn.Linear(d_model, vocab_size, bias=False) def forward(self, ids: torch.Tensor) -> torch.Tensor: p = torch.arange(ids.size(1), device=ids.device).unsqueeze(0) return self.head(self.norm(self.l2(self.l1(self.emb(ids) + self.pos(p))))) def benchmark_right_anchored_type_infilling(device: torch.device) -> dict[str, Any]: """实验 3C:在 L4 GPU 上对比纯因果 GDN、仅加右卷积、以及完整 Clover 块内双向 GDN 的右锚点类型推断准确率。 模拟块扩散高频场景(如 Rust `let x: [MASK] = parse(..., 42u64);`): 在同一个 16-token 活跃生成块内,右侧已率先揭秘高置信度字面量后缀,模型需并行推断左侧 [MASK] 类型标注: - 近距依赖(距离 +2 槽位,位于右卷积感受野内) - 远距依赖(距离 +11 槽位,跨越整个活跃块,需依赖块内双向状态融合桥) """ g = torch.Generator() g.manual_seed(20260405) mask_id = 0 num_types = 8 # 类型标签 8..15,对应块尾字面量后缀 16..23 def make_split(n: int) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: # 序列长 32(2 个 16-token 块),第 1 块含两处待推断 [MASK]:槽位 18(距近锚点 20 仅 +2 步)与槽位 19(距块尾远锚点 30 达 +11 步) x = torch.randint(1, 7, (n, 32), generator=g) y_near = torch.zeros((n,), dtype=torch.long) y_far = torch.zeros((n,), dtype=torch.long) for i in range(n): t_near = int(torch.randint(0, num_types, (1,), generator=g).item()) t_far = int(torch.randint(0, num_types, (1,), generator=g).item()) x[i, 18] = mask_id x[i, 20] = 16 + t_near # 近距右锚点(+2) x[i, 19] = mask_id x[i, 30] = 16 + t_far # 块尾远距右锚点(+11) y_near[i] = 8 + t_near y_far[i] = 8 + t_far return x, y_near, y_far tr_x, tr_yn, tr_yf = make_split(2048) va_x, va_yn, va_yf = make_split(512) sha16 = hashlib.sha256( json.dumps({"tx": tr_x[:64].tolist(), "vx": va_x[:64].tolist()}, separators=(",", ":")).encode("utf-8") ).hexdigest()[:16] tr_x, tr_yn, tr_yf = tr_x.to(device), tr_yn.to(device), tr_yf.to(device) va_x, va_yn, va_yf = va_x.to(device), va_yn.to(device), va_yf.to(device) results: dict[str, Any] = {} for variant in ("causal_only", "right_conv_only", "clover_full"): torch.manual_seed(20260406) torch.cuda.manual_seed_all(20260406) model = BlockSpanInfillModel(vocab_size=32, d_model=128, block_size=16, variant=variant).to(device) opt = torch.optim.AdamW(model.parameters(), lr=2.5e-3, weight_decay=1e-2) model.train() for _ in range(420): idx = torch.randint(0, tr_x.size(0), (128,), device=device) logits = model(tr_x[idx]) loss = 0.5 * ( F.cross_entropy(logits[:, 18, :], tr_yn[idx]) + F.cross_entropy(logits[:, 19, :], tr_yf[idx]) ) opt.zero_grad(set_to_none=True) loss.backward() opt.step() model.eval() with torch.no_grad(): v_logits = model(va_x) near_acc = float((v_logits[:, 18, :].argmax(dim=-1) == va_yn).float().mean().item() * 100.0) far_acc = float((v_logits[:, 19, :].argmax(dim=-1) == va_yf).float().mean().item() * 100.0) results[variant] = { "near_right_anchor_plus2_acc_pct": round(near_acc, 2), "far_right_anchor_plus11_acc_pct": round(far_acc, 2), "mean_infill_acc_pct": round(0.5 * (near_acc + far_acc), 2), } assert results["causal_only"]["near_right_anchor_plus2_acc_pct"] < 25.0, "纯因果模型无法看见右侧锚点,准确率应接近 12.5% 盲猜" assert results["right_conv_only"]["near_right_anchor_plus2_acc_pct"] > 95.0, "右卷积应精准解决局部右邻 (+2) 依赖" assert results["clover_full"]["far_right_anchor_plus11_acc_pct"] > 95.0, "完整块内双向 GDN 应解决全块跨度 (+11) 右锚点依赖" return { "dataset_fingerprint_sha256_16": sha16, "random_guess_baseline_pct": 12.5, "variants": results, } def run_clover_right_conv_gdn_audit(device: torch.device) -> dict[str, Any]: upstream = inspect_clover_upstream_gdn_source() invariants = verify_zero_shock_init_and_zero_leakage(device) infill_bench = benchmark_right_anchored_type_infilling(device) return { "clover_upstream_gdn_inspection": upstream, "zero_shock_warmstart_and_leakage_proof": invariants, "right_anchored_span_infilling_benchmark": infill_bench, }