Update modeling_omega.py
Browse files- modeling_omega.py +37 -44
modeling_omega.py
CHANGED
|
@@ -8,22 +8,22 @@ from transformers.modeling_outputs import CausalLMOutputWithPast
|
|
| 8 |
from .configuration_omega import OmegaConfig
|
| 9 |
|
| 10 |
# ============================================================
|
| 11 |
-
# 1. QUANTIZATION UTILITIES
|
| 12 |
# ============================================================
|
| 13 |
|
| 14 |
class OmegaQuantLinear(nn.Module):
|
| 15 |
"""
|
| 16 |
-
|
| 17 |
-
|
| 18 |
"""
|
| 19 |
def __init__(self, in_features, out_features, bias=False):
|
| 20 |
super().__init__()
|
| 21 |
self.in_features = in_features
|
| 22 |
self.out_features = out_features
|
| 23 |
|
| 24 |
-
# Binary containers
|
| 25 |
-
self.register_buffer('qweight', torch.zeros((
|
| 26 |
-
self.register_buffer('scales', torch.zeros((
|
| 27 |
|
| 28 |
if bias:
|
| 29 |
self.register_buffer('bias', torch.zeros((out_features), dtype=torch.bfloat16))
|
|
@@ -32,33 +32,30 @@ class OmegaQuantLinear(nn.Module):
|
|
| 32 |
|
| 33 |
def _unpack(self):
|
| 34 |
"""
|
| 35 |
-
|
| 36 |
-
|
| 37 |
"""
|
| 38 |
device = self.qweight.device
|
| 39 |
-
# 1.
|
| 40 |
-
# shape: [
|
| 41 |
-
unpacked = torch.zeros((self.
|
| 42 |
dtype=torch.int32, device=device)
|
| 43 |
|
| 44 |
for i in range(8):
|
| 45 |
unpacked[..., i] = (self.qweight >> (i * 4)) & 0xF
|
| 46 |
|
| 47 |
-
# 2. Reshape to
|
| 48 |
-
|
| 49 |
-
|
| 50 |
|
| 51 |
-
# 3. Apply
|
| 52 |
-
# Apply group-wise scaling (group_size=128)
|
| 53 |
-
weight = (q_weight.to(torch.bfloat16) - 8.0)
|
| 54 |
-
|
| 55 |
-
# scales shape: [In, Out/128]. Upsample to [In, Out]
|
| 56 |
s = self.scales.repeat_interleave(128, dim=1)
|
| 57 |
-
return
|
| 58 |
|
| 59 |
def forward(self, x):
|
| 60 |
-
weight
|
| 61 |
-
|
|
|
|
| 62 |
|
| 63 |
# ============================================================
|
| 64 |
# 2. CORE UTILITIES
|
|
@@ -93,14 +90,13 @@ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
|
|
| 93 |
return q_embed, k_embed
|
| 94 |
|
| 95 |
# ============================================================
|
| 96 |
-
# 3. COMPONENTS
|
| 97 |
# ============================================================
|
| 98 |
|
| 99 |
class OmegaAttention(nn.Module):
|
| 100 |
def __init__(self, config, layer_idx):
|
| 101 |
super().__init__()
|
| 102 |
self.config = config
|
| 103 |
-
# All Projections now use QuantLinear
|
| 104 |
self.q_a_proj = OmegaQuantLinear(config.hidden_size, config.q_lora_rank, bias=False)
|
| 105 |
self.q_a_layernorm = DeepseekV3RMSNorm(config.q_lora_rank)
|
| 106 |
self.q_b_proj = OmegaQuantLinear(config.q_lora_rank, config.num_attention_heads * (config.qk_nope_head_dim + config.qk_rope_head_dim), bias=False)
|
|
@@ -110,13 +106,13 @@ class OmegaAttention(nn.Module):
|
|
| 110 |
self.o_proj = OmegaQuantLinear(config.num_attention_heads * config.v_head_dim, config.hidden_size, bias=False)
|
| 111 |
self.rotary_emb = OmegaRotaryEmbedding(config.qk_rope_head_dim)
|
| 112 |
|
| 113 |
-
def forward(self,
|
| 114 |
-
bsz, q_len, _ =
|
| 115 |
-
q_a = self.q_a_layernorm(self.q_a_proj(
|
| 116 |
q = self.q_b_proj(q_a).view(bsz, q_len, self.config.num_attention_heads, -1).transpose(1, 2)
|
| 117 |
q_nope, q_pe = q.split([self.config.qk_nope_head_dim, self.config.qk_rope_head_dim], dim=-1)
|
| 118 |
|
| 119 |
-
kv_a_raw = self.kv_a_proj_with_mqa(
|
| 120 |
kv_a, k_pe = kv_a_raw.split([self.config.kv_lora_rank, self.config.qk_rope_head_dim], dim=-1)
|
| 121 |
k_pe = k_pe.view(bsz, q_len, 1, -1).transpose(1, 2)
|
| 122 |
|
|
@@ -131,7 +127,7 @@ class OmegaAttention(nn.Module):
|
|
| 131 |
|
| 132 |
attn = (q @ k.transpose(-1, -2)) * (q.shape[-1]**-0.5)
|
| 133 |
if attention_mask is not None: attn += attention_mask
|
| 134 |
-
attn = F.softmax(attn, dim=-1, dtype=torch.float32).to(
|
| 135 |
out = (attn @ v).transpose(1, 2).reshape(bsz, q_len, -1)
|
| 136 |
return self.o_proj(out), None, None
|
| 137 |
|
|
@@ -141,9 +137,7 @@ class OmegaConsensusMLP(nn.Module):
|
|
| 141 |
self.config = config
|
| 142 |
self.layer_idx = layer_idx
|
| 143 |
|
| 144 |
-
#
|
| 145 |
-
# Note: If Layer 0 was patched to Dense during Forge,
|
| 146 |
-
# it will be caught by the standard gate_proj naming.
|
| 147 |
if layer_idx == 0:
|
| 148 |
self.gate_proj = OmegaQuantLinear(config.hidden_size, 18432, bias=False)
|
| 149 |
self.up_proj = OmegaQuantLinear(config.hidden_size, 18432, bias=False)
|
|
@@ -155,17 +149,18 @@ class OmegaConsensusMLP(nn.Module):
|
|
| 155 |
"down_proj": OmegaQuantLinear(config.intermediate_size, config.hidden_size, bias=False)
|
| 156 |
})
|
| 157 |
self.wide_gate_up = OmegaQuantLinear(config.hidden_size, config.expert_intermediate * config.num_experts_per_layer * 2, bias=False)
|
| 158 |
-
|
| 159 |
-
# 3D parameter dequantization (packed as 2D for safetensors compatibility)
|
| 160 |
-
# Expert down weights are treated as a specialized 2D block
|
| 161 |
self.expert_down_weights_packed = OmegaQuantLinear(config.num_experts_per_layer * config.expert_intermediate, config.hidden_size, bias=False)
|
| 162 |
self.register_buffer("importance", torch.ones(config.num_experts_per_layer))
|
| 163 |
|
| 164 |
def forward(self, x):
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
c_gate = self.chairman.gate_proj(x)
|
| 170 |
c_up = self.chairman.up_proj(x)
|
| 171 |
shared_out = self.chairman.down_proj(F.silu(c_gate) * c_up)
|
|
@@ -174,12 +169,11 @@ class OmegaConsensusMLP(nn.Module):
|
|
| 174 |
gate, up = wide_out.chunk(2, dim=-1)
|
| 175 |
lane_acts = F.silu(gate) * up
|
| 176 |
|
| 177 |
-
#
|
| 178 |
-
# We unpack the weights and reshape to [E, I, H]
|
| 179 |
e_weights = self.expert_down_weights_packed._unpack().view(self.config.num_experts_per_layer, self.config.expert_intermediate, -1)
|
| 180 |
expert_outs = torch.einsum('bsei,eih->bseh', lane_acts, e_weights)
|
| 181 |
|
| 182 |
-
#
|
| 183 |
c_norm = torch.norm(shared_out, dim=-1, keepdim=True) + 1e-6
|
| 184 |
agreement = torch.einsum('bseh,bsh->bse', expert_outs.float(), shared_out.float()) / c_norm.float()
|
| 185 |
mask = torch.maximum(F.relu(agreement / self.config.tau).to(x.dtype),
|
|
@@ -189,7 +183,7 @@ class OmegaConsensusMLP(nn.Module):
|
|
| 189 |
return shared_out + council_out
|
| 190 |
|
| 191 |
# ============================================================
|
| 192 |
-
# 4.
|
| 193 |
# ============================================================
|
| 194 |
|
| 195 |
class OmegaDecoderLayer(nn.Module):
|
|
@@ -207,7 +201,6 @@ class OmegaForCausalLM(PreTrainedModel):
|
|
| 207 |
config_class = OmegaConfig
|
| 208 |
def __init__(self, config):
|
| 209 |
super().__init__(config)
|
| 210 |
-
# Keep sensitive Bookends in BF16
|
| 211 |
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 212 |
self.layers = nn.ModuleList([OmegaDecoderLayer(config, i) for i in range(config.num_hidden_layers)])
|
| 213 |
self.norm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
|
|
|
| 8 |
from .configuration_omega import OmegaConfig
|
| 9 |
|
| 10 |
# ============================================================
|
| 11 |
+
# 1. QUANTIZATION UTILITIES (Bit-Unpacking)
|
| 12 |
# ============================================================
|
| 13 |
|
| 14 |
class OmegaQuantLinear(nn.Module):
|
| 15 |
"""
|
| 16 |
+
On-the-fly dequantization kernel.
|
| 17 |
+
Unpacks 8x4-bit weights from Int32 containers into BFloat16 registers.
|
| 18 |
"""
|
| 19 |
def __init__(self, in_features, out_features, bias=False):
|
| 20 |
super().__init__()
|
| 21 |
self.in_features = in_features
|
| 22 |
self.out_features = out_features
|
| 23 |
|
| 24 |
+
# Binary containers as defined in the Forge process
|
| 25 |
+
self.register_buffer('qweight', torch.zeros((out_features, in_features // 8), dtype=torch.int32))
|
| 26 |
+
self.register_buffer('scales', torch.zeros((out_features, in_features // 128), dtype=torch.bfloat16))
|
| 27 |
|
| 28 |
if bias:
|
| 29 |
self.register_buffer('bias', torch.zeros((out_features), dtype=torch.bfloat16))
|
|
|
|
| 32 |
|
| 33 |
def _unpack(self):
|
| 34 |
"""
|
| 35 |
+
JIT Unpacking: Int32 -> 8x 4-bit -> BFloat16.
|
| 36 |
+
Memory Boundary: Only materializes weights for the current layer execution.
|
| 37 |
"""
|
| 38 |
device = self.qweight.device
|
| 39 |
+
# 1. De-interleave bits
|
| 40 |
+
# Resulting shape: [Out, In/8, 8]
|
| 41 |
+
unpacked = torch.zeros((self.out_features, self.in_features // 8, 8),
|
| 42 |
dtype=torch.int32, device=device)
|
| 43 |
|
| 44 |
for i in range(8):
|
| 45 |
unpacked[..., i] = (self.qweight >> (i * 4)) & 0xF
|
| 46 |
|
| 47 |
+
# 2. Reshape to [Out, In] and apply offset (Forge used +8)
|
| 48 |
+
q_weight = unpacked.view(self.out_features, self.in_features)
|
| 49 |
+
fp_weight = (q_weight.to(torch.bfloat16) - 8.0)
|
| 50 |
|
| 51 |
+
# 3. Apply scales (Block size 128)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
s = self.scales.repeat_interleave(128, dim=1)
|
| 53 |
+
return fp_weight * s
|
| 54 |
|
| 55 |
def forward(self, x):
|
| 56 |
+
# We materialise the BF16 weight locally within the function scope
|
| 57 |
+
# It is garbage collected immediately after the linear operation
|
| 58 |
+
return F.linear(x, self._unpack(), self.bias)
|
| 59 |
|
| 60 |
# ============================================================
|
| 61 |
# 2. CORE UTILITIES
|
|
|
|
| 90 |
return q_embed, k_embed
|
| 91 |
|
| 92 |
# ============================================================
|
| 93 |
+
# 3. COMPONENTS
|
| 94 |
# ============================================================
|
| 95 |
|
| 96 |
class OmegaAttention(nn.Module):
|
| 97 |
def __init__(self, config, layer_idx):
|
| 98 |
super().__init__()
|
| 99 |
self.config = config
|
|
|
|
| 100 |
self.q_a_proj = OmegaQuantLinear(config.hidden_size, config.q_lora_rank, bias=False)
|
| 101 |
self.q_a_layernorm = DeepseekV3RMSNorm(config.q_lora_rank)
|
| 102 |
self.q_b_proj = OmegaQuantLinear(config.q_lora_rank, config.num_attention_heads * (config.qk_nope_head_dim + config.qk_rope_head_dim), bias=False)
|
|
|
|
| 106 |
self.o_proj = OmegaQuantLinear(config.num_attention_heads * config.v_head_dim, config.hidden_size, bias=False)
|
| 107 |
self.rotary_emb = OmegaRotaryEmbedding(config.qk_rope_head_dim)
|
| 108 |
|
| 109 |
+
def forward(self, hidden_states, attention_mask=None, position_ids=None, past_key_value=None, **kwargs):
|
| 110 |
+
bsz, q_len, _ = hidden_states.size()
|
| 111 |
+
q_a = self.q_a_layernorm(self.q_a_proj(hidden_states))
|
| 112 |
q = self.q_b_proj(q_a).view(bsz, q_len, self.config.num_attention_heads, -1).transpose(1, 2)
|
| 113 |
q_nope, q_pe = q.split([self.config.qk_nope_head_dim, self.config.qk_rope_head_dim], dim=-1)
|
| 114 |
|
| 115 |
+
kv_a_raw = self.kv_a_proj_with_mqa(hidden_states)
|
| 116 |
kv_a, k_pe = kv_a_raw.split([self.config.kv_lora_rank, self.config.qk_rope_head_dim], dim=-1)
|
| 117 |
k_pe = k_pe.view(bsz, q_len, 1, -1).transpose(1, 2)
|
| 118 |
|
|
|
|
| 127 |
|
| 128 |
attn = (q @ k.transpose(-1, -2)) * (q.shape[-1]**-0.5)
|
| 129 |
if attention_mask is not None: attn += attention_mask
|
| 130 |
+
attn = F.softmax(attn, dim=-1, dtype=torch.float32).to(hidden_states.dtype)
|
| 131 |
out = (attn @ v).transpose(1, 2).reshape(bsz, q_len, -1)
|
| 132 |
return self.o_proj(out), None, None
|
| 133 |
|
|
|
|
| 137 |
self.config = config
|
| 138 |
self.layer_idx = layer_idx
|
| 139 |
|
| 140 |
+
# Layer 0 is Dense (18432 wide). Subsequent layers are Council-style.
|
|
|
|
|
|
|
| 141 |
if layer_idx == 0:
|
| 142 |
self.gate_proj = OmegaQuantLinear(config.hidden_size, 18432, bias=False)
|
| 143 |
self.up_proj = OmegaQuantLinear(config.hidden_size, 18432, bias=False)
|
|
|
|
| 149 |
"down_proj": OmegaQuantLinear(config.intermediate_size, config.hidden_size, bias=False)
|
| 150 |
})
|
| 151 |
self.wide_gate_up = OmegaQuantLinear(config.hidden_size, config.expert_intermediate * config.num_experts_per_layer * 2, bias=False)
|
|
|
|
|
|
|
|
|
|
| 152 |
self.expert_down_weights_packed = OmegaQuantLinear(config.num_experts_per_layer * config.expert_intermediate, config.hidden_size, bias=False)
|
| 153 |
self.register_buffer("importance", torch.ones(config.num_experts_per_layer))
|
| 154 |
|
| 155 |
def forward(self, x):
|
| 156 |
+
# Path 1: Dense SwiGLU (Layer 0)
|
| 157 |
+
if self.layer_idx == 0:
|
| 158 |
+
# SwiGLU: down(silu(gate(x)) * up(x))
|
| 159 |
+
gate = self.gate_proj(x)
|
| 160 |
+
up = self.up_proj(x)
|
| 161 |
+
return self.down_proj(F.silu(gate) * up)
|
| 162 |
+
|
| 163 |
+
# Path 2: Omega Consensus (Layer 1-60)
|
| 164 |
c_gate = self.chairman.gate_proj(x)
|
| 165 |
c_up = self.chairman.up_proj(x)
|
| 166 |
shared_out = self.chairman.down_proj(F.silu(c_gate) * c_up)
|
|
|
|
| 169 |
gate, up = wide_out.chunk(2, dim=-1)
|
| 170 |
lane_acts = F.silu(gate) * up
|
| 171 |
|
| 172 |
+
# Unpack 3D slab: [E*I, H] -> [E, I, H]
|
|
|
|
| 173 |
e_weights = self.expert_down_weights_packed._unpack().view(self.config.num_experts_per_layer, self.config.expert_intermediate, -1)
|
| 174 |
expert_outs = torch.einsum('bsei,eih->bseh', lane_acts, e_weights)
|
| 175 |
|
| 176 |
+
# FP32 Agreement Metric for governance stability
|
| 177 |
c_norm = torch.norm(shared_out, dim=-1, keepdim=True) + 1e-6
|
| 178 |
agreement = torch.einsum('bseh,bsh->bse', expert_outs.float(), shared_out.float()) / c_norm.float()
|
| 179 |
mask = torch.maximum(F.relu(agreement / self.config.tau).to(x.dtype),
|
|
|
|
| 183 |
return shared_out + council_out
|
| 184 |
|
| 185 |
# ============================================================
|
| 186 |
+
# 4. TOP LEVEL
|
| 187 |
# ============================================================
|
| 188 |
|
| 189 |
class OmegaDecoderLayer(nn.Module):
|
|
|
|
| 201 |
config_class = OmegaConfig
|
| 202 |
def __init__(self, config):
|
| 203 |
super().__init__(config)
|
|
|
|
| 204 |
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 205 |
self.layers = nn.ModuleList([OmegaDecoderLayer(config, i) for i in range(config.num_hidden_layers)])
|
| 206 |
self.norm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|