Upload all training checkpoint weights
Browse filesThis view is limited to 50 files because it contains too many changes. Β See raw diff
- bpe_vocab_16k.json +0 -0
- chck_100M/config.json +17 -0
- chck_100M/configuration_msit.py +35 -0
- chck_100M/modeling_msit.py +436 -0
- chck_100M/pytorch_model.bin +3 -0
- chck_100M/tokenizer.json +0 -0
- chck_100M/tokenizer_config.json +10 -0
- chck_10M/config.json +17 -0
- chck_10M/configuration_msit.py +35 -0
- chck_10M/modeling_msit.py +436 -0
- chck_10M/pytorch_model.bin +3 -0
- chck_10M/tokenizer.json +0 -0
- chck_10M/tokenizer_config.json +10 -0
- chck_1M/config.json +17 -0
- chck_1M/configuration_msit.py +35 -0
- chck_1M/modeling_msit.py +436 -0
- chck_1M/pytorch_model.bin +3 -0
- chck_1M/tokenizer.json +0 -0
- chck_1M/tokenizer_config.json +10 -0
- chck_20M/config.json +17 -0
- chck_20M/configuration_msit.py +35 -0
- chck_20M/modeling_msit.py +436 -0
- chck_20M/pytorch_model.bin +3 -0
- chck_20M/tokenizer.json +0 -0
- chck_20M/tokenizer_config.json +10 -0
- chck_2M/config.json +17 -0
- chck_2M/configuration_msit.py +35 -0
- chck_2M/modeling_msit.py +436 -0
- chck_2M/pytorch_model.bin +3 -0
- chck_2M/tokenizer.json +0 -0
- chck_2M/tokenizer_config.json +10 -0
- chck_30M/config.json +17 -0
- chck_30M/configuration_msit.py +35 -0
- chck_30M/modeling_msit.py +436 -0
- chck_30M/pytorch_model.bin +3 -0
- chck_30M/tokenizer.json +0 -0
- chck_30M/tokenizer_config.json +10 -0
- chck_3M/config.json +17 -0
- chck_3M/configuration_msit.py +35 -0
- chck_3M/modeling_msit.py +436 -0
- chck_3M/pytorch_model.bin +3 -0
- chck_3M/tokenizer.json +0 -0
- chck_3M/tokenizer_config.json +10 -0
- chck_40M/config.json +17 -0
- chck_40M/configuration_msit.py +35 -0
- chck_40M/modeling_msit.py +436 -0
- chck_40M/pytorch_model.bin +3 -0
- chck_40M/tokenizer.json +0 -0
- chck_40M/tokenizer_config.json +10 -0
- chck_4M/config.json +17 -0
bpe_vocab_16k.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
chck_100M/config.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"auto_map": {
|
| 3 |
+
"AutoConfig": "modeling_msit.MSITGPTBERTHFConfig",
|
| 4 |
+
"AutoModel": "modeling_msit.MSITGPTBERTModelWrapper",
|
| 5 |
+
"AutoModelForCausalLM": "modeling_msit.MSITGPTBERTForCausalLM"
|
| 6 |
+
},
|
| 7 |
+
"vocab_size": 16384,
|
| 8 |
+
"block_size": 512,
|
| 9 |
+
"d_model": 384,
|
| 10 |
+
"hidden_size": 384,
|
| 11 |
+
"d_thin": 192,
|
| 12 |
+
"num_layers": 6,
|
| 13 |
+
"num_blocks": 6,
|
| 14 |
+
"capacity_factor": 2.0,
|
| 15 |
+
"dropout": 0.1,
|
| 16 |
+
"model_type": "msit_gptbert"
|
| 17 |
+
}
|
chck_100M/configuration_msit.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
|
| 3 |
+
class MSITGPTBERTHFConfig(PretrainedConfig):
|
| 4 |
+
model_type = "msit_gptbert"
|
| 5 |
+
|
| 6 |
+
def __init__(
|
| 7 |
+
self,
|
| 8 |
+
vocab_size: int = 16384,
|
| 9 |
+
block_size: int = 512,
|
| 10 |
+
d_model: int = 384,
|
| 11 |
+
d_thin: int = 192,
|
| 12 |
+
num_layers: int = 6,
|
| 13 |
+
num_blocks: int = 6,
|
| 14 |
+
capacity_factor: float = 2.0,
|
| 15 |
+
dropout: float = 0.1,
|
| 16 |
+
**kwargs
|
| 17 |
+
):
|
| 18 |
+
kwargs.setdefault("is_decoder", True)
|
| 19 |
+
kwargs.setdefault("bos_token_id", 2) # [CLS]
|
| 20 |
+
kwargs.setdefault("eos_token_id", 3) # [SEP]
|
| 21 |
+
kwargs.setdefault("pad_token_id", 1) # [PAD]
|
| 22 |
+
|
| 23 |
+
self.vocab_size = vocab_size
|
| 24 |
+
self.block_size = block_size
|
| 25 |
+
self.d_model = d_model
|
| 26 |
+
self.d_thin = d_thin
|
| 27 |
+
self.num_layers = num_layers
|
| 28 |
+
self.num_blocks = num_blocks
|
| 29 |
+
self.capacity_factor = capacity_factor
|
| 30 |
+
self.dropout = dropout
|
| 31 |
+
|
| 32 |
+
# Attribute parity for classification heads
|
| 33 |
+
self.hidden_size = d_model
|
| 34 |
+
|
| 35 |
+
super().__init__(**kwargs)
|
chck_100M/modeling_msit.py
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import math
|
| 3 |
+
import random
|
| 4 |
+
import inspect
|
| 5 |
+
from typing import Optional, Tuple, Dict, Any
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
|
| 12 |
+
from transformers import PretrainedConfig, PreTrainedModel, GenerationMixin, AutoConfig, AutoModel, AutoModelForCausalLM
|
| 13 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 14 |
+
|
| 15 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 16 |
+
# Configuration Classes
|
| 17 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 18 |
+
|
| 19 |
+
@dataclass
|
| 20 |
+
class MSITGPTBERTConfig:
|
| 21 |
+
vocab_size: int = 16384
|
| 22 |
+
block_size: int = 512
|
| 23 |
+
d_model: int = 384
|
| 24 |
+
d_thin: int = 192
|
| 25 |
+
num_layers: int = 6
|
| 26 |
+
num_blocks: int = 6
|
| 27 |
+
capacity_factor: float = 2.0
|
| 28 |
+
dropout: float = 0.1
|
| 29 |
+
|
| 30 |
+
class MSITGPTBERTHFConfig(PretrainedConfig):
|
| 31 |
+
model_type = "msit_gptbert"
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self,
|
| 35 |
+
vocab_size: int = 16384,
|
| 36 |
+
block_size: int = 512,
|
| 37 |
+
d_model: int = 384,
|
| 38 |
+
d_thin: int = 192,
|
| 39 |
+
num_layers: int = 6,
|
| 40 |
+
num_blocks: int = 6,
|
| 41 |
+
capacity_factor: float = 2.0,
|
| 42 |
+
dropout: float = 0.1,
|
| 43 |
+
**kwargs
|
| 44 |
+
):
|
| 45 |
+
kwargs.setdefault("is_decoder", True)
|
| 46 |
+
kwargs.setdefault("bos_token_id", 2) # [CLS]
|
| 47 |
+
kwargs.setdefault("eos_token_id", 3) # [SEP]
|
| 48 |
+
kwargs.setdefault("pad_token_id", 1) # [PAD]
|
| 49 |
+
|
| 50 |
+
self.vocab_size = vocab_size
|
| 51 |
+
self.block_size = block_size
|
| 52 |
+
self.d_model = d_model
|
| 53 |
+
self.d_thin = d_thin
|
| 54 |
+
self.num_layers = num_layers
|
| 55 |
+
self.num_blocks = num_blocks
|
| 56 |
+
self.capacity_factor = capacity_factor
|
| 57 |
+
self.dropout = dropout
|
| 58 |
+
|
| 59 |
+
# Attribute parity for classification heads
|
| 60 |
+
self.hidden_size = d_model
|
| 61 |
+
|
| 62 |
+
super().__init__(**kwargs)
|
| 63 |
+
|
| 64 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 65 |
+
# ROPE HELPERS
|
| 66 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 67 |
+
|
| 68 |
+
def _precompute_rope_freqs(head_dim: int, seq_len: int, device: torch.device, theta: float = 10000.0):
|
| 69 |
+
assert head_dim % 2 == 0, "head_dim must be divisible by 2 for RoPE"
|
| 70 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim))
|
| 71 |
+
t = torch.arange(seq_len, device=device).float()
|
| 72 |
+
freqs = torch.outer(t, inv_freq)
|
| 73 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 74 |
+
return emb.cos(), emb.sin()
|
| 75 |
+
|
| 76 |
+
def _apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor):
|
| 77 |
+
L = x.size(2)
|
| 78 |
+
cos = cos[:L, :].unsqueeze(0).unsqueeze(1)
|
| 79 |
+
sin = sin[:L, :].unsqueeze(0).unsqueeze(1)
|
| 80 |
+
|
| 81 |
+
half_dim = x.size(-1) // 2
|
| 82 |
+
x1 = x[..., :half_dim]
|
| 83 |
+
x2 = x[..., half_dim:]
|
| 84 |
+
rotated_x = torch.cat((-x2, x1), dim=-1)
|
| 85 |
+
|
| 86 |
+
return (x * cos) + (rotated_x * sin)
|
| 87 |
+
|
| 88 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 89 |
+
# 1. SLIDING WINDOW ATTENTION
|
| 90 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 91 |
+
|
| 92 |
+
class SlidingWindowAttention(nn.Module):
|
| 93 |
+
def __init__(self, dim: int, num_heads: int, window_size=None):
|
| 94 |
+
super().__init__()
|
| 95 |
+
assert dim % num_heads == 0, "dim must be divisible by num_heads"
|
| 96 |
+
self.num_heads = num_heads
|
| 97 |
+
self.window_size = window_size
|
| 98 |
+
self.head_dim = dim // num_heads
|
| 99 |
+
|
| 100 |
+
self.q_proj = nn.Linear(dim, dim, bias=False)
|
| 101 |
+
self.k_proj = nn.Linear(dim, dim, bias=False)
|
| 102 |
+
self.v_proj = nn.Linear(dim, dim, bias=False)
|
| 103 |
+
self.o_proj = nn.Linear(dim, dim, bias=False)
|
| 104 |
+
|
| 105 |
+
def forward(self, x: torch.Tensor,
|
| 106 |
+
past_kv=None,
|
| 107 |
+
use_cache: bool = False,
|
| 108 |
+
bidirectional: bool = False):
|
| 109 |
+
B, L, D = x.size()
|
| 110 |
+
|
| 111 |
+
q = self.q_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 112 |
+
k = self.k_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 113 |
+
v = self.v_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 114 |
+
|
| 115 |
+
if past_kv is not None:
|
| 116 |
+
past_k, past_v = past_kv
|
| 117 |
+
past_len = past_k.size(2)
|
| 118 |
+
q_cos, q_sin = _precompute_rope_freqs(self.head_dim, past_len + L, x.device)
|
| 119 |
+
q = _apply_rope(q, q_cos[past_len:, :], q_sin[past_len:, :])
|
| 120 |
+
k = _apply_rope(k, q_cos[past_len:, :], q_sin[past_len:, :])
|
| 121 |
+
|
| 122 |
+
k = torch.cat([past_k, k], dim=2)
|
| 123 |
+
v = torch.cat([past_v, v], dim=2)
|
| 124 |
+
else:
|
| 125 |
+
cos, sin = _precompute_rope_freqs(self.head_dim, L, x.device)
|
| 126 |
+
q = _apply_rope(q, cos, sin)
|
| 127 |
+
k = _apply_rope(k, cos, sin)
|
| 128 |
+
|
| 129 |
+
L_kv = k.size(2)
|
| 130 |
+
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
|
| 131 |
+
|
| 132 |
+
if bidirectional:
|
| 133 |
+
if self.window_size is not None:
|
| 134 |
+
past_len = L_kv - L
|
| 135 |
+
pos_i = (past_len + torch.arange(L, device=x.device)).unsqueeze(1)
|
| 136 |
+
pos_j = torch.arange(L_kv, device=x.device).unsqueeze(0)
|
| 137 |
+
dist = torch.abs(pos_i - pos_j)
|
| 138 |
+
win_mask = dist < self.window_size
|
| 139 |
+
scores = scores.masked_fill(
|
| 140 |
+
~win_mask.unsqueeze(0).unsqueeze(0), float('-inf')
|
| 141 |
+
)
|
| 142 |
+
else:
|
| 143 |
+
past_len = L_kv - L
|
| 144 |
+
pos_i = (past_len + torch.arange(L, device=x.device)).unsqueeze(1)
|
| 145 |
+
pos_j = torch.arange(L_kv, device=x.device).unsqueeze(0)
|
| 146 |
+
dist = pos_i - pos_j
|
| 147 |
+
|
| 148 |
+
causal_mask = dist >= 0
|
| 149 |
+
if self.window_size is not None:
|
| 150 |
+
causal_mask = causal_mask & (dist < self.window_size)
|
| 151 |
+
|
| 152 |
+
scores = scores.masked_fill(
|
| 153 |
+
~causal_mask.unsqueeze(0).unsqueeze(0), float('-inf')
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
attn = torch.softmax(scores, dim=-1)
|
| 157 |
+
out = torch.matmul(attn, v)
|
| 158 |
+
out = out.transpose(1, 2).contiguous().view(B, L, D)
|
| 159 |
+
out = self.o_proj(out)
|
| 160 |
+
|
| 161 |
+
if use_cache:
|
| 162 |
+
if self.window_size is not None:
|
| 163 |
+
present_kv = (
|
| 164 |
+
k[:, :, -self.window_size:, :],
|
| 165 |
+
v[:, :, -self.window_size:, :]
|
| 166 |
+
)
|
| 167 |
+
else:
|
| 168 |
+
present_kv = (k, v)
|
| 169 |
+
else:
|
| 170 |
+
present_kv = None
|
| 171 |
+
|
| 172 |
+
return out, present_kv
|
| 173 |
+
|
| 174 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 175 |
+
# 2. MSIT BRANCH BLOCK (Pre-Norm)
|
| 176 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 177 |
+
|
| 178 |
+
class MSITBranchBlock(nn.Module):
|
| 179 |
+
def __init__(self, dim: int, num_heads: int, window_size):
|
| 180 |
+
super().__init__()
|
| 181 |
+
self.ln1 = nn.LayerNorm(dim)
|
| 182 |
+
self.attn = SlidingWindowAttention(dim, num_heads, window_size)
|
| 183 |
+
self.ln2 = nn.LayerNorm(dim)
|
| 184 |
+
self.ffn = nn.Sequential(
|
| 185 |
+
nn.Linear(dim, dim * 4, bias=False),
|
| 186 |
+
nn.GELU(),
|
| 187 |
+
nn.Linear(dim * 4, dim, bias=False),
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
def forward(self, x: torch.Tensor,
|
| 191 |
+
past_kv=None,
|
| 192 |
+
use_cache: bool = False,
|
| 193 |
+
bidirectional: bool = False):
|
| 194 |
+
attn_out, present_kv = self.attn(
|
| 195 |
+
self.ln1(x), past_kv, use_cache, bidirectional
|
| 196 |
+
)
|
| 197 |
+
x = x + attn_out
|
| 198 |
+
x = x + self.ffn(self.ln2(x))
|
| 199 |
+
return x, present_kv
|
| 200 |
+
|
| 201 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 202 |
+
# 3. MoEP-MSIT ARCHITECTURE BLOCK (Expert Choice routing)
|
| 203 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 204 |
+
|
| 205 |
+
class MoEPMSITBlock(nn.Module):
|
| 206 |
+
def __init__(self, d_model: int = 512, d_thin: int = 192, num_blocks: int = 14,
|
| 207 |
+
capacity_factor: float = 2.0):
|
| 208 |
+
super().__init__()
|
| 209 |
+
self.d_model = d_model
|
| 210 |
+
self.d_thin = d_thin
|
| 211 |
+
self.num_blocks = num_blocks
|
| 212 |
+
self.capacity_factor = capacity_factor
|
| 213 |
+
|
| 214 |
+
# 1. Global Block (Dense, d_model)
|
| 215 |
+
num_heads_global = max(1, d_model // 64)
|
| 216 |
+
self.global_block = MSITBranchBlock(d_model, num_heads_global, window_size=None)
|
| 217 |
+
|
| 218 |
+
# 2. Router
|
| 219 |
+
self.router_ln = nn.LayerNorm(d_model)
|
| 220 |
+
self.w_router = nn.Linear(d_model, num_blocks, bias=False)
|
| 221 |
+
|
| 222 |
+
# 3. Shrink Projection
|
| 223 |
+
self.w_down = nn.Linear(d_model, d_thin, bias=False)
|
| 224 |
+
|
| 225 |
+
# 4. Thin Parallel Blocks (d_thin)
|
| 226 |
+
self.windows = [None, 16, 8, 4, 2] + [None] * (num_blocks - 5)
|
| 227 |
+
self.heads = [max(1, d_thin // 64)] * num_blocks
|
| 228 |
+
|
| 229 |
+
self.thin_blocks = nn.ModuleList([
|
| 230 |
+
MSITBranchBlock(d_thin, self.heads[i], self.windows[i])
|
| 231 |
+
for i in range(num_blocks)
|
| 232 |
+
])
|
| 233 |
+
|
| 234 |
+
# 6. Grow Projection
|
| 235 |
+
self.w_up = nn.Linear(d_thin, d_model, bias=False)
|
| 236 |
+
self.last_topk_indices = None
|
| 237 |
+
|
| 238 |
+
def forward(self, x_0: torch.Tensor, past_kvs=None, use_cache: bool = False, bidirectional: bool = False):
|
| 239 |
+
B, T, D = x_0.size()
|
| 240 |
+
n_tokens = B * T
|
| 241 |
+
|
| 242 |
+
# Step 1: Global Block
|
| 243 |
+
pkv_g = past_kvs[0] if past_kvs else None
|
| 244 |
+
x_1, nkv_g = self.global_block(x_0, pkv_g, use_cache, bidirectional)
|
| 245 |
+
|
| 246 |
+
# Step 2: Gated input stream
|
| 247 |
+
x_2 = x_1 + x_0
|
| 248 |
+
|
| 249 |
+
# Router scores
|
| 250 |
+
r_logits = self.w_router(self.router_ln(x_2)).view(n_tokens, self.num_blocks)
|
| 251 |
+
r_probs = F.softmax(r_logits, dim=-1)
|
| 252 |
+
|
| 253 |
+
# Per-expert capacity: k = (n * c) / e
|
| 254 |
+
k_capacity = max(1, int(round(n_tokens * self.capacity_factor / self.num_blocks)))
|
| 255 |
+
k_capacity = min(k_capacity, n_tokens)
|
| 256 |
+
|
| 257 |
+
# Expert Choice routing: topk over the token axis for each expert
|
| 258 |
+
expert_token_scores = r_probs.transpose(0, 1) # (num_blocks, n_tokens)
|
| 259 |
+
topk_scores, topk_token_idx = torch.topk(expert_token_scores, k_capacity, dim=-1)
|
| 260 |
+
self.last_topk_indices = topk_token_idx
|
| 261 |
+
|
| 262 |
+
# Load balancing is guaranteed by construction in Expert Choice
|
| 263 |
+
layer_aux_loss = x_2.new_zeros(())
|
| 264 |
+
|
| 265 |
+
# Shrink projection
|
| 266 |
+
x_2_thin = self.w_down(x_2) # (B, T, d_thin)
|
| 267 |
+
x_2_thin_flat = x_2_thin.view(n_tokens, self.d_thin)
|
| 268 |
+
|
| 269 |
+
# Expert computations
|
| 270 |
+
new_kvs = [nkv_g]
|
| 271 |
+
expert_outputs_flat = torch.zeros(n_tokens, self.d_model, device=x_2.device, dtype=x_2.dtype)
|
| 272 |
+
|
| 273 |
+
for i, block in enumerate(self.thin_blocks):
|
| 274 |
+
sel_idx = topk_token_idx[i]
|
| 275 |
+
bucket_in = x_2_thin_flat[sel_idx].unsqueeze(0) # (1, k_capacity, d_thin)
|
| 276 |
+
|
| 277 |
+
pkv_i = past_kvs[i + 1] if past_kvs else None
|
| 278 |
+
bucket_out, nkv_i = block(bucket_in, pkv_i, use_cache, bidirectional)
|
| 279 |
+
if use_cache:
|
| 280 |
+
new_kvs.append(nkv_i)
|
| 281 |
+
|
| 282 |
+
bucket_out = bucket_out.squeeze(0) # (k_capacity, d_thin)
|
| 283 |
+
bucket_out_full = self.w_up(bucket_out) # (k_capacity, d_model)
|
| 284 |
+
|
| 285 |
+
gate = topk_scores[i].unsqueeze(-1) # (k_capacity, 1)
|
| 286 |
+
expert_outputs_flat.index_add_(0, sel_idx, bucket_out_full * gate)
|
| 287 |
+
|
| 288 |
+
x_3_full = expert_outputs_flat.view(B, T, self.d_model)
|
| 289 |
+
out = x_2 + x_3_full
|
| 290 |
+
|
| 291 |
+
present_kvs = tuple(new_kvs) if use_cache else None
|
| 292 |
+
return out, present_kvs, layer_aux_loss
|
| 293 |
+
|
| 294 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 295 |
+
# 4. RAW MSIT-GPT-BERT MODEL
|
| 296 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 297 |
+
|
| 298 |
+
class MSITGPTBERTModel(nn.Module):
|
| 299 |
+
def __init__(self, cfg):
|
| 300 |
+
super().__init__()
|
| 301 |
+
self.cfg = cfg
|
| 302 |
+
self.wte = nn.Embedding(cfg.vocab_size, cfg.d_model)
|
| 303 |
+
self.drop_emb = nn.Dropout(cfg.dropout)
|
| 304 |
+
self.blocks = nn.ModuleList([
|
| 305 |
+
MoEPMSITBlock(
|
| 306 |
+
d_model=cfg.d_model,
|
| 307 |
+
d_thin=cfg.d_thin,
|
| 308 |
+
num_blocks=cfg.num_blocks,
|
| 309 |
+
capacity_factor=cfg.capacity_factor
|
| 310 |
+
)
|
| 311 |
+
for _ in range(cfg.num_layers)
|
| 312 |
+
])
|
| 313 |
+
self.ln_f = nn.LayerNorm(cfg.d_model)
|
| 314 |
+
self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
|
| 315 |
+
self.wte.weight = self.lm_head.weight
|
| 316 |
+
|
| 317 |
+
def forward(self, input_ids: torch.Tensor, targets: torch.Tensor = None, bidirectional: bool = False):
|
| 318 |
+
x = self.drop_emb(self.wte(input_ids))
|
| 319 |
+
total_aux_loss = 0.0
|
| 320 |
+
|
| 321 |
+
for block in self.blocks:
|
| 322 |
+
x, _, layer_aux = block(x, past_kvs=None, use_cache=False, bidirectional=bidirectional)
|
| 323 |
+
total_aux_loss += layer_aux
|
| 324 |
+
|
| 325 |
+
x = self.ln_f(x)
|
| 326 |
+
logits = self.lm_head(x)
|
| 327 |
+
|
| 328 |
+
loss = None
|
| 329 |
+
if targets is not None:
|
| 330 |
+
ce_loss = F.cross_entropy(logits.view(-1, self.cfg.vocab_size), targets.view(-1), ignore_index=-100)
|
| 331 |
+
avg_aux_loss = total_aux_loss / self.cfg.num_layers
|
| 332 |
+
loss = ce_loss + (0.01 * avg_aux_loss)
|
| 333 |
+
|
| 334 |
+
return logits, loss
|
| 335 |
+
|
| 336 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 337 |
+
# 5. HUGGING FACE MODEL WRAPPERS
|
| 338 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 339 |
+
|
| 340 |
+
class MSITGPTBERTModelWrapper(PreTrainedModel):
|
| 341 |
+
config_class = MSITGPTBERTHFConfig
|
| 342 |
+
base_model_prefix = "transformer"
|
| 343 |
+
|
| 344 |
+
def __init__(self, config: MSITGPTBERTHFConfig):
|
| 345 |
+
super().__init__(config)
|
| 346 |
+
self.wte = nn.Embedding(config.vocab_size, config.d_model)
|
| 347 |
+
self.drop_emb = nn.Dropout(config.dropout)
|
| 348 |
+
self.blocks = nn.ModuleList([
|
| 349 |
+
MoEPMSITBlock(config.d_model, config.d_thin, config.num_blocks, config.capacity_factor)
|
| 350 |
+
for _ in range(config.num_layers)
|
| 351 |
+
])
|
| 352 |
+
self.ln_f = nn.LayerNorm(config.d_model)
|
| 353 |
+
self.post_init()
|
| 354 |
+
|
| 355 |
+
def forward(self, input_ids, **kwargs):
|
| 356 |
+
x = self.drop_emb(self.wte(input_ids))
|
| 357 |
+
for block in self.blocks:
|
| 358 |
+
x, _, _ = block(x, past_kvs=None, use_cache=False, bidirectional=False)
|
| 359 |
+
x = self.ln_f(x)
|
| 360 |
+
return BaseModelOutputWithPast(last_hidden_state=x)
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
class MSITGPTBERTForCausalLM(PreTrainedModel, GenerationMixin):
|
| 364 |
+
config_class = MSITGPTBERTHFConfig
|
| 365 |
+
base_model_prefix = "transformer"
|
| 366 |
+
_no_split_modules = ["MoEPMSITBlock"]
|
| 367 |
+
_tied_weights_keys = {"transformer.lm_head.weight": "transformer.wte.weight"}
|
| 368 |
+
|
| 369 |
+
def __init__(self, config: MSITGPTBERTHFConfig):
|
| 370 |
+
super().__init__(config)
|
| 371 |
+
self.transformer = MSITGPTBERTModelWrapper(config)
|
| 372 |
+
self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
|
| 373 |
+
self.post_init()
|
| 374 |
+
|
| 375 |
+
# State-dict pre-hook for backwards compatibility with checkpoint key naming
|
| 376 |
+
def _prefix_cleaner(state_dict, prefix, local_metadata, Moore, missing_keys, unexpected_keys, error_msgs):
|
| 377 |
+
keys = list(state_dict.keys())
|
| 378 |
+
for k in keys:
|
| 379 |
+
if k.startswith("transformer."):
|
| 380 |
+
state_dict[k.replace("transformer.", "", 1)] = state_dict.pop(k)
|
| 381 |
+
elif f"{prefix}transformer." in k:
|
| 382 |
+
state_dict[k.replace("transformer.", "", 1)] = state_dict.pop(k)
|
| 383 |
+
|
| 384 |
+
self._register_load_state_dict_pre_hook(_prefix_cleaner)
|
| 385 |
+
|
| 386 |
+
def tie_weights(self, **kwargs):
|
| 387 |
+
if hasattr(self, "transformer") and hasattr(self.transformer, "wte") and hasattr(self.transformer, "lm_head"):
|
| 388 |
+
self.transformer.wte.weight = self.lm_head.weight
|
| 389 |
+
|
| 390 |
+
def get_input_embeddings(self):
|
| 391 |
+
return self.transformer.wte
|
| 392 |
+
|
| 393 |
+
def set_input_embeddings(self, new_embeddings):
|
| 394 |
+
self.transformer.wte = new_embeddings
|
| 395 |
+
|
| 396 |
+
def get_output_embeddings(self):
|
| 397 |
+
return self.lm_head
|
| 398 |
+
|
| 399 |
+
def set_output_embeddings(self, new_embeddings):
|
| 400 |
+
self.lm_head = new_embeddings
|
| 401 |
+
|
| 402 |
+
def forward(self,
|
| 403 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 404 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 405 |
+
labels: Optional[torch.LongTensor] = None,
|
| 406 |
+
**kwargs) -> CausalLMOutputWithPast:
|
| 407 |
+
outputs = self.transformer(input_ids)
|
| 408 |
+
hidden_states = outputs.last_hidden_state
|
| 409 |
+
logits = self.lm_head(hidden_states)
|
| 410 |
+
|
| 411 |
+
loss = None
|
| 412 |
+
if labels is not None:
|
| 413 |
+
shift_logits = logits[:, :-1, :].contiguous()
|
| 414 |
+
shift_labels = labels[:, 1:].contiguous()
|
| 415 |
+
loss = F.cross_entropy(
|
| 416 |
+
shift_logits.view(-1, self.config.vocab_size),
|
| 417 |
+
shift_labels.view(-1),
|
| 418 |
+
ignore_index=-100
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
return CausalLMOutputWithPast(
|
| 422 |
+
loss=loss,
|
| 423 |
+
logits=logits,
|
| 424 |
+
past_key_values=None,
|
| 425 |
+
hidden_states=None,
|
| 426 |
+
attentions=None,
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
def prepare_inputs_for_generation(self, input_ids, **kwargs):
|
| 430 |
+
return {"input_ids": input_ids}
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
# Register with auto-mapping
|
| 434 |
+
AutoConfig.register("msit_gptbert", MSITGPTBERTHFConfig)
|
| 435 |
+
AutoModel.register(MSITGPTBERTHFConfig, MSITGPTBERTModelWrapper)
|
| 436 |
+
AutoModelForCausalLM.register(MSITGPTBERTHFConfig, MSITGPTBERTForCausalLM)
|
chck_100M/pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d452c57bd38f27f6e4eece4f4fba3827991505fa19abe9818071f0cd94467e50
|
| 3 |
+
size 135253367
|
chck_100M/tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
chck_100M/tokenizer_config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "tokenizers",
|
| 3 |
+
"bos_token": "[CLS]",
|
| 4 |
+
"eos_token": "[SEP]",
|
| 5 |
+
"mask_token": "[MASK]",
|
| 6 |
+
"model_max_length": 1000000000000000019884624838656,
|
| 7 |
+
"pad_token": "[PAD]",
|
| 8 |
+
"tokenizer_class": "TokenizersBackend",
|
| 9 |
+
"unk_token": "[UNK]"
|
| 10 |
+
}
|
chck_10M/config.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"auto_map": {
|
| 3 |
+
"AutoConfig": "modeling_msit.MSITGPTBERTHFConfig",
|
| 4 |
+
"AutoModel": "modeling_msit.MSITGPTBERTModelWrapper",
|
| 5 |
+
"AutoModelForCausalLM": "modeling_msit.MSITGPTBERTForCausalLM"
|
| 6 |
+
},
|
| 7 |
+
"vocab_size": 16384,
|
| 8 |
+
"block_size": 512,
|
| 9 |
+
"d_model": 384,
|
| 10 |
+
"hidden_size": 384,
|
| 11 |
+
"d_thin": 192,
|
| 12 |
+
"num_layers": 6,
|
| 13 |
+
"num_blocks": 6,
|
| 14 |
+
"capacity_factor": 2.0,
|
| 15 |
+
"dropout": 0.1,
|
| 16 |
+
"model_type": "msit_gptbert"
|
| 17 |
+
}
|
chck_10M/configuration_msit.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
|
| 3 |
+
class MSITGPTBERTHFConfig(PretrainedConfig):
|
| 4 |
+
model_type = "msit_gptbert"
|
| 5 |
+
|
| 6 |
+
def __init__(
|
| 7 |
+
self,
|
| 8 |
+
vocab_size: int = 16384,
|
| 9 |
+
block_size: int = 512,
|
| 10 |
+
d_model: int = 384,
|
| 11 |
+
d_thin: int = 192,
|
| 12 |
+
num_layers: int = 6,
|
| 13 |
+
num_blocks: int = 6,
|
| 14 |
+
capacity_factor: float = 2.0,
|
| 15 |
+
dropout: float = 0.1,
|
| 16 |
+
**kwargs
|
| 17 |
+
):
|
| 18 |
+
kwargs.setdefault("is_decoder", True)
|
| 19 |
+
kwargs.setdefault("bos_token_id", 2) # [CLS]
|
| 20 |
+
kwargs.setdefault("eos_token_id", 3) # [SEP]
|
| 21 |
+
kwargs.setdefault("pad_token_id", 1) # [PAD]
|
| 22 |
+
|
| 23 |
+
self.vocab_size = vocab_size
|
| 24 |
+
self.block_size = block_size
|
| 25 |
+
self.d_model = d_model
|
| 26 |
+
self.d_thin = d_thin
|
| 27 |
+
self.num_layers = num_layers
|
| 28 |
+
self.num_blocks = num_blocks
|
| 29 |
+
self.capacity_factor = capacity_factor
|
| 30 |
+
self.dropout = dropout
|
| 31 |
+
|
| 32 |
+
# Attribute parity for classification heads
|
| 33 |
+
self.hidden_size = d_model
|
| 34 |
+
|
| 35 |
+
super().__init__(**kwargs)
|
chck_10M/modeling_msit.py
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import math
|
| 3 |
+
import random
|
| 4 |
+
import inspect
|
| 5 |
+
from typing import Optional, Tuple, Dict, Any
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
|
| 12 |
+
from transformers import PretrainedConfig, PreTrainedModel, GenerationMixin, AutoConfig, AutoModel, AutoModelForCausalLM
|
| 13 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 14 |
+
|
| 15 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 16 |
+
# Configuration Classes
|
| 17 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 18 |
+
|
| 19 |
+
@dataclass
|
| 20 |
+
class MSITGPTBERTConfig:
|
| 21 |
+
vocab_size: int = 16384
|
| 22 |
+
block_size: int = 512
|
| 23 |
+
d_model: int = 384
|
| 24 |
+
d_thin: int = 192
|
| 25 |
+
num_layers: int = 6
|
| 26 |
+
num_blocks: int = 6
|
| 27 |
+
capacity_factor: float = 2.0
|
| 28 |
+
dropout: float = 0.1
|
| 29 |
+
|
| 30 |
+
class MSITGPTBERTHFConfig(PretrainedConfig):
|
| 31 |
+
model_type = "msit_gptbert"
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self,
|
| 35 |
+
vocab_size: int = 16384,
|
| 36 |
+
block_size: int = 512,
|
| 37 |
+
d_model: int = 384,
|
| 38 |
+
d_thin: int = 192,
|
| 39 |
+
num_layers: int = 6,
|
| 40 |
+
num_blocks: int = 6,
|
| 41 |
+
capacity_factor: float = 2.0,
|
| 42 |
+
dropout: float = 0.1,
|
| 43 |
+
**kwargs
|
| 44 |
+
):
|
| 45 |
+
kwargs.setdefault("is_decoder", True)
|
| 46 |
+
kwargs.setdefault("bos_token_id", 2) # [CLS]
|
| 47 |
+
kwargs.setdefault("eos_token_id", 3) # [SEP]
|
| 48 |
+
kwargs.setdefault("pad_token_id", 1) # [PAD]
|
| 49 |
+
|
| 50 |
+
self.vocab_size = vocab_size
|
| 51 |
+
self.block_size = block_size
|
| 52 |
+
self.d_model = d_model
|
| 53 |
+
self.d_thin = d_thin
|
| 54 |
+
self.num_layers = num_layers
|
| 55 |
+
self.num_blocks = num_blocks
|
| 56 |
+
self.capacity_factor = capacity_factor
|
| 57 |
+
self.dropout = dropout
|
| 58 |
+
|
| 59 |
+
# Attribute parity for classification heads
|
| 60 |
+
self.hidden_size = d_model
|
| 61 |
+
|
| 62 |
+
super().__init__(**kwargs)
|
| 63 |
+
|
| 64 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 65 |
+
# ROPE HELPERS
|
| 66 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 67 |
+
|
| 68 |
+
def _precompute_rope_freqs(head_dim: int, seq_len: int, device: torch.device, theta: float = 10000.0):
|
| 69 |
+
assert head_dim % 2 == 0, "head_dim must be divisible by 2 for RoPE"
|
| 70 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim))
|
| 71 |
+
t = torch.arange(seq_len, device=device).float()
|
| 72 |
+
freqs = torch.outer(t, inv_freq)
|
| 73 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 74 |
+
return emb.cos(), emb.sin()
|
| 75 |
+
|
| 76 |
+
def _apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor):
|
| 77 |
+
L = x.size(2)
|
| 78 |
+
cos = cos[:L, :].unsqueeze(0).unsqueeze(1)
|
| 79 |
+
sin = sin[:L, :].unsqueeze(0).unsqueeze(1)
|
| 80 |
+
|
| 81 |
+
half_dim = x.size(-1) // 2
|
| 82 |
+
x1 = x[..., :half_dim]
|
| 83 |
+
x2 = x[..., half_dim:]
|
| 84 |
+
rotated_x = torch.cat((-x2, x1), dim=-1)
|
| 85 |
+
|
| 86 |
+
return (x * cos) + (rotated_x * sin)
|
| 87 |
+
|
| 88 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 89 |
+
# 1. SLIDING WINDOW ATTENTION
|
| 90 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 91 |
+
|
| 92 |
+
class SlidingWindowAttention(nn.Module):
|
| 93 |
+
def __init__(self, dim: int, num_heads: int, window_size=None):
|
| 94 |
+
super().__init__()
|
| 95 |
+
assert dim % num_heads == 0, "dim must be divisible by num_heads"
|
| 96 |
+
self.num_heads = num_heads
|
| 97 |
+
self.window_size = window_size
|
| 98 |
+
self.head_dim = dim // num_heads
|
| 99 |
+
|
| 100 |
+
self.q_proj = nn.Linear(dim, dim, bias=False)
|
| 101 |
+
self.k_proj = nn.Linear(dim, dim, bias=False)
|
| 102 |
+
self.v_proj = nn.Linear(dim, dim, bias=False)
|
| 103 |
+
self.o_proj = nn.Linear(dim, dim, bias=False)
|
| 104 |
+
|
| 105 |
+
def forward(self, x: torch.Tensor,
|
| 106 |
+
past_kv=None,
|
| 107 |
+
use_cache: bool = False,
|
| 108 |
+
bidirectional: bool = False):
|
| 109 |
+
B, L, D = x.size()
|
| 110 |
+
|
| 111 |
+
q = self.q_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 112 |
+
k = self.k_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 113 |
+
v = self.v_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 114 |
+
|
| 115 |
+
if past_kv is not None:
|
| 116 |
+
past_k, past_v = past_kv
|
| 117 |
+
past_len = past_k.size(2)
|
| 118 |
+
q_cos, q_sin = _precompute_rope_freqs(self.head_dim, past_len + L, x.device)
|
| 119 |
+
q = _apply_rope(q, q_cos[past_len:, :], q_sin[past_len:, :])
|
| 120 |
+
k = _apply_rope(k, q_cos[past_len:, :], q_sin[past_len:, :])
|
| 121 |
+
|
| 122 |
+
k = torch.cat([past_k, k], dim=2)
|
| 123 |
+
v = torch.cat([past_v, v], dim=2)
|
| 124 |
+
else:
|
| 125 |
+
cos, sin = _precompute_rope_freqs(self.head_dim, L, x.device)
|
| 126 |
+
q = _apply_rope(q, cos, sin)
|
| 127 |
+
k = _apply_rope(k, cos, sin)
|
| 128 |
+
|
| 129 |
+
L_kv = k.size(2)
|
| 130 |
+
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
|
| 131 |
+
|
| 132 |
+
if bidirectional:
|
| 133 |
+
if self.window_size is not None:
|
| 134 |
+
past_len = L_kv - L
|
| 135 |
+
pos_i = (past_len + torch.arange(L, device=x.device)).unsqueeze(1)
|
| 136 |
+
pos_j = torch.arange(L_kv, device=x.device).unsqueeze(0)
|
| 137 |
+
dist = torch.abs(pos_i - pos_j)
|
| 138 |
+
win_mask = dist < self.window_size
|
| 139 |
+
scores = scores.masked_fill(
|
| 140 |
+
~win_mask.unsqueeze(0).unsqueeze(0), float('-inf')
|
| 141 |
+
)
|
| 142 |
+
else:
|
| 143 |
+
past_len = L_kv - L
|
| 144 |
+
pos_i = (past_len + torch.arange(L, device=x.device)).unsqueeze(1)
|
| 145 |
+
pos_j = torch.arange(L_kv, device=x.device).unsqueeze(0)
|
| 146 |
+
dist = pos_i - pos_j
|
| 147 |
+
|
| 148 |
+
causal_mask = dist >= 0
|
| 149 |
+
if self.window_size is not None:
|
| 150 |
+
causal_mask = causal_mask & (dist < self.window_size)
|
| 151 |
+
|
| 152 |
+
scores = scores.masked_fill(
|
| 153 |
+
~causal_mask.unsqueeze(0).unsqueeze(0), float('-inf')
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
attn = torch.softmax(scores, dim=-1)
|
| 157 |
+
out = torch.matmul(attn, v)
|
| 158 |
+
out = out.transpose(1, 2).contiguous().view(B, L, D)
|
| 159 |
+
out = self.o_proj(out)
|
| 160 |
+
|
| 161 |
+
if use_cache:
|
| 162 |
+
if self.window_size is not None:
|
| 163 |
+
present_kv = (
|
| 164 |
+
k[:, :, -self.window_size:, :],
|
| 165 |
+
v[:, :, -self.window_size:, :]
|
| 166 |
+
)
|
| 167 |
+
else:
|
| 168 |
+
present_kv = (k, v)
|
| 169 |
+
else:
|
| 170 |
+
present_kv = None
|
| 171 |
+
|
| 172 |
+
return out, present_kv
|
| 173 |
+
|
| 174 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 175 |
+
# 2. MSIT BRANCH BLOCK (Pre-Norm)
|
| 176 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 177 |
+
|
| 178 |
+
class MSITBranchBlock(nn.Module):
|
| 179 |
+
def __init__(self, dim: int, num_heads: int, window_size):
|
| 180 |
+
super().__init__()
|
| 181 |
+
self.ln1 = nn.LayerNorm(dim)
|
| 182 |
+
self.attn = SlidingWindowAttention(dim, num_heads, window_size)
|
| 183 |
+
self.ln2 = nn.LayerNorm(dim)
|
| 184 |
+
self.ffn = nn.Sequential(
|
| 185 |
+
nn.Linear(dim, dim * 4, bias=False),
|
| 186 |
+
nn.GELU(),
|
| 187 |
+
nn.Linear(dim * 4, dim, bias=False),
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
def forward(self, x: torch.Tensor,
|
| 191 |
+
past_kv=None,
|
| 192 |
+
use_cache: bool = False,
|
| 193 |
+
bidirectional: bool = False):
|
| 194 |
+
attn_out, present_kv = self.attn(
|
| 195 |
+
self.ln1(x), past_kv, use_cache, bidirectional
|
| 196 |
+
)
|
| 197 |
+
x = x + attn_out
|
| 198 |
+
x = x + self.ffn(self.ln2(x))
|
| 199 |
+
return x, present_kv
|
| 200 |
+
|
| 201 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 202 |
+
# 3. MoEP-MSIT ARCHITECTURE BLOCK (Expert Choice routing)
|
| 203 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 204 |
+
|
| 205 |
+
class MoEPMSITBlock(nn.Module):
|
| 206 |
+
def __init__(self, d_model: int = 512, d_thin: int = 192, num_blocks: int = 14,
|
| 207 |
+
capacity_factor: float = 2.0):
|
| 208 |
+
super().__init__()
|
| 209 |
+
self.d_model = d_model
|
| 210 |
+
self.d_thin = d_thin
|
| 211 |
+
self.num_blocks = num_blocks
|
| 212 |
+
self.capacity_factor = capacity_factor
|
| 213 |
+
|
| 214 |
+
# 1. Global Block (Dense, d_model)
|
| 215 |
+
num_heads_global = max(1, d_model // 64)
|
| 216 |
+
self.global_block = MSITBranchBlock(d_model, num_heads_global, window_size=None)
|
| 217 |
+
|
| 218 |
+
# 2. Router
|
| 219 |
+
self.router_ln = nn.LayerNorm(d_model)
|
| 220 |
+
self.w_router = nn.Linear(d_model, num_blocks, bias=False)
|
| 221 |
+
|
| 222 |
+
# 3. Shrink Projection
|
| 223 |
+
self.w_down = nn.Linear(d_model, d_thin, bias=False)
|
| 224 |
+
|
| 225 |
+
# 4. Thin Parallel Blocks (d_thin)
|
| 226 |
+
self.windows = [None, 16, 8, 4, 2] + [None] * (num_blocks - 5)
|
| 227 |
+
self.heads = [max(1, d_thin // 64)] * num_blocks
|
| 228 |
+
|
| 229 |
+
self.thin_blocks = nn.ModuleList([
|
| 230 |
+
MSITBranchBlock(d_thin, self.heads[i], self.windows[i])
|
| 231 |
+
for i in range(num_blocks)
|
| 232 |
+
])
|
| 233 |
+
|
| 234 |
+
# 6. Grow Projection
|
| 235 |
+
self.w_up = nn.Linear(d_thin, d_model, bias=False)
|
| 236 |
+
self.last_topk_indices = None
|
| 237 |
+
|
| 238 |
+
def forward(self, x_0: torch.Tensor, past_kvs=None, use_cache: bool = False, bidirectional: bool = False):
|
| 239 |
+
B, T, D = x_0.size()
|
| 240 |
+
n_tokens = B * T
|
| 241 |
+
|
| 242 |
+
# Step 1: Global Block
|
| 243 |
+
pkv_g = past_kvs[0] if past_kvs else None
|
| 244 |
+
x_1, nkv_g = self.global_block(x_0, pkv_g, use_cache, bidirectional)
|
| 245 |
+
|
| 246 |
+
# Step 2: Gated input stream
|
| 247 |
+
x_2 = x_1 + x_0
|
| 248 |
+
|
| 249 |
+
# Router scores
|
| 250 |
+
r_logits = self.w_router(self.router_ln(x_2)).view(n_tokens, self.num_blocks)
|
| 251 |
+
r_probs = F.softmax(r_logits, dim=-1)
|
| 252 |
+
|
| 253 |
+
# Per-expert capacity: k = (n * c) / e
|
| 254 |
+
k_capacity = max(1, int(round(n_tokens * self.capacity_factor / self.num_blocks)))
|
| 255 |
+
k_capacity = min(k_capacity, n_tokens)
|
| 256 |
+
|
| 257 |
+
# Expert Choice routing: topk over the token axis for each expert
|
| 258 |
+
expert_token_scores = r_probs.transpose(0, 1) # (num_blocks, n_tokens)
|
| 259 |
+
topk_scores, topk_token_idx = torch.topk(expert_token_scores, k_capacity, dim=-1)
|
| 260 |
+
self.last_topk_indices = topk_token_idx
|
| 261 |
+
|
| 262 |
+
# Load balancing is guaranteed by construction in Expert Choice
|
| 263 |
+
layer_aux_loss = x_2.new_zeros(())
|
| 264 |
+
|
| 265 |
+
# Shrink projection
|
| 266 |
+
x_2_thin = self.w_down(x_2) # (B, T, d_thin)
|
| 267 |
+
x_2_thin_flat = x_2_thin.view(n_tokens, self.d_thin)
|
| 268 |
+
|
| 269 |
+
# Expert computations
|
| 270 |
+
new_kvs = [nkv_g]
|
| 271 |
+
expert_outputs_flat = torch.zeros(n_tokens, self.d_model, device=x_2.device, dtype=x_2.dtype)
|
| 272 |
+
|
| 273 |
+
for i, block in enumerate(self.thin_blocks):
|
| 274 |
+
sel_idx = topk_token_idx[i]
|
| 275 |
+
bucket_in = x_2_thin_flat[sel_idx].unsqueeze(0) # (1, k_capacity, d_thin)
|
| 276 |
+
|
| 277 |
+
pkv_i = past_kvs[i + 1] if past_kvs else None
|
| 278 |
+
bucket_out, nkv_i = block(bucket_in, pkv_i, use_cache, bidirectional)
|
| 279 |
+
if use_cache:
|
| 280 |
+
new_kvs.append(nkv_i)
|
| 281 |
+
|
| 282 |
+
bucket_out = bucket_out.squeeze(0) # (k_capacity, d_thin)
|
| 283 |
+
bucket_out_full = self.w_up(bucket_out) # (k_capacity, d_model)
|
| 284 |
+
|
| 285 |
+
gate = topk_scores[i].unsqueeze(-1) # (k_capacity, 1)
|
| 286 |
+
expert_outputs_flat.index_add_(0, sel_idx, bucket_out_full * gate)
|
| 287 |
+
|
| 288 |
+
x_3_full = expert_outputs_flat.view(B, T, self.d_model)
|
| 289 |
+
out = x_2 + x_3_full
|
| 290 |
+
|
| 291 |
+
present_kvs = tuple(new_kvs) if use_cache else None
|
| 292 |
+
return out, present_kvs, layer_aux_loss
|
| 293 |
+
|
| 294 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 295 |
+
# 4. RAW MSIT-GPT-BERT MODEL
|
| 296 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 297 |
+
|
| 298 |
+
class MSITGPTBERTModel(nn.Module):
|
| 299 |
+
def __init__(self, cfg):
|
| 300 |
+
super().__init__()
|
| 301 |
+
self.cfg = cfg
|
| 302 |
+
self.wte = nn.Embedding(cfg.vocab_size, cfg.d_model)
|
| 303 |
+
self.drop_emb = nn.Dropout(cfg.dropout)
|
| 304 |
+
self.blocks = nn.ModuleList([
|
| 305 |
+
MoEPMSITBlock(
|
| 306 |
+
d_model=cfg.d_model,
|
| 307 |
+
d_thin=cfg.d_thin,
|
| 308 |
+
num_blocks=cfg.num_blocks,
|
| 309 |
+
capacity_factor=cfg.capacity_factor
|
| 310 |
+
)
|
| 311 |
+
for _ in range(cfg.num_layers)
|
| 312 |
+
])
|
| 313 |
+
self.ln_f = nn.LayerNorm(cfg.d_model)
|
| 314 |
+
self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
|
| 315 |
+
self.wte.weight = self.lm_head.weight
|
| 316 |
+
|
| 317 |
+
def forward(self, input_ids: torch.Tensor, targets: torch.Tensor = None, bidirectional: bool = False):
|
| 318 |
+
x = self.drop_emb(self.wte(input_ids))
|
| 319 |
+
total_aux_loss = 0.0
|
| 320 |
+
|
| 321 |
+
for block in self.blocks:
|
| 322 |
+
x, _, layer_aux = block(x, past_kvs=None, use_cache=False, bidirectional=bidirectional)
|
| 323 |
+
total_aux_loss += layer_aux
|
| 324 |
+
|
| 325 |
+
x = self.ln_f(x)
|
| 326 |
+
logits = self.lm_head(x)
|
| 327 |
+
|
| 328 |
+
loss = None
|
| 329 |
+
if targets is not None:
|
| 330 |
+
ce_loss = F.cross_entropy(logits.view(-1, self.cfg.vocab_size), targets.view(-1), ignore_index=-100)
|
| 331 |
+
avg_aux_loss = total_aux_loss / self.cfg.num_layers
|
| 332 |
+
loss = ce_loss + (0.01 * avg_aux_loss)
|
| 333 |
+
|
| 334 |
+
return logits, loss
|
| 335 |
+
|
| 336 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 337 |
+
# 5. HUGGING FACE MODEL WRAPPERS
|
| 338 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 339 |
+
|
| 340 |
+
class MSITGPTBERTModelWrapper(PreTrainedModel):
|
| 341 |
+
config_class = MSITGPTBERTHFConfig
|
| 342 |
+
base_model_prefix = "transformer"
|
| 343 |
+
|
| 344 |
+
def __init__(self, config: MSITGPTBERTHFConfig):
|
| 345 |
+
super().__init__(config)
|
| 346 |
+
self.wte = nn.Embedding(config.vocab_size, config.d_model)
|
| 347 |
+
self.drop_emb = nn.Dropout(config.dropout)
|
| 348 |
+
self.blocks = nn.ModuleList([
|
| 349 |
+
MoEPMSITBlock(config.d_model, config.d_thin, config.num_blocks, config.capacity_factor)
|
| 350 |
+
for _ in range(config.num_layers)
|
| 351 |
+
])
|
| 352 |
+
self.ln_f = nn.LayerNorm(config.d_model)
|
| 353 |
+
self.post_init()
|
| 354 |
+
|
| 355 |
+
def forward(self, input_ids, **kwargs):
|
| 356 |
+
x = self.drop_emb(self.wte(input_ids))
|
| 357 |
+
for block in self.blocks:
|
| 358 |
+
x, _, _ = block(x, past_kvs=None, use_cache=False, bidirectional=False)
|
| 359 |
+
x = self.ln_f(x)
|
| 360 |
+
return BaseModelOutputWithPast(last_hidden_state=x)
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
class MSITGPTBERTForCausalLM(PreTrainedModel, GenerationMixin):
|
| 364 |
+
config_class = MSITGPTBERTHFConfig
|
| 365 |
+
base_model_prefix = "transformer"
|
| 366 |
+
_no_split_modules = ["MoEPMSITBlock"]
|
| 367 |
+
_tied_weights_keys = {"transformer.lm_head.weight": "transformer.wte.weight"}
|
| 368 |
+
|
| 369 |
+
def __init__(self, config: MSITGPTBERTHFConfig):
|
| 370 |
+
super().__init__(config)
|
| 371 |
+
self.transformer = MSITGPTBERTModelWrapper(config)
|
| 372 |
+
self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
|
| 373 |
+
self.post_init()
|
| 374 |
+
|
| 375 |
+
# State-dict pre-hook for backwards compatibility with checkpoint key naming
|
| 376 |
+
def _prefix_cleaner(state_dict, prefix, local_metadata, Moore, missing_keys, unexpected_keys, error_msgs):
|
| 377 |
+
keys = list(state_dict.keys())
|
| 378 |
+
for k in keys:
|
| 379 |
+
if k.startswith("transformer."):
|
| 380 |
+
state_dict[k.replace("transformer.", "", 1)] = state_dict.pop(k)
|
| 381 |
+
elif f"{prefix}transformer." in k:
|
| 382 |
+
state_dict[k.replace("transformer.", "", 1)] = state_dict.pop(k)
|
| 383 |
+
|
| 384 |
+
self._register_load_state_dict_pre_hook(_prefix_cleaner)
|
| 385 |
+
|
| 386 |
+
def tie_weights(self, **kwargs):
|
| 387 |
+
if hasattr(self, "transformer") and hasattr(self.transformer, "wte") and hasattr(self.transformer, "lm_head"):
|
| 388 |
+
self.transformer.wte.weight = self.lm_head.weight
|
| 389 |
+
|
| 390 |
+
def get_input_embeddings(self):
|
| 391 |
+
return self.transformer.wte
|
| 392 |
+
|
| 393 |
+
def set_input_embeddings(self, new_embeddings):
|
| 394 |
+
self.transformer.wte = new_embeddings
|
| 395 |
+
|
| 396 |
+
def get_output_embeddings(self):
|
| 397 |
+
return self.lm_head
|
| 398 |
+
|
| 399 |
+
def set_output_embeddings(self, new_embeddings):
|
| 400 |
+
self.lm_head = new_embeddings
|
| 401 |
+
|
| 402 |
+
def forward(self,
|
| 403 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 404 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 405 |
+
labels: Optional[torch.LongTensor] = None,
|
| 406 |
+
**kwargs) -> CausalLMOutputWithPast:
|
| 407 |
+
outputs = self.transformer(input_ids)
|
| 408 |
+
hidden_states = outputs.last_hidden_state
|
| 409 |
+
logits = self.lm_head(hidden_states)
|
| 410 |
+
|
| 411 |
+
loss = None
|
| 412 |
+
if labels is not None:
|
| 413 |
+
shift_logits = logits[:, :-1, :].contiguous()
|
| 414 |
+
shift_labels = labels[:, 1:].contiguous()
|
| 415 |
+
loss = F.cross_entropy(
|
| 416 |
+
shift_logits.view(-1, self.config.vocab_size),
|
| 417 |
+
shift_labels.view(-1),
|
| 418 |
+
ignore_index=-100
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
return CausalLMOutputWithPast(
|
| 422 |
+
loss=loss,
|
| 423 |
+
logits=logits,
|
| 424 |
+
past_key_values=None,
|
| 425 |
+
hidden_states=None,
|
| 426 |
+
attentions=None,
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
def prepare_inputs_for_generation(self, input_ids, **kwargs):
|
| 430 |
+
return {"input_ids": input_ids}
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
# Register with auto-mapping
|
| 434 |
+
AutoConfig.register("msit_gptbert", MSITGPTBERTHFConfig)
|
| 435 |
+
AutoModel.register(MSITGPTBERTHFConfig, MSITGPTBERTModelWrapper)
|
| 436 |
+
AutoModelForCausalLM.register(MSITGPTBERTHFConfig, MSITGPTBERTForCausalLM)
|
chck_10M/pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5be2b8c0f883b7c5c32cb6daab34f0d6c9ada8841cdb4a8e8610fe1ec231ba83
|
| 3 |
+
size 135253367
|
chck_10M/tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
chck_10M/tokenizer_config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "tokenizers",
|
| 3 |
+
"bos_token": "[CLS]",
|
| 4 |
+
"eos_token": "[SEP]",
|
| 5 |
+
"mask_token": "[MASK]",
|
| 6 |
+
"model_max_length": 1000000000000000019884624838656,
|
| 7 |
+
"pad_token": "[PAD]",
|
| 8 |
+
"tokenizer_class": "TokenizersBackend",
|
| 9 |
+
"unk_token": "[UNK]"
|
| 10 |
+
}
|
chck_1M/config.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"auto_map": {
|
| 3 |
+
"AutoConfig": "modeling_msit.MSITGPTBERTHFConfig",
|
| 4 |
+
"AutoModel": "modeling_msit.MSITGPTBERTModelWrapper",
|
| 5 |
+
"AutoModelForCausalLM": "modeling_msit.MSITGPTBERTForCausalLM"
|
| 6 |
+
},
|
| 7 |
+
"vocab_size": 16384,
|
| 8 |
+
"block_size": 512,
|
| 9 |
+
"d_model": 384,
|
| 10 |
+
"hidden_size": 384,
|
| 11 |
+
"d_thin": 192,
|
| 12 |
+
"num_layers": 6,
|
| 13 |
+
"num_blocks": 6,
|
| 14 |
+
"capacity_factor": 2.0,
|
| 15 |
+
"dropout": 0.1,
|
| 16 |
+
"model_type": "msit_gptbert"
|
| 17 |
+
}
|
chck_1M/configuration_msit.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
|
| 3 |
+
class MSITGPTBERTHFConfig(PretrainedConfig):
|
| 4 |
+
model_type = "msit_gptbert"
|
| 5 |
+
|
| 6 |
+
def __init__(
|
| 7 |
+
self,
|
| 8 |
+
vocab_size: int = 16384,
|
| 9 |
+
block_size: int = 512,
|
| 10 |
+
d_model: int = 384,
|
| 11 |
+
d_thin: int = 192,
|
| 12 |
+
num_layers: int = 6,
|
| 13 |
+
num_blocks: int = 6,
|
| 14 |
+
capacity_factor: float = 2.0,
|
| 15 |
+
dropout: float = 0.1,
|
| 16 |
+
**kwargs
|
| 17 |
+
):
|
| 18 |
+
kwargs.setdefault("is_decoder", True)
|
| 19 |
+
kwargs.setdefault("bos_token_id", 2) # [CLS]
|
| 20 |
+
kwargs.setdefault("eos_token_id", 3) # [SEP]
|
| 21 |
+
kwargs.setdefault("pad_token_id", 1) # [PAD]
|
| 22 |
+
|
| 23 |
+
self.vocab_size = vocab_size
|
| 24 |
+
self.block_size = block_size
|
| 25 |
+
self.d_model = d_model
|
| 26 |
+
self.d_thin = d_thin
|
| 27 |
+
self.num_layers = num_layers
|
| 28 |
+
self.num_blocks = num_blocks
|
| 29 |
+
self.capacity_factor = capacity_factor
|
| 30 |
+
self.dropout = dropout
|
| 31 |
+
|
| 32 |
+
# Attribute parity for classification heads
|
| 33 |
+
self.hidden_size = d_model
|
| 34 |
+
|
| 35 |
+
super().__init__(**kwargs)
|
chck_1M/modeling_msit.py
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import math
|
| 3 |
+
import random
|
| 4 |
+
import inspect
|
| 5 |
+
from typing import Optional, Tuple, Dict, Any
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
|
| 12 |
+
from transformers import PretrainedConfig, PreTrainedModel, GenerationMixin, AutoConfig, AutoModel, AutoModelForCausalLM
|
| 13 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 14 |
+
|
| 15 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 16 |
+
# Configuration Classes
|
| 17 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 18 |
+
|
| 19 |
+
@dataclass
|
| 20 |
+
class MSITGPTBERTConfig:
|
| 21 |
+
vocab_size: int = 16384
|
| 22 |
+
block_size: int = 512
|
| 23 |
+
d_model: int = 384
|
| 24 |
+
d_thin: int = 192
|
| 25 |
+
num_layers: int = 6
|
| 26 |
+
num_blocks: int = 6
|
| 27 |
+
capacity_factor: float = 2.0
|
| 28 |
+
dropout: float = 0.1
|
| 29 |
+
|
| 30 |
+
class MSITGPTBERTHFConfig(PretrainedConfig):
|
| 31 |
+
model_type = "msit_gptbert"
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self,
|
| 35 |
+
vocab_size: int = 16384,
|
| 36 |
+
block_size: int = 512,
|
| 37 |
+
d_model: int = 384,
|
| 38 |
+
d_thin: int = 192,
|
| 39 |
+
num_layers: int = 6,
|
| 40 |
+
num_blocks: int = 6,
|
| 41 |
+
capacity_factor: float = 2.0,
|
| 42 |
+
dropout: float = 0.1,
|
| 43 |
+
**kwargs
|
| 44 |
+
):
|
| 45 |
+
kwargs.setdefault("is_decoder", True)
|
| 46 |
+
kwargs.setdefault("bos_token_id", 2) # [CLS]
|
| 47 |
+
kwargs.setdefault("eos_token_id", 3) # [SEP]
|
| 48 |
+
kwargs.setdefault("pad_token_id", 1) # [PAD]
|
| 49 |
+
|
| 50 |
+
self.vocab_size = vocab_size
|
| 51 |
+
self.block_size = block_size
|
| 52 |
+
self.d_model = d_model
|
| 53 |
+
self.d_thin = d_thin
|
| 54 |
+
self.num_layers = num_layers
|
| 55 |
+
self.num_blocks = num_blocks
|
| 56 |
+
self.capacity_factor = capacity_factor
|
| 57 |
+
self.dropout = dropout
|
| 58 |
+
|
| 59 |
+
# Attribute parity for classification heads
|
| 60 |
+
self.hidden_size = d_model
|
| 61 |
+
|
| 62 |
+
super().__init__(**kwargs)
|
| 63 |
+
|
| 64 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 65 |
+
# ROPE HELPERS
|
| 66 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 67 |
+
|
| 68 |
+
def _precompute_rope_freqs(head_dim: int, seq_len: int, device: torch.device, theta: float = 10000.0):
|
| 69 |
+
assert head_dim % 2 == 0, "head_dim must be divisible by 2 for RoPE"
|
| 70 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim))
|
| 71 |
+
t = torch.arange(seq_len, device=device).float()
|
| 72 |
+
freqs = torch.outer(t, inv_freq)
|
| 73 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 74 |
+
return emb.cos(), emb.sin()
|
| 75 |
+
|
| 76 |
+
def _apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor):
|
| 77 |
+
L = x.size(2)
|
| 78 |
+
cos = cos[:L, :].unsqueeze(0).unsqueeze(1)
|
| 79 |
+
sin = sin[:L, :].unsqueeze(0).unsqueeze(1)
|
| 80 |
+
|
| 81 |
+
half_dim = x.size(-1) // 2
|
| 82 |
+
x1 = x[..., :half_dim]
|
| 83 |
+
x2 = x[..., half_dim:]
|
| 84 |
+
rotated_x = torch.cat((-x2, x1), dim=-1)
|
| 85 |
+
|
| 86 |
+
return (x * cos) + (rotated_x * sin)
|
| 87 |
+
|
| 88 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 89 |
+
# 1. SLIDING WINDOW ATTENTION
|
| 90 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 91 |
+
|
| 92 |
+
class SlidingWindowAttention(nn.Module):
|
| 93 |
+
def __init__(self, dim: int, num_heads: int, window_size=None):
|
| 94 |
+
super().__init__()
|
| 95 |
+
assert dim % num_heads == 0, "dim must be divisible by num_heads"
|
| 96 |
+
self.num_heads = num_heads
|
| 97 |
+
self.window_size = window_size
|
| 98 |
+
self.head_dim = dim // num_heads
|
| 99 |
+
|
| 100 |
+
self.q_proj = nn.Linear(dim, dim, bias=False)
|
| 101 |
+
self.k_proj = nn.Linear(dim, dim, bias=False)
|
| 102 |
+
self.v_proj = nn.Linear(dim, dim, bias=False)
|
| 103 |
+
self.o_proj = nn.Linear(dim, dim, bias=False)
|
| 104 |
+
|
| 105 |
+
def forward(self, x: torch.Tensor,
|
| 106 |
+
past_kv=None,
|
| 107 |
+
use_cache: bool = False,
|
| 108 |
+
bidirectional: bool = False):
|
| 109 |
+
B, L, D = x.size()
|
| 110 |
+
|
| 111 |
+
q = self.q_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 112 |
+
k = self.k_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 113 |
+
v = self.v_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 114 |
+
|
| 115 |
+
if past_kv is not None:
|
| 116 |
+
past_k, past_v = past_kv
|
| 117 |
+
past_len = past_k.size(2)
|
| 118 |
+
q_cos, q_sin = _precompute_rope_freqs(self.head_dim, past_len + L, x.device)
|
| 119 |
+
q = _apply_rope(q, q_cos[past_len:, :], q_sin[past_len:, :])
|
| 120 |
+
k = _apply_rope(k, q_cos[past_len:, :], q_sin[past_len:, :])
|
| 121 |
+
|
| 122 |
+
k = torch.cat([past_k, k], dim=2)
|
| 123 |
+
v = torch.cat([past_v, v], dim=2)
|
| 124 |
+
else:
|
| 125 |
+
cos, sin = _precompute_rope_freqs(self.head_dim, L, x.device)
|
| 126 |
+
q = _apply_rope(q, cos, sin)
|
| 127 |
+
k = _apply_rope(k, cos, sin)
|
| 128 |
+
|
| 129 |
+
L_kv = k.size(2)
|
| 130 |
+
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
|
| 131 |
+
|
| 132 |
+
if bidirectional:
|
| 133 |
+
if self.window_size is not None:
|
| 134 |
+
past_len = L_kv - L
|
| 135 |
+
pos_i = (past_len + torch.arange(L, device=x.device)).unsqueeze(1)
|
| 136 |
+
pos_j = torch.arange(L_kv, device=x.device).unsqueeze(0)
|
| 137 |
+
dist = torch.abs(pos_i - pos_j)
|
| 138 |
+
win_mask = dist < self.window_size
|
| 139 |
+
scores = scores.masked_fill(
|
| 140 |
+
~win_mask.unsqueeze(0).unsqueeze(0), float('-inf')
|
| 141 |
+
)
|
| 142 |
+
else:
|
| 143 |
+
past_len = L_kv - L
|
| 144 |
+
pos_i = (past_len + torch.arange(L, device=x.device)).unsqueeze(1)
|
| 145 |
+
pos_j = torch.arange(L_kv, device=x.device).unsqueeze(0)
|
| 146 |
+
dist = pos_i - pos_j
|
| 147 |
+
|
| 148 |
+
causal_mask = dist >= 0
|
| 149 |
+
if self.window_size is not None:
|
| 150 |
+
causal_mask = causal_mask & (dist < self.window_size)
|
| 151 |
+
|
| 152 |
+
scores = scores.masked_fill(
|
| 153 |
+
~causal_mask.unsqueeze(0).unsqueeze(0), float('-inf')
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
attn = torch.softmax(scores, dim=-1)
|
| 157 |
+
out = torch.matmul(attn, v)
|
| 158 |
+
out = out.transpose(1, 2).contiguous().view(B, L, D)
|
| 159 |
+
out = self.o_proj(out)
|
| 160 |
+
|
| 161 |
+
if use_cache:
|
| 162 |
+
if self.window_size is not None:
|
| 163 |
+
present_kv = (
|
| 164 |
+
k[:, :, -self.window_size:, :],
|
| 165 |
+
v[:, :, -self.window_size:, :]
|
| 166 |
+
)
|
| 167 |
+
else:
|
| 168 |
+
present_kv = (k, v)
|
| 169 |
+
else:
|
| 170 |
+
present_kv = None
|
| 171 |
+
|
| 172 |
+
return out, present_kv
|
| 173 |
+
|
| 174 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 175 |
+
# 2. MSIT BRANCH BLOCK (Pre-Norm)
|
| 176 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 177 |
+
|
| 178 |
+
class MSITBranchBlock(nn.Module):
|
| 179 |
+
def __init__(self, dim: int, num_heads: int, window_size):
|
| 180 |
+
super().__init__()
|
| 181 |
+
self.ln1 = nn.LayerNorm(dim)
|
| 182 |
+
self.attn = SlidingWindowAttention(dim, num_heads, window_size)
|
| 183 |
+
self.ln2 = nn.LayerNorm(dim)
|
| 184 |
+
self.ffn = nn.Sequential(
|
| 185 |
+
nn.Linear(dim, dim * 4, bias=False),
|
| 186 |
+
nn.GELU(),
|
| 187 |
+
nn.Linear(dim * 4, dim, bias=False),
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
def forward(self, x: torch.Tensor,
|
| 191 |
+
past_kv=None,
|
| 192 |
+
use_cache: bool = False,
|
| 193 |
+
bidirectional: bool = False):
|
| 194 |
+
attn_out, present_kv = self.attn(
|
| 195 |
+
self.ln1(x), past_kv, use_cache, bidirectional
|
| 196 |
+
)
|
| 197 |
+
x = x + attn_out
|
| 198 |
+
x = x + self.ffn(self.ln2(x))
|
| 199 |
+
return x, present_kv
|
| 200 |
+
|
| 201 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 202 |
+
# 3. MoEP-MSIT ARCHITECTURE BLOCK (Expert Choice routing)
|
| 203 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 204 |
+
|
| 205 |
+
class MoEPMSITBlock(nn.Module):
|
| 206 |
+
def __init__(self, d_model: int = 512, d_thin: int = 192, num_blocks: int = 14,
|
| 207 |
+
capacity_factor: float = 2.0):
|
| 208 |
+
super().__init__()
|
| 209 |
+
self.d_model = d_model
|
| 210 |
+
self.d_thin = d_thin
|
| 211 |
+
self.num_blocks = num_blocks
|
| 212 |
+
self.capacity_factor = capacity_factor
|
| 213 |
+
|
| 214 |
+
# 1. Global Block (Dense, d_model)
|
| 215 |
+
num_heads_global = max(1, d_model // 64)
|
| 216 |
+
self.global_block = MSITBranchBlock(d_model, num_heads_global, window_size=None)
|
| 217 |
+
|
| 218 |
+
# 2. Router
|
| 219 |
+
self.router_ln = nn.LayerNorm(d_model)
|
| 220 |
+
self.w_router = nn.Linear(d_model, num_blocks, bias=False)
|
| 221 |
+
|
| 222 |
+
# 3. Shrink Projection
|
| 223 |
+
self.w_down = nn.Linear(d_model, d_thin, bias=False)
|
| 224 |
+
|
| 225 |
+
# 4. Thin Parallel Blocks (d_thin)
|
| 226 |
+
self.windows = [None, 16, 8, 4, 2] + [None] * (num_blocks - 5)
|
| 227 |
+
self.heads = [max(1, d_thin // 64)] * num_blocks
|
| 228 |
+
|
| 229 |
+
self.thin_blocks = nn.ModuleList([
|
| 230 |
+
MSITBranchBlock(d_thin, self.heads[i], self.windows[i])
|
| 231 |
+
for i in range(num_blocks)
|
| 232 |
+
])
|
| 233 |
+
|
| 234 |
+
# 6. Grow Projection
|
| 235 |
+
self.w_up = nn.Linear(d_thin, d_model, bias=False)
|
| 236 |
+
self.last_topk_indices = None
|
| 237 |
+
|
| 238 |
+
def forward(self, x_0: torch.Tensor, past_kvs=None, use_cache: bool = False, bidirectional: bool = False):
|
| 239 |
+
B, T, D = x_0.size()
|
| 240 |
+
n_tokens = B * T
|
| 241 |
+
|
| 242 |
+
# Step 1: Global Block
|
| 243 |
+
pkv_g = past_kvs[0] if past_kvs else None
|
| 244 |
+
x_1, nkv_g = self.global_block(x_0, pkv_g, use_cache, bidirectional)
|
| 245 |
+
|
| 246 |
+
# Step 2: Gated input stream
|
| 247 |
+
x_2 = x_1 + x_0
|
| 248 |
+
|
| 249 |
+
# Router scores
|
| 250 |
+
r_logits = self.w_router(self.router_ln(x_2)).view(n_tokens, self.num_blocks)
|
| 251 |
+
r_probs = F.softmax(r_logits, dim=-1)
|
| 252 |
+
|
| 253 |
+
# Per-expert capacity: k = (n * c) / e
|
| 254 |
+
k_capacity = max(1, int(round(n_tokens * self.capacity_factor / self.num_blocks)))
|
| 255 |
+
k_capacity = min(k_capacity, n_tokens)
|
| 256 |
+
|
| 257 |
+
# Expert Choice routing: topk over the token axis for each expert
|
| 258 |
+
expert_token_scores = r_probs.transpose(0, 1) # (num_blocks, n_tokens)
|
| 259 |
+
topk_scores, topk_token_idx = torch.topk(expert_token_scores, k_capacity, dim=-1)
|
| 260 |
+
self.last_topk_indices = topk_token_idx
|
| 261 |
+
|
| 262 |
+
# Load balancing is guaranteed by construction in Expert Choice
|
| 263 |
+
layer_aux_loss = x_2.new_zeros(())
|
| 264 |
+
|
| 265 |
+
# Shrink projection
|
| 266 |
+
x_2_thin = self.w_down(x_2) # (B, T, d_thin)
|
| 267 |
+
x_2_thin_flat = x_2_thin.view(n_tokens, self.d_thin)
|
| 268 |
+
|
| 269 |
+
# Expert computations
|
| 270 |
+
new_kvs = [nkv_g]
|
| 271 |
+
expert_outputs_flat = torch.zeros(n_tokens, self.d_model, device=x_2.device, dtype=x_2.dtype)
|
| 272 |
+
|
| 273 |
+
for i, block in enumerate(self.thin_blocks):
|
| 274 |
+
sel_idx = topk_token_idx[i]
|
| 275 |
+
bucket_in = x_2_thin_flat[sel_idx].unsqueeze(0) # (1, k_capacity, d_thin)
|
| 276 |
+
|
| 277 |
+
pkv_i = past_kvs[i + 1] if past_kvs else None
|
| 278 |
+
bucket_out, nkv_i = block(bucket_in, pkv_i, use_cache, bidirectional)
|
| 279 |
+
if use_cache:
|
| 280 |
+
new_kvs.append(nkv_i)
|
| 281 |
+
|
| 282 |
+
bucket_out = bucket_out.squeeze(0) # (k_capacity, d_thin)
|
| 283 |
+
bucket_out_full = self.w_up(bucket_out) # (k_capacity, d_model)
|
| 284 |
+
|
| 285 |
+
gate = topk_scores[i].unsqueeze(-1) # (k_capacity, 1)
|
| 286 |
+
expert_outputs_flat.index_add_(0, sel_idx, bucket_out_full * gate)
|
| 287 |
+
|
| 288 |
+
x_3_full = expert_outputs_flat.view(B, T, self.d_model)
|
| 289 |
+
out = x_2 + x_3_full
|
| 290 |
+
|
| 291 |
+
present_kvs = tuple(new_kvs) if use_cache else None
|
| 292 |
+
return out, present_kvs, layer_aux_loss
|
| 293 |
+
|
| 294 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 295 |
+
# 4. RAW MSIT-GPT-BERT MODEL
|
| 296 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 297 |
+
|
| 298 |
+
class MSITGPTBERTModel(nn.Module):
|
| 299 |
+
def __init__(self, cfg):
|
| 300 |
+
super().__init__()
|
| 301 |
+
self.cfg = cfg
|
| 302 |
+
self.wte = nn.Embedding(cfg.vocab_size, cfg.d_model)
|
| 303 |
+
self.drop_emb = nn.Dropout(cfg.dropout)
|
| 304 |
+
self.blocks = nn.ModuleList([
|
| 305 |
+
MoEPMSITBlock(
|
| 306 |
+
d_model=cfg.d_model,
|
| 307 |
+
d_thin=cfg.d_thin,
|
| 308 |
+
num_blocks=cfg.num_blocks,
|
| 309 |
+
capacity_factor=cfg.capacity_factor
|
| 310 |
+
)
|
| 311 |
+
for _ in range(cfg.num_layers)
|
| 312 |
+
])
|
| 313 |
+
self.ln_f = nn.LayerNorm(cfg.d_model)
|
| 314 |
+
self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
|
| 315 |
+
self.wte.weight = self.lm_head.weight
|
| 316 |
+
|
| 317 |
+
def forward(self, input_ids: torch.Tensor, targets: torch.Tensor = None, bidirectional: bool = False):
|
| 318 |
+
x = self.drop_emb(self.wte(input_ids))
|
| 319 |
+
total_aux_loss = 0.0
|
| 320 |
+
|
| 321 |
+
for block in self.blocks:
|
| 322 |
+
x, _, layer_aux = block(x, past_kvs=None, use_cache=False, bidirectional=bidirectional)
|
| 323 |
+
total_aux_loss += layer_aux
|
| 324 |
+
|
| 325 |
+
x = self.ln_f(x)
|
| 326 |
+
logits = self.lm_head(x)
|
| 327 |
+
|
| 328 |
+
loss = None
|
| 329 |
+
if targets is not None:
|
| 330 |
+
ce_loss = F.cross_entropy(logits.view(-1, self.cfg.vocab_size), targets.view(-1), ignore_index=-100)
|
| 331 |
+
avg_aux_loss = total_aux_loss / self.cfg.num_layers
|
| 332 |
+
loss = ce_loss + (0.01 * avg_aux_loss)
|
| 333 |
+
|
| 334 |
+
return logits, loss
|
| 335 |
+
|
| 336 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 337 |
+
# 5. HUGGING FACE MODEL WRAPPERS
|
| 338 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 339 |
+
|
| 340 |
+
class MSITGPTBERTModelWrapper(PreTrainedModel):
|
| 341 |
+
config_class = MSITGPTBERTHFConfig
|
| 342 |
+
base_model_prefix = "transformer"
|
| 343 |
+
|
| 344 |
+
def __init__(self, config: MSITGPTBERTHFConfig):
|
| 345 |
+
super().__init__(config)
|
| 346 |
+
self.wte = nn.Embedding(config.vocab_size, config.d_model)
|
| 347 |
+
self.drop_emb = nn.Dropout(config.dropout)
|
| 348 |
+
self.blocks = nn.ModuleList([
|
| 349 |
+
MoEPMSITBlock(config.d_model, config.d_thin, config.num_blocks, config.capacity_factor)
|
| 350 |
+
for _ in range(config.num_layers)
|
| 351 |
+
])
|
| 352 |
+
self.ln_f = nn.LayerNorm(config.d_model)
|
| 353 |
+
self.post_init()
|
| 354 |
+
|
| 355 |
+
def forward(self, input_ids, **kwargs):
|
| 356 |
+
x = self.drop_emb(self.wte(input_ids))
|
| 357 |
+
for block in self.blocks:
|
| 358 |
+
x, _, _ = block(x, past_kvs=None, use_cache=False, bidirectional=False)
|
| 359 |
+
x = self.ln_f(x)
|
| 360 |
+
return BaseModelOutputWithPast(last_hidden_state=x)
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
class MSITGPTBERTForCausalLM(PreTrainedModel, GenerationMixin):
|
| 364 |
+
config_class = MSITGPTBERTHFConfig
|
| 365 |
+
base_model_prefix = "transformer"
|
| 366 |
+
_no_split_modules = ["MoEPMSITBlock"]
|
| 367 |
+
_tied_weights_keys = {"transformer.lm_head.weight": "transformer.wte.weight"}
|
| 368 |
+
|
| 369 |
+
def __init__(self, config: MSITGPTBERTHFConfig):
|
| 370 |
+
super().__init__(config)
|
| 371 |
+
self.transformer = MSITGPTBERTModelWrapper(config)
|
| 372 |
+
self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
|
| 373 |
+
self.post_init()
|
| 374 |
+
|
| 375 |
+
# State-dict pre-hook for backwards compatibility with checkpoint key naming
|
| 376 |
+
def _prefix_cleaner(state_dict, prefix, local_metadata, Moore, missing_keys, unexpected_keys, error_msgs):
|
| 377 |
+
keys = list(state_dict.keys())
|
| 378 |
+
for k in keys:
|
| 379 |
+
if k.startswith("transformer."):
|
| 380 |
+
state_dict[k.replace("transformer.", "", 1)] = state_dict.pop(k)
|
| 381 |
+
elif f"{prefix}transformer." in k:
|
| 382 |
+
state_dict[k.replace("transformer.", "", 1)] = state_dict.pop(k)
|
| 383 |
+
|
| 384 |
+
self._register_load_state_dict_pre_hook(_prefix_cleaner)
|
| 385 |
+
|
| 386 |
+
def tie_weights(self, **kwargs):
|
| 387 |
+
if hasattr(self, "transformer") and hasattr(self.transformer, "wte") and hasattr(self.transformer, "lm_head"):
|
| 388 |
+
self.transformer.wte.weight = self.lm_head.weight
|
| 389 |
+
|
| 390 |
+
def get_input_embeddings(self):
|
| 391 |
+
return self.transformer.wte
|
| 392 |
+
|
| 393 |
+
def set_input_embeddings(self, new_embeddings):
|
| 394 |
+
self.transformer.wte = new_embeddings
|
| 395 |
+
|
| 396 |
+
def get_output_embeddings(self):
|
| 397 |
+
return self.lm_head
|
| 398 |
+
|
| 399 |
+
def set_output_embeddings(self, new_embeddings):
|
| 400 |
+
self.lm_head = new_embeddings
|
| 401 |
+
|
| 402 |
+
def forward(self,
|
| 403 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 404 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 405 |
+
labels: Optional[torch.LongTensor] = None,
|
| 406 |
+
**kwargs) -> CausalLMOutputWithPast:
|
| 407 |
+
outputs = self.transformer(input_ids)
|
| 408 |
+
hidden_states = outputs.last_hidden_state
|
| 409 |
+
logits = self.lm_head(hidden_states)
|
| 410 |
+
|
| 411 |
+
loss = None
|
| 412 |
+
if labels is not None:
|
| 413 |
+
shift_logits = logits[:, :-1, :].contiguous()
|
| 414 |
+
shift_labels = labels[:, 1:].contiguous()
|
| 415 |
+
loss = F.cross_entropy(
|
| 416 |
+
shift_logits.view(-1, self.config.vocab_size),
|
| 417 |
+
shift_labels.view(-1),
|
| 418 |
+
ignore_index=-100
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
return CausalLMOutputWithPast(
|
| 422 |
+
loss=loss,
|
| 423 |
+
logits=logits,
|
| 424 |
+
past_key_values=None,
|
| 425 |
+
hidden_states=None,
|
| 426 |
+
attentions=None,
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
def prepare_inputs_for_generation(self, input_ids, **kwargs):
|
| 430 |
+
return {"input_ids": input_ids}
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
# Register with auto-mapping
|
| 434 |
+
AutoConfig.register("msit_gptbert", MSITGPTBERTHFConfig)
|
| 435 |
+
AutoModel.register(MSITGPTBERTHFConfig, MSITGPTBERTModelWrapper)
|
| 436 |
+
AutoModelForCausalLM.register(MSITGPTBERTHFConfig, MSITGPTBERTForCausalLM)
|
chck_1M/pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1b172a3b81d4a22f5d8e5ad6bce461f81204abe639b99bfa9d585231a2f5b40e
|
| 3 |
+
size 135253367
|
chck_1M/tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
chck_1M/tokenizer_config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "tokenizers",
|
| 3 |
+
"bos_token": "[CLS]",
|
| 4 |
+
"eos_token": "[SEP]",
|
| 5 |
+
"mask_token": "[MASK]",
|
| 6 |
+
"model_max_length": 1000000000000000019884624838656,
|
| 7 |
+
"pad_token": "[PAD]",
|
| 8 |
+
"tokenizer_class": "TokenizersBackend",
|
| 9 |
+
"unk_token": "[UNK]"
|
| 10 |
+
}
|
chck_20M/config.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"auto_map": {
|
| 3 |
+
"AutoConfig": "modeling_msit.MSITGPTBERTHFConfig",
|
| 4 |
+
"AutoModel": "modeling_msit.MSITGPTBERTModelWrapper",
|
| 5 |
+
"AutoModelForCausalLM": "modeling_msit.MSITGPTBERTForCausalLM"
|
| 6 |
+
},
|
| 7 |
+
"vocab_size": 16384,
|
| 8 |
+
"block_size": 512,
|
| 9 |
+
"d_model": 384,
|
| 10 |
+
"hidden_size": 384,
|
| 11 |
+
"d_thin": 192,
|
| 12 |
+
"num_layers": 6,
|
| 13 |
+
"num_blocks": 6,
|
| 14 |
+
"capacity_factor": 2.0,
|
| 15 |
+
"dropout": 0.1,
|
| 16 |
+
"model_type": "msit_gptbert"
|
| 17 |
+
}
|
chck_20M/configuration_msit.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
|
| 3 |
+
class MSITGPTBERTHFConfig(PretrainedConfig):
|
| 4 |
+
model_type = "msit_gptbert"
|
| 5 |
+
|
| 6 |
+
def __init__(
|
| 7 |
+
self,
|
| 8 |
+
vocab_size: int = 16384,
|
| 9 |
+
block_size: int = 512,
|
| 10 |
+
d_model: int = 384,
|
| 11 |
+
d_thin: int = 192,
|
| 12 |
+
num_layers: int = 6,
|
| 13 |
+
num_blocks: int = 6,
|
| 14 |
+
capacity_factor: float = 2.0,
|
| 15 |
+
dropout: float = 0.1,
|
| 16 |
+
**kwargs
|
| 17 |
+
):
|
| 18 |
+
kwargs.setdefault("is_decoder", True)
|
| 19 |
+
kwargs.setdefault("bos_token_id", 2) # [CLS]
|
| 20 |
+
kwargs.setdefault("eos_token_id", 3) # [SEP]
|
| 21 |
+
kwargs.setdefault("pad_token_id", 1) # [PAD]
|
| 22 |
+
|
| 23 |
+
self.vocab_size = vocab_size
|
| 24 |
+
self.block_size = block_size
|
| 25 |
+
self.d_model = d_model
|
| 26 |
+
self.d_thin = d_thin
|
| 27 |
+
self.num_layers = num_layers
|
| 28 |
+
self.num_blocks = num_blocks
|
| 29 |
+
self.capacity_factor = capacity_factor
|
| 30 |
+
self.dropout = dropout
|
| 31 |
+
|
| 32 |
+
# Attribute parity for classification heads
|
| 33 |
+
self.hidden_size = d_model
|
| 34 |
+
|
| 35 |
+
super().__init__(**kwargs)
|
chck_20M/modeling_msit.py
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import math
|
| 3 |
+
import random
|
| 4 |
+
import inspect
|
| 5 |
+
from typing import Optional, Tuple, Dict, Any
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
|
| 12 |
+
from transformers import PretrainedConfig, PreTrainedModel, GenerationMixin, AutoConfig, AutoModel, AutoModelForCausalLM
|
| 13 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 14 |
+
|
| 15 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 16 |
+
# Configuration Classes
|
| 17 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 18 |
+
|
| 19 |
+
@dataclass
|
| 20 |
+
class MSITGPTBERTConfig:
|
| 21 |
+
vocab_size: int = 16384
|
| 22 |
+
block_size: int = 512
|
| 23 |
+
d_model: int = 384
|
| 24 |
+
d_thin: int = 192
|
| 25 |
+
num_layers: int = 6
|
| 26 |
+
num_blocks: int = 6
|
| 27 |
+
capacity_factor: float = 2.0
|
| 28 |
+
dropout: float = 0.1
|
| 29 |
+
|
| 30 |
+
class MSITGPTBERTHFConfig(PretrainedConfig):
|
| 31 |
+
model_type = "msit_gptbert"
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self,
|
| 35 |
+
vocab_size: int = 16384,
|
| 36 |
+
block_size: int = 512,
|
| 37 |
+
d_model: int = 384,
|
| 38 |
+
d_thin: int = 192,
|
| 39 |
+
num_layers: int = 6,
|
| 40 |
+
num_blocks: int = 6,
|
| 41 |
+
capacity_factor: float = 2.0,
|
| 42 |
+
dropout: float = 0.1,
|
| 43 |
+
**kwargs
|
| 44 |
+
):
|
| 45 |
+
kwargs.setdefault("is_decoder", True)
|
| 46 |
+
kwargs.setdefault("bos_token_id", 2) # [CLS]
|
| 47 |
+
kwargs.setdefault("eos_token_id", 3) # [SEP]
|
| 48 |
+
kwargs.setdefault("pad_token_id", 1) # [PAD]
|
| 49 |
+
|
| 50 |
+
self.vocab_size = vocab_size
|
| 51 |
+
self.block_size = block_size
|
| 52 |
+
self.d_model = d_model
|
| 53 |
+
self.d_thin = d_thin
|
| 54 |
+
self.num_layers = num_layers
|
| 55 |
+
self.num_blocks = num_blocks
|
| 56 |
+
self.capacity_factor = capacity_factor
|
| 57 |
+
self.dropout = dropout
|
| 58 |
+
|
| 59 |
+
# Attribute parity for classification heads
|
| 60 |
+
self.hidden_size = d_model
|
| 61 |
+
|
| 62 |
+
super().__init__(**kwargs)
|
| 63 |
+
|
| 64 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 65 |
+
# ROPE HELPERS
|
| 66 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 67 |
+
|
| 68 |
+
def _precompute_rope_freqs(head_dim: int, seq_len: int, device: torch.device, theta: float = 10000.0):
|
| 69 |
+
assert head_dim % 2 == 0, "head_dim must be divisible by 2 for RoPE"
|
| 70 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim))
|
| 71 |
+
t = torch.arange(seq_len, device=device).float()
|
| 72 |
+
freqs = torch.outer(t, inv_freq)
|
| 73 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 74 |
+
return emb.cos(), emb.sin()
|
| 75 |
+
|
| 76 |
+
def _apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor):
|
| 77 |
+
L = x.size(2)
|
| 78 |
+
cos = cos[:L, :].unsqueeze(0).unsqueeze(1)
|
| 79 |
+
sin = sin[:L, :].unsqueeze(0).unsqueeze(1)
|
| 80 |
+
|
| 81 |
+
half_dim = x.size(-1) // 2
|
| 82 |
+
x1 = x[..., :half_dim]
|
| 83 |
+
x2 = x[..., half_dim:]
|
| 84 |
+
rotated_x = torch.cat((-x2, x1), dim=-1)
|
| 85 |
+
|
| 86 |
+
return (x * cos) + (rotated_x * sin)
|
| 87 |
+
|
| 88 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 89 |
+
# 1. SLIDING WINDOW ATTENTION
|
| 90 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 91 |
+
|
| 92 |
+
class SlidingWindowAttention(nn.Module):
|
| 93 |
+
def __init__(self, dim: int, num_heads: int, window_size=None):
|
| 94 |
+
super().__init__()
|
| 95 |
+
assert dim % num_heads == 0, "dim must be divisible by num_heads"
|
| 96 |
+
self.num_heads = num_heads
|
| 97 |
+
self.window_size = window_size
|
| 98 |
+
self.head_dim = dim // num_heads
|
| 99 |
+
|
| 100 |
+
self.q_proj = nn.Linear(dim, dim, bias=False)
|
| 101 |
+
self.k_proj = nn.Linear(dim, dim, bias=False)
|
| 102 |
+
self.v_proj = nn.Linear(dim, dim, bias=False)
|
| 103 |
+
self.o_proj = nn.Linear(dim, dim, bias=False)
|
| 104 |
+
|
| 105 |
+
def forward(self, x: torch.Tensor,
|
| 106 |
+
past_kv=None,
|
| 107 |
+
use_cache: bool = False,
|
| 108 |
+
bidirectional: bool = False):
|
| 109 |
+
B, L, D = x.size()
|
| 110 |
+
|
| 111 |
+
q = self.q_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 112 |
+
k = self.k_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 113 |
+
v = self.v_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 114 |
+
|
| 115 |
+
if past_kv is not None:
|
| 116 |
+
past_k, past_v = past_kv
|
| 117 |
+
past_len = past_k.size(2)
|
| 118 |
+
q_cos, q_sin = _precompute_rope_freqs(self.head_dim, past_len + L, x.device)
|
| 119 |
+
q = _apply_rope(q, q_cos[past_len:, :], q_sin[past_len:, :])
|
| 120 |
+
k = _apply_rope(k, q_cos[past_len:, :], q_sin[past_len:, :])
|
| 121 |
+
|
| 122 |
+
k = torch.cat([past_k, k], dim=2)
|
| 123 |
+
v = torch.cat([past_v, v], dim=2)
|
| 124 |
+
else:
|
| 125 |
+
cos, sin = _precompute_rope_freqs(self.head_dim, L, x.device)
|
| 126 |
+
q = _apply_rope(q, cos, sin)
|
| 127 |
+
k = _apply_rope(k, cos, sin)
|
| 128 |
+
|
| 129 |
+
L_kv = k.size(2)
|
| 130 |
+
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
|
| 131 |
+
|
| 132 |
+
if bidirectional:
|
| 133 |
+
if self.window_size is not None:
|
| 134 |
+
past_len = L_kv - L
|
| 135 |
+
pos_i = (past_len + torch.arange(L, device=x.device)).unsqueeze(1)
|
| 136 |
+
pos_j = torch.arange(L_kv, device=x.device).unsqueeze(0)
|
| 137 |
+
dist = torch.abs(pos_i - pos_j)
|
| 138 |
+
win_mask = dist < self.window_size
|
| 139 |
+
scores = scores.masked_fill(
|
| 140 |
+
~win_mask.unsqueeze(0).unsqueeze(0), float('-inf')
|
| 141 |
+
)
|
| 142 |
+
else:
|
| 143 |
+
past_len = L_kv - L
|
| 144 |
+
pos_i = (past_len + torch.arange(L, device=x.device)).unsqueeze(1)
|
| 145 |
+
pos_j = torch.arange(L_kv, device=x.device).unsqueeze(0)
|
| 146 |
+
dist = pos_i - pos_j
|
| 147 |
+
|
| 148 |
+
causal_mask = dist >= 0
|
| 149 |
+
if self.window_size is not None:
|
| 150 |
+
causal_mask = causal_mask & (dist < self.window_size)
|
| 151 |
+
|
| 152 |
+
scores = scores.masked_fill(
|
| 153 |
+
~causal_mask.unsqueeze(0).unsqueeze(0), float('-inf')
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
attn = torch.softmax(scores, dim=-1)
|
| 157 |
+
out = torch.matmul(attn, v)
|
| 158 |
+
out = out.transpose(1, 2).contiguous().view(B, L, D)
|
| 159 |
+
out = self.o_proj(out)
|
| 160 |
+
|
| 161 |
+
if use_cache:
|
| 162 |
+
if self.window_size is not None:
|
| 163 |
+
present_kv = (
|
| 164 |
+
k[:, :, -self.window_size:, :],
|
| 165 |
+
v[:, :, -self.window_size:, :]
|
| 166 |
+
)
|
| 167 |
+
else:
|
| 168 |
+
present_kv = (k, v)
|
| 169 |
+
else:
|
| 170 |
+
present_kv = None
|
| 171 |
+
|
| 172 |
+
return out, present_kv
|
| 173 |
+
|
| 174 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 175 |
+
# 2. MSIT BRANCH BLOCK (Pre-Norm)
|
| 176 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 177 |
+
|
| 178 |
+
class MSITBranchBlock(nn.Module):
|
| 179 |
+
def __init__(self, dim: int, num_heads: int, window_size):
|
| 180 |
+
super().__init__()
|
| 181 |
+
self.ln1 = nn.LayerNorm(dim)
|
| 182 |
+
self.attn = SlidingWindowAttention(dim, num_heads, window_size)
|
| 183 |
+
self.ln2 = nn.LayerNorm(dim)
|
| 184 |
+
self.ffn = nn.Sequential(
|
| 185 |
+
nn.Linear(dim, dim * 4, bias=False),
|
| 186 |
+
nn.GELU(),
|
| 187 |
+
nn.Linear(dim * 4, dim, bias=False),
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
def forward(self, x: torch.Tensor,
|
| 191 |
+
past_kv=None,
|
| 192 |
+
use_cache: bool = False,
|
| 193 |
+
bidirectional: bool = False):
|
| 194 |
+
attn_out, present_kv = self.attn(
|
| 195 |
+
self.ln1(x), past_kv, use_cache, bidirectional
|
| 196 |
+
)
|
| 197 |
+
x = x + attn_out
|
| 198 |
+
x = x + self.ffn(self.ln2(x))
|
| 199 |
+
return x, present_kv
|
| 200 |
+
|
| 201 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 202 |
+
# 3. MoEP-MSIT ARCHITECTURE BLOCK (Expert Choice routing)
|
| 203 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 204 |
+
|
| 205 |
+
class MoEPMSITBlock(nn.Module):
|
| 206 |
+
def __init__(self, d_model: int = 512, d_thin: int = 192, num_blocks: int = 14,
|
| 207 |
+
capacity_factor: float = 2.0):
|
| 208 |
+
super().__init__()
|
| 209 |
+
self.d_model = d_model
|
| 210 |
+
self.d_thin = d_thin
|
| 211 |
+
self.num_blocks = num_blocks
|
| 212 |
+
self.capacity_factor = capacity_factor
|
| 213 |
+
|
| 214 |
+
# 1. Global Block (Dense, d_model)
|
| 215 |
+
num_heads_global = max(1, d_model // 64)
|
| 216 |
+
self.global_block = MSITBranchBlock(d_model, num_heads_global, window_size=None)
|
| 217 |
+
|
| 218 |
+
# 2. Router
|
| 219 |
+
self.router_ln = nn.LayerNorm(d_model)
|
| 220 |
+
self.w_router = nn.Linear(d_model, num_blocks, bias=False)
|
| 221 |
+
|
| 222 |
+
# 3. Shrink Projection
|
| 223 |
+
self.w_down = nn.Linear(d_model, d_thin, bias=False)
|
| 224 |
+
|
| 225 |
+
# 4. Thin Parallel Blocks (d_thin)
|
| 226 |
+
self.windows = [None, 16, 8, 4, 2] + [None] * (num_blocks - 5)
|
| 227 |
+
self.heads = [max(1, d_thin // 64)] * num_blocks
|
| 228 |
+
|
| 229 |
+
self.thin_blocks = nn.ModuleList([
|
| 230 |
+
MSITBranchBlock(d_thin, self.heads[i], self.windows[i])
|
| 231 |
+
for i in range(num_blocks)
|
| 232 |
+
])
|
| 233 |
+
|
| 234 |
+
# 6. Grow Projection
|
| 235 |
+
self.w_up = nn.Linear(d_thin, d_model, bias=False)
|
| 236 |
+
self.last_topk_indices = None
|
| 237 |
+
|
| 238 |
+
def forward(self, x_0: torch.Tensor, past_kvs=None, use_cache: bool = False, bidirectional: bool = False):
|
| 239 |
+
B, T, D = x_0.size()
|
| 240 |
+
n_tokens = B * T
|
| 241 |
+
|
| 242 |
+
# Step 1: Global Block
|
| 243 |
+
pkv_g = past_kvs[0] if past_kvs else None
|
| 244 |
+
x_1, nkv_g = self.global_block(x_0, pkv_g, use_cache, bidirectional)
|
| 245 |
+
|
| 246 |
+
# Step 2: Gated input stream
|
| 247 |
+
x_2 = x_1 + x_0
|
| 248 |
+
|
| 249 |
+
# Router scores
|
| 250 |
+
r_logits = self.w_router(self.router_ln(x_2)).view(n_tokens, self.num_blocks)
|
| 251 |
+
r_probs = F.softmax(r_logits, dim=-1)
|
| 252 |
+
|
| 253 |
+
# Per-expert capacity: k = (n * c) / e
|
| 254 |
+
k_capacity = max(1, int(round(n_tokens * self.capacity_factor / self.num_blocks)))
|
| 255 |
+
k_capacity = min(k_capacity, n_tokens)
|
| 256 |
+
|
| 257 |
+
# Expert Choice routing: topk over the token axis for each expert
|
| 258 |
+
expert_token_scores = r_probs.transpose(0, 1) # (num_blocks, n_tokens)
|
| 259 |
+
topk_scores, topk_token_idx = torch.topk(expert_token_scores, k_capacity, dim=-1)
|
| 260 |
+
self.last_topk_indices = topk_token_idx
|
| 261 |
+
|
| 262 |
+
# Load balancing is guaranteed by construction in Expert Choice
|
| 263 |
+
layer_aux_loss = x_2.new_zeros(())
|
| 264 |
+
|
| 265 |
+
# Shrink projection
|
| 266 |
+
x_2_thin = self.w_down(x_2) # (B, T, d_thin)
|
| 267 |
+
x_2_thin_flat = x_2_thin.view(n_tokens, self.d_thin)
|
| 268 |
+
|
| 269 |
+
# Expert computations
|
| 270 |
+
new_kvs = [nkv_g]
|
| 271 |
+
expert_outputs_flat = torch.zeros(n_tokens, self.d_model, device=x_2.device, dtype=x_2.dtype)
|
| 272 |
+
|
| 273 |
+
for i, block in enumerate(self.thin_blocks):
|
| 274 |
+
sel_idx = topk_token_idx[i]
|
| 275 |
+
bucket_in = x_2_thin_flat[sel_idx].unsqueeze(0) # (1, k_capacity, d_thin)
|
| 276 |
+
|
| 277 |
+
pkv_i = past_kvs[i + 1] if past_kvs else None
|
| 278 |
+
bucket_out, nkv_i = block(bucket_in, pkv_i, use_cache, bidirectional)
|
| 279 |
+
if use_cache:
|
| 280 |
+
new_kvs.append(nkv_i)
|
| 281 |
+
|
| 282 |
+
bucket_out = bucket_out.squeeze(0) # (k_capacity, d_thin)
|
| 283 |
+
bucket_out_full = self.w_up(bucket_out) # (k_capacity, d_model)
|
| 284 |
+
|
| 285 |
+
gate = topk_scores[i].unsqueeze(-1) # (k_capacity, 1)
|
| 286 |
+
expert_outputs_flat.index_add_(0, sel_idx, bucket_out_full * gate)
|
| 287 |
+
|
| 288 |
+
x_3_full = expert_outputs_flat.view(B, T, self.d_model)
|
| 289 |
+
out = x_2 + x_3_full
|
| 290 |
+
|
| 291 |
+
present_kvs = tuple(new_kvs) if use_cache else None
|
| 292 |
+
return out, present_kvs, layer_aux_loss
|
| 293 |
+
|
| 294 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 295 |
+
# 4. RAW MSIT-GPT-BERT MODEL
|
| 296 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 297 |
+
|
| 298 |
+
class MSITGPTBERTModel(nn.Module):
|
| 299 |
+
def __init__(self, cfg):
|
| 300 |
+
super().__init__()
|
| 301 |
+
self.cfg = cfg
|
| 302 |
+
self.wte = nn.Embedding(cfg.vocab_size, cfg.d_model)
|
| 303 |
+
self.drop_emb = nn.Dropout(cfg.dropout)
|
| 304 |
+
self.blocks = nn.ModuleList([
|
| 305 |
+
MoEPMSITBlock(
|
| 306 |
+
d_model=cfg.d_model,
|
| 307 |
+
d_thin=cfg.d_thin,
|
| 308 |
+
num_blocks=cfg.num_blocks,
|
| 309 |
+
capacity_factor=cfg.capacity_factor
|
| 310 |
+
)
|
| 311 |
+
for _ in range(cfg.num_layers)
|
| 312 |
+
])
|
| 313 |
+
self.ln_f = nn.LayerNorm(cfg.d_model)
|
| 314 |
+
self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
|
| 315 |
+
self.wte.weight = self.lm_head.weight
|
| 316 |
+
|
| 317 |
+
def forward(self, input_ids: torch.Tensor, targets: torch.Tensor = None, bidirectional: bool = False):
|
| 318 |
+
x = self.drop_emb(self.wte(input_ids))
|
| 319 |
+
total_aux_loss = 0.0
|
| 320 |
+
|
| 321 |
+
for block in self.blocks:
|
| 322 |
+
x, _, layer_aux = block(x, past_kvs=None, use_cache=False, bidirectional=bidirectional)
|
| 323 |
+
total_aux_loss += layer_aux
|
| 324 |
+
|
| 325 |
+
x = self.ln_f(x)
|
| 326 |
+
logits = self.lm_head(x)
|
| 327 |
+
|
| 328 |
+
loss = None
|
| 329 |
+
if targets is not None:
|
| 330 |
+
ce_loss = F.cross_entropy(logits.view(-1, self.cfg.vocab_size), targets.view(-1), ignore_index=-100)
|
| 331 |
+
avg_aux_loss = total_aux_loss / self.cfg.num_layers
|
| 332 |
+
loss = ce_loss + (0.01 * avg_aux_loss)
|
| 333 |
+
|
| 334 |
+
return logits, loss
|
| 335 |
+
|
| 336 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 337 |
+
# 5. HUGGING FACE MODEL WRAPPERS
|
| 338 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 339 |
+
|
| 340 |
+
class MSITGPTBERTModelWrapper(PreTrainedModel):
|
| 341 |
+
config_class = MSITGPTBERTHFConfig
|
| 342 |
+
base_model_prefix = "transformer"
|
| 343 |
+
|
| 344 |
+
def __init__(self, config: MSITGPTBERTHFConfig):
|
| 345 |
+
super().__init__(config)
|
| 346 |
+
self.wte = nn.Embedding(config.vocab_size, config.d_model)
|
| 347 |
+
self.drop_emb = nn.Dropout(config.dropout)
|
| 348 |
+
self.blocks = nn.ModuleList([
|
| 349 |
+
MoEPMSITBlock(config.d_model, config.d_thin, config.num_blocks, config.capacity_factor)
|
| 350 |
+
for _ in range(config.num_layers)
|
| 351 |
+
])
|
| 352 |
+
self.ln_f = nn.LayerNorm(config.d_model)
|
| 353 |
+
self.post_init()
|
| 354 |
+
|
| 355 |
+
def forward(self, input_ids, **kwargs):
|
| 356 |
+
x = self.drop_emb(self.wte(input_ids))
|
| 357 |
+
for block in self.blocks:
|
| 358 |
+
x, _, _ = block(x, past_kvs=None, use_cache=False, bidirectional=False)
|
| 359 |
+
x = self.ln_f(x)
|
| 360 |
+
return BaseModelOutputWithPast(last_hidden_state=x)
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
class MSITGPTBERTForCausalLM(PreTrainedModel, GenerationMixin):
|
| 364 |
+
config_class = MSITGPTBERTHFConfig
|
| 365 |
+
base_model_prefix = "transformer"
|
| 366 |
+
_no_split_modules = ["MoEPMSITBlock"]
|
| 367 |
+
_tied_weights_keys = {"transformer.lm_head.weight": "transformer.wte.weight"}
|
| 368 |
+
|
| 369 |
+
def __init__(self, config: MSITGPTBERTHFConfig):
|
| 370 |
+
super().__init__(config)
|
| 371 |
+
self.transformer = MSITGPTBERTModelWrapper(config)
|
| 372 |
+
self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
|
| 373 |
+
self.post_init()
|
| 374 |
+
|
| 375 |
+
# State-dict pre-hook for backwards compatibility with checkpoint key naming
|
| 376 |
+
def _prefix_cleaner(state_dict, prefix, local_metadata, Moore, missing_keys, unexpected_keys, error_msgs):
|
| 377 |
+
keys = list(state_dict.keys())
|
| 378 |
+
for k in keys:
|
| 379 |
+
if k.startswith("transformer."):
|
| 380 |
+
state_dict[k.replace("transformer.", "", 1)] = state_dict.pop(k)
|
| 381 |
+
elif f"{prefix}transformer." in k:
|
| 382 |
+
state_dict[k.replace("transformer.", "", 1)] = state_dict.pop(k)
|
| 383 |
+
|
| 384 |
+
self._register_load_state_dict_pre_hook(_prefix_cleaner)
|
| 385 |
+
|
| 386 |
+
def tie_weights(self, **kwargs):
|
| 387 |
+
if hasattr(self, "transformer") and hasattr(self.transformer, "wte") and hasattr(self.transformer, "lm_head"):
|
| 388 |
+
self.transformer.wte.weight = self.lm_head.weight
|
| 389 |
+
|
| 390 |
+
def get_input_embeddings(self):
|
| 391 |
+
return self.transformer.wte
|
| 392 |
+
|
| 393 |
+
def set_input_embeddings(self, new_embeddings):
|
| 394 |
+
self.transformer.wte = new_embeddings
|
| 395 |
+
|
| 396 |
+
def get_output_embeddings(self):
|
| 397 |
+
return self.lm_head
|
| 398 |
+
|
| 399 |
+
def set_output_embeddings(self, new_embeddings):
|
| 400 |
+
self.lm_head = new_embeddings
|
| 401 |
+
|
| 402 |
+
def forward(self,
|
| 403 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 404 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 405 |
+
labels: Optional[torch.LongTensor] = None,
|
| 406 |
+
**kwargs) -> CausalLMOutputWithPast:
|
| 407 |
+
outputs = self.transformer(input_ids)
|
| 408 |
+
hidden_states = outputs.last_hidden_state
|
| 409 |
+
logits = self.lm_head(hidden_states)
|
| 410 |
+
|
| 411 |
+
loss = None
|
| 412 |
+
if labels is not None:
|
| 413 |
+
shift_logits = logits[:, :-1, :].contiguous()
|
| 414 |
+
shift_labels = labels[:, 1:].contiguous()
|
| 415 |
+
loss = F.cross_entropy(
|
| 416 |
+
shift_logits.view(-1, self.config.vocab_size),
|
| 417 |
+
shift_labels.view(-1),
|
| 418 |
+
ignore_index=-100
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
return CausalLMOutputWithPast(
|
| 422 |
+
loss=loss,
|
| 423 |
+
logits=logits,
|
| 424 |
+
past_key_values=None,
|
| 425 |
+
hidden_states=None,
|
| 426 |
+
attentions=None,
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
def prepare_inputs_for_generation(self, input_ids, **kwargs):
|
| 430 |
+
return {"input_ids": input_ids}
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
# Register with auto-mapping
|
| 434 |
+
AutoConfig.register("msit_gptbert", MSITGPTBERTHFConfig)
|
| 435 |
+
AutoModel.register(MSITGPTBERTHFConfig, MSITGPTBERTModelWrapper)
|
| 436 |
+
AutoModelForCausalLM.register(MSITGPTBERTHFConfig, MSITGPTBERTForCausalLM)
|
chck_20M/pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e22551b2d00a44d2505c12a0c6fc60b46ef33ea855f3011ecaeafc971fd7757f
|
| 3 |
+
size 135253367
|
chck_20M/tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
chck_20M/tokenizer_config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "tokenizers",
|
| 3 |
+
"bos_token": "[CLS]",
|
| 4 |
+
"eos_token": "[SEP]",
|
| 5 |
+
"mask_token": "[MASK]",
|
| 6 |
+
"model_max_length": 1000000000000000019884624838656,
|
| 7 |
+
"pad_token": "[PAD]",
|
| 8 |
+
"tokenizer_class": "TokenizersBackend",
|
| 9 |
+
"unk_token": "[UNK]"
|
| 10 |
+
}
|
chck_2M/config.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"auto_map": {
|
| 3 |
+
"AutoConfig": "modeling_msit.MSITGPTBERTHFConfig",
|
| 4 |
+
"AutoModel": "modeling_msit.MSITGPTBERTModelWrapper",
|
| 5 |
+
"AutoModelForCausalLM": "modeling_msit.MSITGPTBERTForCausalLM"
|
| 6 |
+
},
|
| 7 |
+
"vocab_size": 16384,
|
| 8 |
+
"block_size": 512,
|
| 9 |
+
"d_model": 384,
|
| 10 |
+
"hidden_size": 384,
|
| 11 |
+
"d_thin": 192,
|
| 12 |
+
"num_layers": 6,
|
| 13 |
+
"num_blocks": 6,
|
| 14 |
+
"capacity_factor": 2.0,
|
| 15 |
+
"dropout": 0.1,
|
| 16 |
+
"model_type": "msit_gptbert"
|
| 17 |
+
}
|
chck_2M/configuration_msit.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
|
| 3 |
+
class MSITGPTBERTHFConfig(PretrainedConfig):
|
| 4 |
+
model_type = "msit_gptbert"
|
| 5 |
+
|
| 6 |
+
def __init__(
|
| 7 |
+
self,
|
| 8 |
+
vocab_size: int = 16384,
|
| 9 |
+
block_size: int = 512,
|
| 10 |
+
d_model: int = 384,
|
| 11 |
+
d_thin: int = 192,
|
| 12 |
+
num_layers: int = 6,
|
| 13 |
+
num_blocks: int = 6,
|
| 14 |
+
capacity_factor: float = 2.0,
|
| 15 |
+
dropout: float = 0.1,
|
| 16 |
+
**kwargs
|
| 17 |
+
):
|
| 18 |
+
kwargs.setdefault("is_decoder", True)
|
| 19 |
+
kwargs.setdefault("bos_token_id", 2) # [CLS]
|
| 20 |
+
kwargs.setdefault("eos_token_id", 3) # [SEP]
|
| 21 |
+
kwargs.setdefault("pad_token_id", 1) # [PAD]
|
| 22 |
+
|
| 23 |
+
self.vocab_size = vocab_size
|
| 24 |
+
self.block_size = block_size
|
| 25 |
+
self.d_model = d_model
|
| 26 |
+
self.d_thin = d_thin
|
| 27 |
+
self.num_layers = num_layers
|
| 28 |
+
self.num_blocks = num_blocks
|
| 29 |
+
self.capacity_factor = capacity_factor
|
| 30 |
+
self.dropout = dropout
|
| 31 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import math
|
| 3 |
+
import random
|
| 4 |
+
import inspect
|
| 5 |
+
from typing import Optional, Tuple, Dict, Any
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
|
| 12 |
+
from transformers import PretrainedConfig, PreTrainedModel, GenerationMixin, AutoConfig, AutoModel, AutoModelForCausalLM
|
| 13 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 14 |
+
|
| 15 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 16 |
+
# Configuration Classes
|
| 17 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 18 |
+
|
| 19 |
+
@dataclass
|
| 20 |
+
class MSITGPTBERTConfig:
|
| 21 |
+
vocab_size: int = 16384
|
| 22 |
+
block_size: int = 512
|
| 23 |
+
d_model: int = 384
|
| 24 |
+
d_thin: int = 192
|
| 25 |
+
num_layers: int = 6
|
| 26 |
+
num_blocks: int = 6
|
| 27 |
+
capacity_factor: float = 2.0
|
| 28 |
+
dropout: float = 0.1
|
| 29 |
+
|
| 30 |
+
class MSITGPTBERTHFConfig(PretrainedConfig):
|
| 31 |
+
model_type = "msit_gptbert"
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self,
|
| 35 |
+
vocab_size: int = 16384,
|
| 36 |
+
block_size: int = 512,
|
| 37 |
+
d_model: int = 384,
|
| 38 |
+
d_thin: int = 192,
|
| 39 |
+
num_layers: int = 6,
|
| 40 |
+
num_blocks: int = 6,
|
| 41 |
+
capacity_factor: float = 2.0,
|
| 42 |
+
dropout: float = 0.1,
|
| 43 |
+
**kwargs
|
| 44 |
+
):
|
| 45 |
+
kwargs.setdefault("is_decoder", True)
|
| 46 |
+
kwargs.setdefault("bos_token_id", 2) # [CLS]
|
| 47 |
+
kwargs.setdefault("eos_token_id", 3) # [SEP]
|
| 48 |
+
kwargs.setdefault("pad_token_id", 1) # [PAD]
|
| 49 |
+
|
| 50 |
+
self.vocab_size = vocab_size
|
| 51 |
+
self.block_size = block_size
|
| 52 |
+
self.d_model = d_model
|
| 53 |
+
self.d_thin = d_thin
|
| 54 |
+
self.num_layers = num_layers
|
| 55 |
+
self.num_blocks = num_blocks
|
| 56 |
+
self.capacity_factor = capacity_factor
|
| 57 |
+
self.dropout = dropout
|
| 58 |
+
|
| 59 |
+
# Attribute parity for classification heads
|
| 60 |
+
self.hidden_size = d_model
|
| 61 |
+
|
| 62 |
+
super().__init__(**kwargs)
|
| 63 |
+
|
| 64 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 65 |
+
# ROPE HELPERS
|
| 66 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 67 |
+
|
| 68 |
+
def _precompute_rope_freqs(head_dim: int, seq_len: int, device: torch.device, theta: float = 10000.0):
|
| 69 |
+
assert head_dim % 2 == 0, "head_dim must be divisible by 2 for RoPE"
|
| 70 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim))
|
| 71 |
+
t = torch.arange(seq_len, device=device).float()
|
| 72 |
+
freqs = torch.outer(t, inv_freq)
|
| 73 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 74 |
+
return emb.cos(), emb.sin()
|
| 75 |
+
|
| 76 |
+
def _apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor):
|
| 77 |
+
L = x.size(2)
|
| 78 |
+
cos = cos[:L, :].unsqueeze(0).unsqueeze(1)
|
| 79 |
+
sin = sin[:L, :].unsqueeze(0).unsqueeze(1)
|
| 80 |
+
|
| 81 |
+
half_dim = x.size(-1) // 2
|
| 82 |
+
x1 = x[..., :half_dim]
|
| 83 |
+
x2 = x[..., half_dim:]
|
| 84 |
+
rotated_x = torch.cat((-x2, x1), dim=-1)
|
| 85 |
+
|
| 86 |
+
return (x * cos) + (rotated_x * sin)
|
| 87 |
+
|
| 88 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 89 |
+
# 1. SLIDING WINDOW ATTENTION
|
| 90 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 91 |
+
|
| 92 |
+
class SlidingWindowAttention(nn.Module):
|
| 93 |
+
def __init__(self, dim: int, num_heads: int, window_size=None):
|
| 94 |
+
super().__init__()
|
| 95 |
+
assert dim % num_heads == 0, "dim must be divisible by num_heads"
|
| 96 |
+
self.num_heads = num_heads
|
| 97 |
+
self.window_size = window_size
|
| 98 |
+
self.head_dim = dim // num_heads
|
| 99 |
+
|
| 100 |
+
self.q_proj = nn.Linear(dim, dim, bias=False)
|
| 101 |
+
self.k_proj = nn.Linear(dim, dim, bias=False)
|
| 102 |
+
self.v_proj = nn.Linear(dim, dim, bias=False)
|
| 103 |
+
self.o_proj = nn.Linear(dim, dim, bias=False)
|
| 104 |
+
|
| 105 |
+
def forward(self, x: torch.Tensor,
|
| 106 |
+
past_kv=None,
|
| 107 |
+
use_cache: bool = False,
|
| 108 |
+
bidirectional: bool = False):
|
| 109 |
+
B, L, D = x.size()
|
| 110 |
+
|
| 111 |
+
q = self.q_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 112 |
+
k = self.k_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 113 |
+
v = self.v_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 114 |
+
|
| 115 |
+
if past_kv is not None:
|
| 116 |
+
past_k, past_v = past_kv
|
| 117 |
+
past_len = past_k.size(2)
|
| 118 |
+
q_cos, q_sin = _precompute_rope_freqs(self.head_dim, past_len + L, x.device)
|
| 119 |
+
q = _apply_rope(q, q_cos[past_len:, :], q_sin[past_len:, :])
|
| 120 |
+
k = _apply_rope(k, q_cos[past_len:, :], q_sin[past_len:, :])
|
| 121 |
+
|
| 122 |
+
k = torch.cat([past_k, k], dim=2)
|
| 123 |
+
v = torch.cat([past_v, v], dim=2)
|
| 124 |
+
else:
|
| 125 |
+
cos, sin = _precompute_rope_freqs(self.head_dim, L, x.device)
|
| 126 |
+
q = _apply_rope(q, cos, sin)
|
| 127 |
+
k = _apply_rope(k, cos, sin)
|
| 128 |
+
|
| 129 |
+
L_kv = k.size(2)
|
| 130 |
+
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
|
| 131 |
+
|
| 132 |
+
if bidirectional:
|
| 133 |
+
if self.window_size is not None:
|
| 134 |
+
past_len = L_kv - L
|
| 135 |
+
pos_i = (past_len + torch.arange(L, device=x.device)).unsqueeze(1)
|
| 136 |
+
pos_j = torch.arange(L_kv, device=x.device).unsqueeze(0)
|
| 137 |
+
dist = torch.abs(pos_i - pos_j)
|
| 138 |
+
win_mask = dist < self.window_size
|
| 139 |
+
scores = scores.masked_fill(
|
| 140 |
+
~win_mask.unsqueeze(0).unsqueeze(0), float('-inf')
|
| 141 |
+
)
|
| 142 |
+
else:
|
| 143 |
+
past_len = L_kv - L
|
| 144 |
+
pos_i = (past_len + torch.arange(L, device=x.device)).unsqueeze(1)
|
| 145 |
+
pos_j = torch.arange(L_kv, device=x.device).unsqueeze(0)
|
| 146 |
+
dist = pos_i - pos_j
|
| 147 |
+
|
| 148 |
+
causal_mask = dist >= 0
|
| 149 |
+
if self.window_size is not None:
|
| 150 |
+
causal_mask = causal_mask & (dist < self.window_size)
|
| 151 |
+
|
| 152 |
+
scores = scores.masked_fill(
|
| 153 |
+
~causal_mask.unsqueeze(0).unsqueeze(0), float('-inf')
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
attn = torch.softmax(scores, dim=-1)
|
| 157 |
+
out = torch.matmul(attn, v)
|
| 158 |
+
out = out.transpose(1, 2).contiguous().view(B, L, D)
|
| 159 |
+
out = self.o_proj(out)
|
| 160 |
+
|
| 161 |
+
if use_cache:
|
| 162 |
+
if self.window_size is not None:
|
| 163 |
+
present_kv = (
|
| 164 |
+
k[:, :, -self.window_size:, :],
|
| 165 |
+
v[:, :, -self.window_size:, :]
|
| 166 |
+
)
|
| 167 |
+
else:
|
| 168 |
+
present_kv = (k, v)
|
| 169 |
+
else:
|
| 170 |
+
present_kv = None
|
| 171 |
+
|
| 172 |
+
return out, present_kv
|
| 173 |
+
|
| 174 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 175 |
+
# 2. MSIT BRANCH BLOCK (Pre-Norm)
|
| 176 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 177 |
+
|
| 178 |
+
class MSITBranchBlock(nn.Module):
|
| 179 |
+
def __init__(self, dim: int, num_heads: int, window_size):
|
| 180 |
+
super().__init__()
|
| 181 |
+
self.ln1 = nn.LayerNorm(dim)
|
| 182 |
+
self.attn = SlidingWindowAttention(dim, num_heads, window_size)
|
| 183 |
+
self.ln2 = nn.LayerNorm(dim)
|
| 184 |
+
self.ffn = nn.Sequential(
|
| 185 |
+
nn.Linear(dim, dim * 4, bias=False),
|
| 186 |
+
nn.GELU(),
|
| 187 |
+
nn.Linear(dim * 4, dim, bias=False),
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
def forward(self, x: torch.Tensor,
|
| 191 |
+
past_kv=None,
|
| 192 |
+
use_cache: bool = False,
|
| 193 |
+
bidirectional: bool = False):
|
| 194 |
+
attn_out, present_kv = self.attn(
|
| 195 |
+
self.ln1(x), past_kv, use_cache, bidirectional
|
| 196 |
+
)
|
| 197 |
+
x = x + attn_out
|
| 198 |
+
x = x + self.ffn(self.ln2(x))
|
| 199 |
+
return x, present_kv
|
| 200 |
+
|
| 201 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 202 |
+
# 3. MoEP-MSIT ARCHITECTURE BLOCK (Expert Choice routing)
|
| 203 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 204 |
+
|
| 205 |
+
class MoEPMSITBlock(nn.Module):
|
| 206 |
+
def __init__(self, d_model: int = 512, d_thin: int = 192, num_blocks: int = 14,
|
| 207 |
+
capacity_factor: float = 2.0):
|
| 208 |
+
super().__init__()
|
| 209 |
+
self.d_model = d_model
|
| 210 |
+
self.d_thin = d_thin
|
| 211 |
+
self.num_blocks = num_blocks
|
| 212 |
+
self.capacity_factor = capacity_factor
|
| 213 |
+
|
| 214 |
+
# 1. Global Block (Dense, d_model)
|
| 215 |
+
num_heads_global = max(1, d_model // 64)
|
| 216 |
+
self.global_block = MSITBranchBlock(d_model, num_heads_global, window_size=None)
|
| 217 |
+
|
| 218 |
+
# 2. Router
|
| 219 |
+
self.router_ln = nn.LayerNorm(d_model)
|
| 220 |
+
self.w_router = nn.Linear(d_model, num_blocks, bias=False)
|
| 221 |
+
|
| 222 |
+
# 3. Shrink Projection
|
| 223 |
+
self.w_down = nn.Linear(d_model, d_thin, bias=False)
|
| 224 |
+
|
| 225 |
+
# 4. Thin Parallel Blocks (d_thin)
|
| 226 |
+
self.windows = [None, 16, 8, 4, 2] + [None] * (num_blocks - 5)
|
| 227 |
+
self.heads = [max(1, d_thin // 64)] * num_blocks
|
| 228 |
+
|
| 229 |
+
self.thin_blocks = nn.ModuleList([
|
| 230 |
+
MSITBranchBlock(d_thin, self.heads[i], self.windows[i])
|
| 231 |
+
for i in range(num_blocks)
|
| 232 |
+
])
|
| 233 |
+
|
| 234 |
+
# 6. Grow Projection
|
| 235 |
+
self.w_up = nn.Linear(d_thin, d_model, bias=False)
|
| 236 |
+
self.last_topk_indices = None
|
| 237 |
+
|
| 238 |
+
def forward(self, x_0: torch.Tensor, past_kvs=None, use_cache: bool = False, bidirectional: bool = False):
|
| 239 |
+
B, T, D = x_0.size()
|
| 240 |
+
n_tokens = B * T
|
| 241 |
+
|
| 242 |
+
# Step 1: Global Block
|
| 243 |
+
pkv_g = past_kvs[0] if past_kvs else None
|
| 244 |
+
x_1, nkv_g = self.global_block(x_0, pkv_g, use_cache, bidirectional)
|
| 245 |
+
|
| 246 |
+
# Step 2: Gated input stream
|
| 247 |
+
x_2 = x_1 + x_0
|
| 248 |
+
|
| 249 |
+
# Router scores
|
| 250 |
+
r_logits = self.w_router(self.router_ln(x_2)).view(n_tokens, self.num_blocks)
|
| 251 |
+
r_probs = F.softmax(r_logits, dim=-1)
|
| 252 |
+
|
| 253 |
+
# Per-expert capacity: k = (n * c) / e
|
| 254 |
+
k_capacity = max(1, int(round(n_tokens * self.capacity_factor / self.num_blocks)))
|
| 255 |
+
k_capacity = min(k_capacity, n_tokens)
|
| 256 |
+
|
| 257 |
+
# Expert Choice routing: topk over the token axis for each expert
|
| 258 |
+
expert_token_scores = r_probs.transpose(0, 1) # (num_blocks, n_tokens)
|
| 259 |
+
topk_scores, topk_token_idx = torch.topk(expert_token_scores, k_capacity, dim=-1)
|
| 260 |
+
self.last_topk_indices = topk_token_idx
|
| 261 |
+
|
| 262 |
+
# Load balancing is guaranteed by construction in Expert Choice
|
| 263 |
+
layer_aux_loss = x_2.new_zeros(())
|
| 264 |
+
|
| 265 |
+
# Shrink projection
|
| 266 |
+
x_2_thin = self.w_down(x_2) # (B, T, d_thin)
|
| 267 |
+
x_2_thin_flat = x_2_thin.view(n_tokens, self.d_thin)
|
| 268 |
+
|
| 269 |
+
# Expert computations
|
| 270 |
+
new_kvs = [nkv_g]
|
| 271 |
+
expert_outputs_flat = torch.zeros(n_tokens, self.d_model, device=x_2.device, dtype=x_2.dtype)
|
| 272 |
+
|
| 273 |
+
for i, block in enumerate(self.thin_blocks):
|
| 274 |
+
sel_idx = topk_token_idx[i]
|
| 275 |
+
bucket_in = x_2_thin_flat[sel_idx].unsqueeze(0) # (1, k_capacity, d_thin)
|
| 276 |
+
|
| 277 |
+
pkv_i = past_kvs[i + 1] if past_kvs else None
|
| 278 |
+
bucket_out, nkv_i = block(bucket_in, pkv_i, use_cache, bidirectional)
|
| 279 |
+
if use_cache:
|
| 280 |
+
new_kvs.append(nkv_i)
|
| 281 |
+
|
| 282 |
+
bucket_out = bucket_out.squeeze(0) # (k_capacity, d_thin)
|
| 283 |
+
bucket_out_full = self.w_up(bucket_out) # (k_capacity, d_model)
|
| 284 |
+
|
| 285 |
+
gate = topk_scores[i].unsqueeze(-1) # (k_capacity, 1)
|
| 286 |
+
expert_outputs_flat.index_add_(0, sel_idx, bucket_out_full * gate)
|
| 287 |
+
|
| 288 |
+
x_3_full = expert_outputs_flat.view(B, T, self.d_model)
|
| 289 |
+
out = x_2 + x_3_full
|
| 290 |
+
|
| 291 |
+
present_kvs = tuple(new_kvs) if use_cache else None
|
| 292 |
+
return out, present_kvs, layer_aux_loss
|
| 293 |
+
|
| 294 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 295 |
+
# 4. RAW MSIT-GPT-BERT MODEL
|
| 296 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 297 |
+
|
| 298 |
+
class MSITGPTBERTModel(nn.Module):
|
| 299 |
+
def __init__(self, cfg):
|
| 300 |
+
super().__init__()
|
| 301 |
+
self.cfg = cfg
|
| 302 |
+
self.wte = nn.Embedding(cfg.vocab_size, cfg.d_model)
|
| 303 |
+
self.drop_emb = nn.Dropout(cfg.dropout)
|
| 304 |
+
self.blocks = nn.ModuleList([
|
| 305 |
+
MoEPMSITBlock(
|
| 306 |
+
d_model=cfg.d_model,
|
| 307 |
+
d_thin=cfg.d_thin,
|
| 308 |
+
num_blocks=cfg.num_blocks,
|
| 309 |
+
capacity_factor=cfg.capacity_factor
|
| 310 |
+
)
|
| 311 |
+
for _ in range(cfg.num_layers)
|
| 312 |
+
])
|
| 313 |
+
self.ln_f = nn.LayerNorm(cfg.d_model)
|
| 314 |
+
self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
|
| 315 |
+
self.wte.weight = self.lm_head.weight
|
| 316 |
+
|
| 317 |
+
def forward(self, input_ids: torch.Tensor, targets: torch.Tensor = None, bidirectional: bool = False):
|
| 318 |
+
x = self.drop_emb(self.wte(input_ids))
|
| 319 |
+
total_aux_loss = 0.0
|
| 320 |
+
|
| 321 |
+
for block in self.blocks:
|
| 322 |
+
x, _, layer_aux = block(x, past_kvs=None, use_cache=False, bidirectional=bidirectional)
|
| 323 |
+
total_aux_loss += layer_aux
|
| 324 |
+
|
| 325 |
+
x = self.ln_f(x)
|
| 326 |
+
logits = self.lm_head(x)
|
| 327 |
+
|
| 328 |
+
loss = None
|
| 329 |
+
if targets is not None:
|
| 330 |
+
ce_loss = F.cross_entropy(logits.view(-1, self.cfg.vocab_size), targets.view(-1), ignore_index=-100)
|
| 331 |
+
avg_aux_loss = total_aux_loss / self.cfg.num_layers
|
| 332 |
+
loss = ce_loss + (0.01 * avg_aux_loss)
|
| 333 |
+
|
| 334 |
+
return logits, loss
|
| 335 |
+
|
| 336 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 337 |
+
# 5. HUGGING FACE MODEL WRAPPERS
|
| 338 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 339 |
+
|
| 340 |
+
class MSITGPTBERTModelWrapper(PreTrainedModel):
|
| 341 |
+
config_class = MSITGPTBERTHFConfig
|
| 342 |
+
base_model_prefix = "transformer"
|
| 343 |
+
|
| 344 |
+
def __init__(self, config: MSITGPTBERTHFConfig):
|
| 345 |
+
super().__init__(config)
|
| 346 |
+
self.wte = nn.Embedding(config.vocab_size, config.d_model)
|
| 347 |
+
self.drop_emb = nn.Dropout(config.dropout)
|
| 348 |
+
self.blocks = nn.ModuleList([
|
| 349 |
+
MoEPMSITBlock(config.d_model, config.d_thin, config.num_blocks, config.capacity_factor)
|
| 350 |
+
for _ in range(config.num_layers)
|
| 351 |
+
])
|
| 352 |
+
self.ln_f = nn.LayerNorm(config.d_model)
|
| 353 |
+
self.post_init()
|
| 354 |
+
|
| 355 |
+
def forward(self, input_ids, **kwargs):
|
| 356 |
+
x = self.drop_emb(self.wte(input_ids))
|
| 357 |
+
for block in self.blocks:
|
| 358 |
+
x, _, _ = block(x, past_kvs=None, use_cache=False, bidirectional=False)
|
| 359 |
+
x = self.ln_f(x)
|
| 360 |
+
return BaseModelOutputWithPast(last_hidden_state=x)
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
class MSITGPTBERTForCausalLM(PreTrainedModel, GenerationMixin):
|
| 364 |
+
config_class = MSITGPTBERTHFConfig
|
| 365 |
+
base_model_prefix = "transformer"
|
| 366 |
+
_no_split_modules = ["MoEPMSITBlock"]
|
| 367 |
+
_tied_weights_keys = {"transformer.lm_head.weight": "transformer.wte.weight"}
|
| 368 |
+
|
| 369 |
+
def __init__(self, config: MSITGPTBERTHFConfig):
|
| 370 |
+
super().__init__(config)
|
| 371 |
+
self.transformer = MSITGPTBERTModelWrapper(config)
|
| 372 |
+
self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
|
| 373 |
+
self.post_init()
|
| 374 |
+
|
| 375 |
+
# State-dict pre-hook for backwards compatibility with checkpoint key naming
|
| 376 |
+
def _prefix_cleaner(state_dict, prefix, local_metadata, Moore, missing_keys, unexpected_keys, error_msgs):
|
| 377 |
+
keys = list(state_dict.keys())
|
| 378 |
+
for k in keys:
|
| 379 |
+
if k.startswith("transformer."):
|
| 380 |
+
state_dict[k.replace("transformer.", "", 1)] = state_dict.pop(k)
|
| 381 |
+
elif f"{prefix}transformer." in k:
|
| 382 |
+
state_dict[k.replace("transformer.", "", 1)] = state_dict.pop(k)
|
| 383 |
+
|
| 384 |
+
self._register_load_state_dict_pre_hook(_prefix_cleaner)
|
| 385 |
+
|
| 386 |
+
def tie_weights(self, **kwargs):
|
| 387 |
+
if hasattr(self, "transformer") and hasattr(self.transformer, "wte") and hasattr(self.transformer, "lm_head"):
|
| 388 |
+
self.transformer.wte.weight = self.lm_head.weight
|
| 389 |
+
|
| 390 |
+
def get_input_embeddings(self):
|
| 391 |
+
return self.transformer.wte
|
| 392 |
+
|
| 393 |
+
def set_input_embeddings(self, new_embeddings):
|
| 394 |
+
self.transformer.wte = new_embeddings
|
| 395 |
+
|
| 396 |
+
def get_output_embeddings(self):
|
| 397 |
+
return self.lm_head
|
| 398 |
+
|
| 399 |
+
def set_output_embeddings(self, new_embeddings):
|
| 400 |
+
self.lm_head = new_embeddings
|
| 401 |
+
|
| 402 |
+
def forward(self,
|
| 403 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 404 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 405 |
+
labels: Optional[torch.LongTensor] = None,
|
| 406 |
+
**kwargs) -> CausalLMOutputWithPast:
|
| 407 |
+
outputs = self.transformer(input_ids)
|
| 408 |
+
hidden_states = outputs.last_hidden_state
|
| 409 |
+
logits = self.lm_head(hidden_states)
|
| 410 |
+
|
| 411 |
+
loss = None
|
| 412 |
+
if labels is not None:
|
| 413 |
+
shift_logits = logits[:, :-1, :].contiguous()
|
| 414 |
+
shift_labels = labels[:, 1:].contiguous()
|
| 415 |
+
loss = F.cross_entropy(
|
| 416 |
+
shift_logits.view(-1, self.config.vocab_size),
|
| 417 |
+
shift_labels.view(-1),
|
| 418 |
+
ignore_index=-100
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
return CausalLMOutputWithPast(
|
| 422 |
+
loss=loss,
|
| 423 |
+
logits=logits,
|
| 424 |
+
past_key_values=None,
|
| 425 |
+
hidden_states=None,
|
| 426 |
+
attentions=None,
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
def prepare_inputs_for_generation(self, input_ids, **kwargs):
|
| 430 |
+
return {"input_ids": input_ids}
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
# Register with auto-mapping
|
| 434 |
+
AutoConfig.register("msit_gptbert", MSITGPTBERTHFConfig)
|
| 435 |
+
AutoModel.register(MSITGPTBERTHFConfig, MSITGPTBERTModelWrapper)
|
| 436 |
+
AutoModelForCausalLM.register(MSITGPTBERTHFConfig, MSITGPTBERTForCausalLM)
|
chck_2M/pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5fdf475fe580ea214169e2c3e045292c861db6c936c7a56c078af0eb4f1fcf05
|
| 3 |
+
size 135253367
|
chck_2M/tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
chck_2M/tokenizer_config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "tokenizers",
|
| 3 |
+
"bos_token": "[CLS]",
|
| 4 |
+
"eos_token": "[SEP]",
|
| 5 |
+
"mask_token": "[MASK]",
|
| 6 |
+
"model_max_length": 1000000000000000019884624838656,
|
| 7 |
+
"pad_token": "[PAD]",
|
| 8 |
+
"tokenizer_class": "TokenizersBackend",
|
| 9 |
+
"unk_token": "[UNK]"
|
| 10 |
+
}
|
chck_30M/config.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"auto_map": {
|
| 3 |
+
"AutoConfig": "modeling_msit.MSITGPTBERTHFConfig",
|
| 4 |
+
"AutoModel": "modeling_msit.MSITGPTBERTModelWrapper",
|
| 5 |
+
"AutoModelForCausalLM": "modeling_msit.MSITGPTBERTForCausalLM"
|
| 6 |
+
},
|
| 7 |
+
"vocab_size": 16384,
|
| 8 |
+
"block_size": 512,
|
| 9 |
+
"d_model": 384,
|
| 10 |
+
"hidden_size": 384,
|
| 11 |
+
"d_thin": 192,
|
| 12 |
+
"num_layers": 6,
|
| 13 |
+
"num_blocks": 6,
|
| 14 |
+
"capacity_factor": 2.0,
|
| 15 |
+
"dropout": 0.1,
|
| 16 |
+
"model_type": "msit_gptbert"
|
| 17 |
+
}
|
chck_30M/configuration_msit.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
|
| 3 |
+
class MSITGPTBERTHFConfig(PretrainedConfig):
|
| 4 |
+
model_type = "msit_gptbert"
|
| 5 |
+
|
| 6 |
+
def __init__(
|
| 7 |
+
self,
|
| 8 |
+
vocab_size: int = 16384,
|
| 9 |
+
block_size: int = 512,
|
| 10 |
+
d_model: int = 384,
|
| 11 |
+
d_thin: int = 192,
|
| 12 |
+
num_layers: int = 6,
|
| 13 |
+
num_blocks: int = 6,
|
| 14 |
+
capacity_factor: float = 2.0,
|
| 15 |
+
dropout: float = 0.1,
|
| 16 |
+
**kwargs
|
| 17 |
+
):
|
| 18 |
+
kwargs.setdefault("is_decoder", True)
|
| 19 |
+
kwargs.setdefault("bos_token_id", 2) # [CLS]
|
| 20 |
+
kwargs.setdefault("eos_token_id", 3) # [SEP]
|
| 21 |
+
kwargs.setdefault("pad_token_id", 1) # [PAD]
|
| 22 |
+
|
| 23 |
+
self.vocab_size = vocab_size
|
| 24 |
+
self.block_size = block_size
|
| 25 |
+
self.d_model = d_model
|
| 26 |
+
self.d_thin = d_thin
|
| 27 |
+
self.num_layers = num_layers
|
| 28 |
+
self.num_blocks = num_blocks
|
| 29 |
+
self.capacity_factor = capacity_factor
|
| 30 |
+
self.dropout = dropout
|
| 31 |
+
|
| 32 |
+
# Attribute parity for classification heads
|
| 33 |
+
self.hidden_size = d_model
|
| 34 |
+
|
| 35 |
+
super().__init__(**kwargs)
|
chck_30M/modeling_msit.py
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import math
|
| 3 |
+
import random
|
| 4 |
+
import inspect
|
| 5 |
+
from typing import Optional, Tuple, Dict, Any
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
|
| 12 |
+
from transformers import PretrainedConfig, PreTrainedModel, GenerationMixin, AutoConfig, AutoModel, AutoModelForCausalLM
|
| 13 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 14 |
+
|
| 15 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 16 |
+
# Configuration Classes
|
| 17 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 18 |
+
|
| 19 |
+
@dataclass
|
| 20 |
+
class MSITGPTBERTConfig:
|
| 21 |
+
vocab_size: int = 16384
|
| 22 |
+
block_size: int = 512
|
| 23 |
+
d_model: int = 384
|
| 24 |
+
d_thin: int = 192
|
| 25 |
+
num_layers: int = 6
|
| 26 |
+
num_blocks: int = 6
|
| 27 |
+
capacity_factor: float = 2.0
|
| 28 |
+
dropout: float = 0.1
|
| 29 |
+
|
| 30 |
+
class MSITGPTBERTHFConfig(PretrainedConfig):
|
| 31 |
+
model_type = "msit_gptbert"
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self,
|
| 35 |
+
vocab_size: int = 16384,
|
| 36 |
+
block_size: int = 512,
|
| 37 |
+
d_model: int = 384,
|
| 38 |
+
d_thin: int = 192,
|
| 39 |
+
num_layers: int = 6,
|
| 40 |
+
num_blocks: int = 6,
|
| 41 |
+
capacity_factor: float = 2.0,
|
| 42 |
+
dropout: float = 0.1,
|
| 43 |
+
**kwargs
|
| 44 |
+
):
|
| 45 |
+
kwargs.setdefault("is_decoder", True)
|
| 46 |
+
kwargs.setdefault("bos_token_id", 2) # [CLS]
|
| 47 |
+
kwargs.setdefault("eos_token_id", 3) # [SEP]
|
| 48 |
+
kwargs.setdefault("pad_token_id", 1) # [PAD]
|
| 49 |
+
|
| 50 |
+
self.vocab_size = vocab_size
|
| 51 |
+
self.block_size = block_size
|
| 52 |
+
self.d_model = d_model
|
| 53 |
+
self.d_thin = d_thin
|
| 54 |
+
self.num_layers = num_layers
|
| 55 |
+
self.num_blocks = num_blocks
|
| 56 |
+
self.capacity_factor = capacity_factor
|
| 57 |
+
self.dropout = dropout
|
| 58 |
+
|
| 59 |
+
# Attribute parity for classification heads
|
| 60 |
+
self.hidden_size = d_model
|
| 61 |
+
|
| 62 |
+
super().__init__(**kwargs)
|
| 63 |
+
|
| 64 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 65 |
+
# ROPE HELPERS
|
| 66 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 67 |
+
|
| 68 |
+
def _precompute_rope_freqs(head_dim: int, seq_len: int, device: torch.device, theta: float = 10000.0):
|
| 69 |
+
assert head_dim % 2 == 0, "head_dim must be divisible by 2 for RoPE"
|
| 70 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim))
|
| 71 |
+
t = torch.arange(seq_len, device=device).float()
|
| 72 |
+
freqs = torch.outer(t, inv_freq)
|
| 73 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 74 |
+
return emb.cos(), emb.sin()
|
| 75 |
+
|
| 76 |
+
def _apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor):
|
| 77 |
+
L = x.size(2)
|
| 78 |
+
cos = cos[:L, :].unsqueeze(0).unsqueeze(1)
|
| 79 |
+
sin = sin[:L, :].unsqueeze(0).unsqueeze(1)
|
| 80 |
+
|
| 81 |
+
half_dim = x.size(-1) // 2
|
| 82 |
+
x1 = x[..., :half_dim]
|
| 83 |
+
x2 = x[..., half_dim:]
|
| 84 |
+
rotated_x = torch.cat((-x2, x1), dim=-1)
|
| 85 |
+
|
| 86 |
+
return (x * cos) + (rotated_x * sin)
|
| 87 |
+
|
| 88 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 89 |
+
# 1. SLIDING WINDOW ATTENTION
|
| 90 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 91 |
+
|
| 92 |
+
class SlidingWindowAttention(nn.Module):
|
| 93 |
+
def __init__(self, dim: int, num_heads: int, window_size=None):
|
| 94 |
+
super().__init__()
|
| 95 |
+
assert dim % num_heads == 0, "dim must be divisible by num_heads"
|
| 96 |
+
self.num_heads = num_heads
|
| 97 |
+
self.window_size = window_size
|
| 98 |
+
self.head_dim = dim // num_heads
|
| 99 |
+
|
| 100 |
+
self.q_proj = nn.Linear(dim, dim, bias=False)
|
| 101 |
+
self.k_proj = nn.Linear(dim, dim, bias=False)
|
| 102 |
+
self.v_proj = nn.Linear(dim, dim, bias=False)
|
| 103 |
+
self.o_proj = nn.Linear(dim, dim, bias=False)
|
| 104 |
+
|
| 105 |
+
def forward(self, x: torch.Tensor,
|
| 106 |
+
past_kv=None,
|
| 107 |
+
use_cache: bool = False,
|
| 108 |
+
bidirectional: bool = False):
|
| 109 |
+
B, L, D = x.size()
|
| 110 |
+
|
| 111 |
+
q = self.q_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 112 |
+
k = self.k_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 113 |
+
v = self.v_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 114 |
+
|
| 115 |
+
if past_kv is not None:
|
| 116 |
+
past_k, past_v = past_kv
|
| 117 |
+
past_len = past_k.size(2)
|
| 118 |
+
q_cos, q_sin = _precompute_rope_freqs(self.head_dim, past_len + L, x.device)
|
| 119 |
+
q = _apply_rope(q, q_cos[past_len:, :], q_sin[past_len:, :])
|
| 120 |
+
k = _apply_rope(k, q_cos[past_len:, :], q_sin[past_len:, :])
|
| 121 |
+
|
| 122 |
+
k = torch.cat([past_k, k], dim=2)
|
| 123 |
+
v = torch.cat([past_v, v], dim=2)
|
| 124 |
+
else:
|
| 125 |
+
cos, sin = _precompute_rope_freqs(self.head_dim, L, x.device)
|
| 126 |
+
q = _apply_rope(q, cos, sin)
|
| 127 |
+
k = _apply_rope(k, cos, sin)
|
| 128 |
+
|
| 129 |
+
L_kv = k.size(2)
|
| 130 |
+
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
|
| 131 |
+
|
| 132 |
+
if bidirectional:
|
| 133 |
+
if self.window_size is not None:
|
| 134 |
+
past_len = L_kv - L
|
| 135 |
+
pos_i = (past_len + torch.arange(L, device=x.device)).unsqueeze(1)
|
| 136 |
+
pos_j = torch.arange(L_kv, device=x.device).unsqueeze(0)
|
| 137 |
+
dist = torch.abs(pos_i - pos_j)
|
| 138 |
+
win_mask = dist < self.window_size
|
| 139 |
+
scores = scores.masked_fill(
|
| 140 |
+
~win_mask.unsqueeze(0).unsqueeze(0), float('-inf')
|
| 141 |
+
)
|
| 142 |
+
else:
|
| 143 |
+
past_len = L_kv - L
|
| 144 |
+
pos_i = (past_len + torch.arange(L, device=x.device)).unsqueeze(1)
|
| 145 |
+
pos_j = torch.arange(L_kv, device=x.device).unsqueeze(0)
|
| 146 |
+
dist = pos_i - pos_j
|
| 147 |
+
|
| 148 |
+
causal_mask = dist >= 0
|
| 149 |
+
if self.window_size is not None:
|
| 150 |
+
causal_mask = causal_mask & (dist < self.window_size)
|
| 151 |
+
|
| 152 |
+
scores = scores.masked_fill(
|
| 153 |
+
~causal_mask.unsqueeze(0).unsqueeze(0), float('-inf')
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
attn = torch.softmax(scores, dim=-1)
|
| 157 |
+
out = torch.matmul(attn, v)
|
| 158 |
+
out = out.transpose(1, 2).contiguous().view(B, L, D)
|
| 159 |
+
out = self.o_proj(out)
|
| 160 |
+
|
| 161 |
+
if use_cache:
|
| 162 |
+
if self.window_size is not None:
|
| 163 |
+
present_kv = (
|
| 164 |
+
k[:, :, -self.window_size:, :],
|
| 165 |
+
v[:, :, -self.window_size:, :]
|
| 166 |
+
)
|
| 167 |
+
else:
|
| 168 |
+
present_kv = (k, v)
|
| 169 |
+
else:
|
| 170 |
+
present_kv = None
|
| 171 |
+
|
| 172 |
+
return out, present_kv
|
| 173 |
+
|
| 174 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 175 |
+
# 2. MSIT BRANCH BLOCK (Pre-Norm)
|
| 176 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 177 |
+
|
| 178 |
+
class MSITBranchBlock(nn.Module):
|
| 179 |
+
def __init__(self, dim: int, num_heads: int, window_size):
|
| 180 |
+
super().__init__()
|
| 181 |
+
self.ln1 = nn.LayerNorm(dim)
|
| 182 |
+
self.attn = SlidingWindowAttention(dim, num_heads, window_size)
|
| 183 |
+
self.ln2 = nn.LayerNorm(dim)
|
| 184 |
+
self.ffn = nn.Sequential(
|
| 185 |
+
nn.Linear(dim, dim * 4, bias=False),
|
| 186 |
+
nn.GELU(),
|
| 187 |
+
nn.Linear(dim * 4, dim, bias=False),
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
def forward(self, x: torch.Tensor,
|
| 191 |
+
past_kv=None,
|
| 192 |
+
use_cache: bool = False,
|
| 193 |
+
bidirectional: bool = False):
|
| 194 |
+
attn_out, present_kv = self.attn(
|
| 195 |
+
self.ln1(x), past_kv, use_cache, bidirectional
|
| 196 |
+
)
|
| 197 |
+
x = x + attn_out
|
| 198 |
+
x = x + self.ffn(self.ln2(x))
|
| 199 |
+
return x, present_kv
|
| 200 |
+
|
| 201 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 202 |
+
# 3. MoEP-MSIT ARCHITECTURE BLOCK (Expert Choice routing)
|
| 203 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 204 |
+
|
| 205 |
+
class MoEPMSITBlock(nn.Module):
|
| 206 |
+
def __init__(self, d_model: int = 512, d_thin: int = 192, num_blocks: int = 14,
|
| 207 |
+
capacity_factor: float = 2.0):
|
| 208 |
+
super().__init__()
|
| 209 |
+
self.d_model = d_model
|
| 210 |
+
self.d_thin = d_thin
|
| 211 |
+
self.num_blocks = num_blocks
|
| 212 |
+
self.capacity_factor = capacity_factor
|
| 213 |
+
|
| 214 |
+
# 1. Global Block (Dense, d_model)
|
| 215 |
+
num_heads_global = max(1, d_model // 64)
|
| 216 |
+
self.global_block = MSITBranchBlock(d_model, num_heads_global, window_size=None)
|
| 217 |
+
|
| 218 |
+
# 2. Router
|
| 219 |
+
self.router_ln = nn.LayerNorm(d_model)
|
| 220 |
+
self.w_router = nn.Linear(d_model, num_blocks, bias=False)
|
| 221 |
+
|
| 222 |
+
# 3. Shrink Projection
|
| 223 |
+
self.w_down = nn.Linear(d_model, d_thin, bias=False)
|
| 224 |
+
|
| 225 |
+
# 4. Thin Parallel Blocks (d_thin)
|
| 226 |
+
self.windows = [None, 16, 8, 4, 2] + [None] * (num_blocks - 5)
|
| 227 |
+
self.heads = [max(1, d_thin // 64)] * num_blocks
|
| 228 |
+
|
| 229 |
+
self.thin_blocks = nn.ModuleList([
|
| 230 |
+
MSITBranchBlock(d_thin, self.heads[i], self.windows[i])
|
| 231 |
+
for i in range(num_blocks)
|
| 232 |
+
])
|
| 233 |
+
|
| 234 |
+
# 6. Grow Projection
|
| 235 |
+
self.w_up = nn.Linear(d_thin, d_model, bias=False)
|
| 236 |
+
self.last_topk_indices = None
|
| 237 |
+
|
| 238 |
+
def forward(self, x_0: torch.Tensor, past_kvs=None, use_cache: bool = False, bidirectional: bool = False):
|
| 239 |
+
B, T, D = x_0.size()
|
| 240 |
+
n_tokens = B * T
|
| 241 |
+
|
| 242 |
+
# Step 1: Global Block
|
| 243 |
+
pkv_g = past_kvs[0] if past_kvs else None
|
| 244 |
+
x_1, nkv_g = self.global_block(x_0, pkv_g, use_cache, bidirectional)
|
| 245 |
+
|
| 246 |
+
# Step 2: Gated input stream
|
| 247 |
+
x_2 = x_1 + x_0
|
| 248 |
+
|
| 249 |
+
# Router scores
|
| 250 |
+
r_logits = self.w_router(self.router_ln(x_2)).view(n_tokens, self.num_blocks)
|
| 251 |
+
r_probs = F.softmax(r_logits, dim=-1)
|
| 252 |
+
|
| 253 |
+
# Per-expert capacity: k = (n * c) / e
|
| 254 |
+
k_capacity = max(1, int(round(n_tokens * self.capacity_factor / self.num_blocks)))
|
| 255 |
+
k_capacity = min(k_capacity, n_tokens)
|
| 256 |
+
|
| 257 |
+
# Expert Choice routing: topk over the token axis for each expert
|
| 258 |
+
expert_token_scores = r_probs.transpose(0, 1) # (num_blocks, n_tokens)
|
| 259 |
+
topk_scores, topk_token_idx = torch.topk(expert_token_scores, k_capacity, dim=-1)
|
| 260 |
+
self.last_topk_indices = topk_token_idx
|
| 261 |
+
|
| 262 |
+
# Load balancing is guaranteed by construction in Expert Choice
|
| 263 |
+
layer_aux_loss = x_2.new_zeros(())
|
| 264 |
+
|
| 265 |
+
# Shrink projection
|
| 266 |
+
x_2_thin = self.w_down(x_2) # (B, T, d_thin)
|
| 267 |
+
x_2_thin_flat = x_2_thin.view(n_tokens, self.d_thin)
|
| 268 |
+
|
| 269 |
+
# Expert computations
|
| 270 |
+
new_kvs = [nkv_g]
|
| 271 |
+
expert_outputs_flat = torch.zeros(n_tokens, self.d_model, device=x_2.device, dtype=x_2.dtype)
|
| 272 |
+
|
| 273 |
+
for i, block in enumerate(self.thin_blocks):
|
| 274 |
+
sel_idx = topk_token_idx[i]
|
| 275 |
+
bucket_in = x_2_thin_flat[sel_idx].unsqueeze(0) # (1, k_capacity, d_thin)
|
| 276 |
+
|
| 277 |
+
pkv_i = past_kvs[i + 1] if past_kvs else None
|
| 278 |
+
bucket_out, nkv_i = block(bucket_in, pkv_i, use_cache, bidirectional)
|
| 279 |
+
if use_cache:
|
| 280 |
+
new_kvs.append(nkv_i)
|
| 281 |
+
|
| 282 |
+
bucket_out = bucket_out.squeeze(0) # (k_capacity, d_thin)
|
| 283 |
+
bucket_out_full = self.w_up(bucket_out) # (k_capacity, d_model)
|
| 284 |
+
|
| 285 |
+
gate = topk_scores[i].unsqueeze(-1) # (k_capacity, 1)
|
| 286 |
+
expert_outputs_flat.index_add_(0, sel_idx, bucket_out_full * gate)
|
| 287 |
+
|
| 288 |
+
x_3_full = expert_outputs_flat.view(B, T, self.d_model)
|
| 289 |
+
out = x_2 + x_3_full
|
| 290 |
+
|
| 291 |
+
present_kvs = tuple(new_kvs) if use_cache else None
|
| 292 |
+
return out, present_kvs, layer_aux_loss
|
| 293 |
+
|
| 294 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 295 |
+
# 4. RAW MSIT-GPT-BERT MODEL
|
| 296 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 297 |
+
|
| 298 |
+
class MSITGPTBERTModel(nn.Module):
|
| 299 |
+
def __init__(self, cfg):
|
| 300 |
+
super().__init__()
|
| 301 |
+
self.cfg = cfg
|
| 302 |
+
self.wte = nn.Embedding(cfg.vocab_size, cfg.d_model)
|
| 303 |
+
self.drop_emb = nn.Dropout(cfg.dropout)
|
| 304 |
+
self.blocks = nn.ModuleList([
|
| 305 |
+
MoEPMSITBlock(
|
| 306 |
+
d_model=cfg.d_model,
|
| 307 |
+
d_thin=cfg.d_thin,
|
| 308 |
+
num_blocks=cfg.num_blocks,
|
| 309 |
+
capacity_factor=cfg.capacity_factor
|
| 310 |
+
)
|
| 311 |
+
for _ in range(cfg.num_layers)
|
| 312 |
+
])
|
| 313 |
+
self.ln_f = nn.LayerNorm(cfg.d_model)
|
| 314 |
+
self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
|
| 315 |
+
self.wte.weight = self.lm_head.weight
|
| 316 |
+
|
| 317 |
+
def forward(self, input_ids: torch.Tensor, targets: torch.Tensor = None, bidirectional: bool = False):
|
| 318 |
+
x = self.drop_emb(self.wte(input_ids))
|
| 319 |
+
total_aux_loss = 0.0
|
| 320 |
+
|
| 321 |
+
for block in self.blocks:
|
| 322 |
+
x, _, layer_aux = block(x, past_kvs=None, use_cache=False, bidirectional=bidirectional)
|
| 323 |
+
total_aux_loss += layer_aux
|
| 324 |
+
|
| 325 |
+
x = self.ln_f(x)
|
| 326 |
+
logits = self.lm_head(x)
|
| 327 |
+
|
| 328 |
+
loss = None
|
| 329 |
+
if targets is not None:
|
| 330 |
+
ce_loss = F.cross_entropy(logits.view(-1, self.cfg.vocab_size), targets.view(-1), ignore_index=-100)
|
| 331 |
+
avg_aux_loss = total_aux_loss / self.cfg.num_layers
|
| 332 |
+
loss = ce_loss + (0.01 * avg_aux_loss)
|
| 333 |
+
|
| 334 |
+
return logits, loss
|
| 335 |
+
|
| 336 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 337 |
+
# 5. HUGGING FACE MODEL WRAPPERS
|
| 338 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 339 |
+
|
| 340 |
+
class MSITGPTBERTModelWrapper(PreTrainedModel):
|
| 341 |
+
config_class = MSITGPTBERTHFConfig
|
| 342 |
+
base_model_prefix = "transformer"
|
| 343 |
+
|
| 344 |
+
def __init__(self, config: MSITGPTBERTHFConfig):
|
| 345 |
+
super().__init__(config)
|
| 346 |
+
self.wte = nn.Embedding(config.vocab_size, config.d_model)
|
| 347 |
+
self.drop_emb = nn.Dropout(config.dropout)
|
| 348 |
+
self.blocks = nn.ModuleList([
|
| 349 |
+
MoEPMSITBlock(config.d_model, config.d_thin, config.num_blocks, config.capacity_factor)
|
| 350 |
+
for _ in range(config.num_layers)
|
| 351 |
+
])
|
| 352 |
+
self.ln_f = nn.LayerNorm(config.d_model)
|
| 353 |
+
self.post_init()
|
| 354 |
+
|
| 355 |
+
def forward(self, input_ids, **kwargs):
|
| 356 |
+
x = self.drop_emb(self.wte(input_ids))
|
| 357 |
+
for block in self.blocks:
|
| 358 |
+
x, _, _ = block(x, past_kvs=None, use_cache=False, bidirectional=False)
|
| 359 |
+
x = self.ln_f(x)
|
| 360 |
+
return BaseModelOutputWithPast(last_hidden_state=x)
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
class MSITGPTBERTForCausalLM(PreTrainedModel, GenerationMixin):
|
| 364 |
+
config_class = MSITGPTBERTHFConfig
|
| 365 |
+
base_model_prefix = "transformer"
|
| 366 |
+
_no_split_modules = ["MoEPMSITBlock"]
|
| 367 |
+
_tied_weights_keys = {"transformer.lm_head.weight": "transformer.wte.weight"}
|
| 368 |
+
|
| 369 |
+
def __init__(self, config: MSITGPTBERTHFConfig):
|
| 370 |
+
super().__init__(config)
|
| 371 |
+
self.transformer = MSITGPTBERTModelWrapper(config)
|
| 372 |
+
self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
|
| 373 |
+
self.post_init()
|
| 374 |
+
|
| 375 |
+
# State-dict pre-hook for backwards compatibility with checkpoint key naming
|
| 376 |
+
def _prefix_cleaner(state_dict, prefix, local_metadata, Moore, missing_keys, unexpected_keys, error_msgs):
|
| 377 |
+
keys = list(state_dict.keys())
|
| 378 |
+
for k in keys:
|
| 379 |
+
if k.startswith("transformer."):
|
| 380 |
+
state_dict[k.replace("transformer.", "", 1)] = state_dict.pop(k)
|
| 381 |
+
elif f"{prefix}transformer." in k:
|
| 382 |
+
state_dict[k.replace("transformer.", "", 1)] = state_dict.pop(k)
|
| 383 |
+
|
| 384 |
+
self._register_load_state_dict_pre_hook(_prefix_cleaner)
|
| 385 |
+
|
| 386 |
+
def tie_weights(self, **kwargs):
|
| 387 |
+
if hasattr(self, "transformer") and hasattr(self.transformer, "wte") and hasattr(self.transformer, "lm_head"):
|
| 388 |
+
self.transformer.wte.weight = self.lm_head.weight
|
| 389 |
+
|
| 390 |
+
def get_input_embeddings(self):
|
| 391 |
+
return self.transformer.wte
|
| 392 |
+
|
| 393 |
+
def set_input_embeddings(self, new_embeddings):
|
| 394 |
+
self.transformer.wte = new_embeddings
|
| 395 |
+
|
| 396 |
+
def get_output_embeddings(self):
|
| 397 |
+
return self.lm_head
|
| 398 |
+
|
| 399 |
+
def set_output_embeddings(self, new_embeddings):
|
| 400 |
+
self.lm_head = new_embeddings
|
| 401 |
+
|
| 402 |
+
def forward(self,
|
| 403 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 404 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 405 |
+
labels: Optional[torch.LongTensor] = None,
|
| 406 |
+
**kwargs) -> CausalLMOutputWithPast:
|
| 407 |
+
outputs = self.transformer(input_ids)
|
| 408 |
+
hidden_states = outputs.last_hidden_state
|
| 409 |
+
logits = self.lm_head(hidden_states)
|
| 410 |
+
|
| 411 |
+
loss = None
|
| 412 |
+
if labels is not None:
|
| 413 |
+
shift_logits = logits[:, :-1, :].contiguous()
|
| 414 |
+
shift_labels = labels[:, 1:].contiguous()
|
| 415 |
+
loss = F.cross_entropy(
|
| 416 |
+
shift_logits.view(-1, self.config.vocab_size),
|
| 417 |
+
shift_labels.view(-1),
|
| 418 |
+
ignore_index=-100
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
return CausalLMOutputWithPast(
|
| 422 |
+
loss=loss,
|
| 423 |
+
logits=logits,
|
| 424 |
+
past_key_values=None,
|
| 425 |
+
hidden_states=None,
|
| 426 |
+
attentions=None,
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
def prepare_inputs_for_generation(self, input_ids, **kwargs):
|
| 430 |
+
return {"input_ids": input_ids}
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
# Register with auto-mapping
|
| 434 |
+
AutoConfig.register("msit_gptbert", MSITGPTBERTHFConfig)
|
| 435 |
+
AutoModel.register(MSITGPTBERTHFConfig, MSITGPTBERTModelWrapper)
|
| 436 |
+
AutoModelForCausalLM.register(MSITGPTBERTHFConfig, MSITGPTBERTForCausalLM)
|
chck_30M/pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c248b6eca5aa60f92a60427b5823138d44b307945c3c314c0fadbfc2a8551bde
|
| 3 |
+
size 135253367
|
chck_30M/tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
chck_30M/tokenizer_config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "tokenizers",
|
| 3 |
+
"bos_token": "[CLS]",
|
| 4 |
+
"eos_token": "[SEP]",
|
| 5 |
+
"mask_token": "[MASK]",
|
| 6 |
+
"model_max_length": 1000000000000000019884624838656,
|
| 7 |
+
"pad_token": "[PAD]",
|
| 8 |
+
"tokenizer_class": "TokenizersBackend",
|
| 9 |
+
"unk_token": "[UNK]"
|
| 10 |
+
}
|
chck_3M/config.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"auto_map": {
|
| 3 |
+
"AutoConfig": "modeling_msit.MSITGPTBERTHFConfig",
|
| 4 |
+
"AutoModel": "modeling_msit.MSITGPTBERTModelWrapper",
|
| 5 |
+
"AutoModelForCausalLM": "modeling_msit.MSITGPTBERTForCausalLM"
|
| 6 |
+
},
|
| 7 |
+
"vocab_size": 16384,
|
| 8 |
+
"block_size": 512,
|
| 9 |
+
"d_model": 384,
|
| 10 |
+
"hidden_size": 384,
|
| 11 |
+
"d_thin": 192,
|
| 12 |
+
"num_layers": 6,
|
| 13 |
+
"num_blocks": 6,
|
| 14 |
+
"capacity_factor": 2.0,
|
| 15 |
+
"dropout": 0.1,
|
| 16 |
+
"model_type": "msit_gptbert"
|
| 17 |
+
}
|
chck_3M/configuration_msit.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
|
| 3 |
+
class MSITGPTBERTHFConfig(PretrainedConfig):
|
| 4 |
+
model_type = "msit_gptbert"
|
| 5 |
+
|
| 6 |
+
def __init__(
|
| 7 |
+
self,
|
| 8 |
+
vocab_size: int = 16384,
|
| 9 |
+
block_size: int = 512,
|
| 10 |
+
d_model: int = 384,
|
| 11 |
+
d_thin: int = 192,
|
| 12 |
+
num_layers: int = 6,
|
| 13 |
+
num_blocks: int = 6,
|
| 14 |
+
capacity_factor: float = 2.0,
|
| 15 |
+
dropout: float = 0.1,
|
| 16 |
+
**kwargs
|
| 17 |
+
):
|
| 18 |
+
kwargs.setdefault("is_decoder", True)
|
| 19 |
+
kwargs.setdefault("bos_token_id", 2) # [CLS]
|
| 20 |
+
kwargs.setdefault("eos_token_id", 3) # [SEP]
|
| 21 |
+
kwargs.setdefault("pad_token_id", 1) # [PAD]
|
| 22 |
+
|
| 23 |
+
self.vocab_size = vocab_size
|
| 24 |
+
self.block_size = block_size
|
| 25 |
+
self.d_model = d_model
|
| 26 |
+
self.d_thin = d_thin
|
| 27 |
+
self.num_layers = num_layers
|
| 28 |
+
self.num_blocks = num_blocks
|
| 29 |
+
self.capacity_factor = capacity_factor
|
| 30 |
+
self.dropout = dropout
|
| 31 |
+
|
| 32 |
+
# Attribute parity for classification heads
|
| 33 |
+
self.hidden_size = d_model
|
| 34 |
+
|
| 35 |
+
super().__init__(**kwargs)
|
chck_3M/modeling_msit.py
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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Any
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
|
| 12 |
+
from transformers import PretrainedConfig, PreTrainedModel, GenerationMixin, AutoConfig, AutoModel, AutoModelForCausalLM
|
| 13 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 14 |
+
|
| 15 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 16 |
+
# Configuration Classes
|
| 17 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 18 |
+
|
| 19 |
+
@dataclass
|
| 20 |
+
class MSITGPTBERTConfig:
|
| 21 |
+
vocab_size: int = 16384
|
| 22 |
+
block_size: int = 512
|
| 23 |
+
d_model: int = 384
|
| 24 |
+
d_thin: int = 192
|
| 25 |
+
num_layers: int = 6
|
| 26 |
+
num_blocks: int = 6
|
| 27 |
+
capacity_factor: float = 2.0
|
| 28 |
+
dropout: float = 0.1
|
| 29 |
+
|
| 30 |
+
class MSITGPTBERTHFConfig(PretrainedConfig):
|
| 31 |
+
model_type = "msit_gptbert"
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self,
|
| 35 |
+
vocab_size: int = 16384,
|
| 36 |
+
block_size: int = 512,
|
| 37 |
+
d_model: int = 384,
|
| 38 |
+
d_thin: int = 192,
|
| 39 |
+
num_layers: int = 6,
|
| 40 |
+
num_blocks: int = 6,
|
| 41 |
+
capacity_factor: float = 2.0,
|
| 42 |
+
dropout: float = 0.1,
|
| 43 |
+
**kwargs
|
| 44 |
+
):
|
| 45 |
+
kwargs.setdefault("is_decoder", True)
|
| 46 |
+
kwargs.setdefault("bos_token_id", 2) # [CLS]
|
| 47 |
+
kwargs.setdefault("eos_token_id", 3) # [SEP]
|
| 48 |
+
kwargs.setdefault("pad_token_id", 1) # [PAD]
|
| 49 |
+
|
| 50 |
+
self.vocab_size = vocab_size
|
| 51 |
+
self.block_size = block_size
|
| 52 |
+
self.d_model = d_model
|
| 53 |
+
self.d_thin = d_thin
|
| 54 |
+
self.num_layers = num_layers
|
| 55 |
+
self.num_blocks = num_blocks
|
| 56 |
+
self.capacity_factor = capacity_factor
|
| 57 |
+
self.dropout = dropout
|
| 58 |
+
|
| 59 |
+
# Attribute parity for classification heads
|
| 60 |
+
self.hidden_size = d_model
|
| 61 |
+
|
| 62 |
+
super().__init__(**kwargs)
|
| 63 |
+
|
| 64 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 65 |
+
# ROPE HELPERS
|
| 66 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 67 |
+
|
| 68 |
+
def _precompute_rope_freqs(head_dim: int, seq_len: int, device: torch.device, theta: float = 10000.0):
|
| 69 |
+
assert head_dim % 2 == 0, "head_dim must be divisible by 2 for RoPE"
|
| 70 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim))
|
| 71 |
+
t = torch.arange(seq_len, device=device).float()
|
| 72 |
+
freqs = torch.outer(t, inv_freq)
|
| 73 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 74 |
+
return emb.cos(), emb.sin()
|
| 75 |
+
|
| 76 |
+
def _apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor):
|
| 77 |
+
L = x.size(2)
|
| 78 |
+
cos = cos[:L, :].unsqueeze(0).unsqueeze(1)
|
| 79 |
+
sin = sin[:L, :].unsqueeze(0).unsqueeze(1)
|
| 80 |
+
|
| 81 |
+
half_dim = x.size(-1) // 2
|
| 82 |
+
x1 = x[..., :half_dim]
|
| 83 |
+
x2 = x[..., half_dim:]
|
| 84 |
+
rotated_x = torch.cat((-x2, x1), dim=-1)
|
| 85 |
+
|
| 86 |
+
return (x * cos) + (rotated_x * sin)
|
| 87 |
+
|
| 88 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 89 |
+
# 1. SLIDING WINDOW ATTENTION
|
| 90 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 91 |
+
|
| 92 |
+
class SlidingWindowAttention(nn.Module):
|
| 93 |
+
def __init__(self, dim: int, num_heads: int, window_size=None):
|
| 94 |
+
super().__init__()
|
| 95 |
+
assert dim % num_heads == 0, "dim must be divisible by num_heads"
|
| 96 |
+
self.num_heads = num_heads
|
| 97 |
+
self.window_size = window_size
|
| 98 |
+
self.head_dim = dim // num_heads
|
| 99 |
+
|
| 100 |
+
self.q_proj = nn.Linear(dim, dim, bias=False)
|
| 101 |
+
self.k_proj = nn.Linear(dim, dim, bias=False)
|
| 102 |
+
self.v_proj = nn.Linear(dim, dim, bias=False)
|
| 103 |
+
self.o_proj = nn.Linear(dim, dim, bias=False)
|
| 104 |
+
|
| 105 |
+
def forward(self, x: torch.Tensor,
|
| 106 |
+
past_kv=None,
|
| 107 |
+
use_cache: bool = False,
|
| 108 |
+
bidirectional: bool = False):
|
| 109 |
+
B, L, D = x.size()
|
| 110 |
+
|
| 111 |
+
q = self.q_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 112 |
+
k = self.k_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 113 |
+
v = self.v_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 114 |
+
|
| 115 |
+
if past_kv is not None:
|
| 116 |
+
past_k, past_v = past_kv
|
| 117 |
+
past_len = past_k.size(2)
|
| 118 |
+
q_cos, q_sin = _precompute_rope_freqs(self.head_dim, past_len + L, x.device)
|
| 119 |
+
q = _apply_rope(q, q_cos[past_len:, :], q_sin[past_len:, :])
|
| 120 |
+
k = _apply_rope(k, q_cos[past_len:, :], q_sin[past_len:, :])
|
| 121 |
+
|
| 122 |
+
k = torch.cat([past_k, k], dim=2)
|
| 123 |
+
v = torch.cat([past_v, v], dim=2)
|
| 124 |
+
else:
|
| 125 |
+
cos, sin = _precompute_rope_freqs(self.head_dim, L, x.device)
|
| 126 |
+
q = _apply_rope(q, cos, sin)
|
| 127 |
+
k = _apply_rope(k, cos, sin)
|
| 128 |
+
|
| 129 |
+
L_kv = k.size(2)
|
| 130 |
+
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
|
| 131 |
+
|
| 132 |
+
if bidirectional:
|
| 133 |
+
if self.window_size is not None:
|
| 134 |
+
past_len = L_kv - L
|
| 135 |
+
pos_i = (past_len + torch.arange(L, device=x.device)).unsqueeze(1)
|
| 136 |
+
pos_j = torch.arange(L_kv, device=x.device).unsqueeze(0)
|
| 137 |
+
dist = torch.abs(pos_i - pos_j)
|
| 138 |
+
win_mask = dist < self.window_size
|
| 139 |
+
scores = scores.masked_fill(
|
| 140 |
+
~win_mask.unsqueeze(0).unsqueeze(0), float('-inf')
|
| 141 |
+
)
|
| 142 |
+
else:
|
| 143 |
+
past_len = L_kv - L
|
| 144 |
+
pos_i = (past_len + torch.arange(L, device=x.device)).unsqueeze(1)
|
| 145 |
+
pos_j = torch.arange(L_kv, device=x.device).unsqueeze(0)
|
| 146 |
+
dist = pos_i - pos_j
|
| 147 |
+
|
| 148 |
+
causal_mask = dist >= 0
|
| 149 |
+
if self.window_size is not None:
|
| 150 |
+
causal_mask = causal_mask & (dist < self.window_size)
|
| 151 |
+
|
| 152 |
+
scores = scores.masked_fill(
|
| 153 |
+
~causal_mask.unsqueeze(0).unsqueeze(0), float('-inf')
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
attn = torch.softmax(scores, dim=-1)
|
| 157 |
+
out = torch.matmul(attn, v)
|
| 158 |
+
out = out.transpose(1, 2).contiguous().view(B, L, D)
|
| 159 |
+
out = self.o_proj(out)
|
| 160 |
+
|
| 161 |
+
if use_cache:
|
| 162 |
+
if self.window_size is not None:
|
| 163 |
+
present_kv = (
|
| 164 |
+
k[:, :, -self.window_size:, :],
|
| 165 |
+
v[:, :, -self.window_size:, :]
|
| 166 |
+
)
|
| 167 |
+
else:
|
| 168 |
+
present_kv = (k, v)
|
| 169 |
+
else:
|
| 170 |
+
present_kv = None
|
| 171 |
+
|
| 172 |
+
return out, present_kv
|
| 173 |
+
|
| 174 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 175 |
+
# 2. MSIT BRANCH BLOCK (Pre-Norm)
|
| 176 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 177 |
+
|
| 178 |
+
class MSITBranchBlock(nn.Module):
|
| 179 |
+
def __init__(self, dim: int, num_heads: int, window_size):
|
| 180 |
+
super().__init__()
|
| 181 |
+
self.ln1 = nn.LayerNorm(dim)
|
| 182 |
+
self.attn = SlidingWindowAttention(dim, num_heads, window_size)
|
| 183 |
+
self.ln2 = nn.LayerNorm(dim)
|
| 184 |
+
self.ffn = nn.Sequential(
|
| 185 |
+
nn.Linear(dim, dim * 4, bias=False),
|
| 186 |
+
nn.GELU(),
|
| 187 |
+
nn.Linear(dim * 4, dim, bias=False),
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
def forward(self, x: torch.Tensor,
|
| 191 |
+
past_kv=None,
|
| 192 |
+
use_cache: bool = False,
|
| 193 |
+
bidirectional: bool = False):
|
| 194 |
+
attn_out, present_kv = self.attn(
|
| 195 |
+
self.ln1(x), past_kv, use_cache, bidirectional
|
| 196 |
+
)
|
| 197 |
+
x = x + attn_out
|
| 198 |
+
x = x + self.ffn(self.ln2(x))
|
| 199 |
+
return x, present_kv
|
| 200 |
+
|
| 201 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 202 |
+
# 3. MoEP-MSIT ARCHITECTURE BLOCK (Expert Choice routing)
|
| 203 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 204 |
+
|
| 205 |
+
class MoEPMSITBlock(nn.Module):
|
| 206 |
+
def __init__(self, d_model: int = 512, d_thin: int = 192, num_blocks: int = 14,
|
| 207 |
+
capacity_factor: float = 2.0):
|
| 208 |
+
super().__init__()
|
| 209 |
+
self.d_model = d_model
|
| 210 |
+
self.d_thin = d_thin
|
| 211 |
+
self.num_blocks = num_blocks
|
| 212 |
+
self.capacity_factor = capacity_factor
|
| 213 |
+
|
| 214 |
+
# 1. Global Block (Dense, d_model)
|
| 215 |
+
num_heads_global = max(1, d_model // 64)
|
| 216 |
+
self.global_block = MSITBranchBlock(d_model, num_heads_global, window_size=None)
|
| 217 |
+
|
| 218 |
+
# 2. Router
|
| 219 |
+
self.router_ln = nn.LayerNorm(d_model)
|
| 220 |
+
self.w_router = nn.Linear(d_model, num_blocks, bias=False)
|
| 221 |
+
|
| 222 |
+
# 3. Shrink Projection
|
| 223 |
+
self.w_down = nn.Linear(d_model, d_thin, bias=False)
|
| 224 |
+
|
| 225 |
+
# 4. Thin Parallel Blocks (d_thin)
|
| 226 |
+
self.windows = [None, 16, 8, 4, 2] + [None] * (num_blocks - 5)
|
| 227 |
+
self.heads = [max(1, d_thin // 64)] * num_blocks
|
| 228 |
+
|
| 229 |
+
self.thin_blocks = nn.ModuleList([
|
| 230 |
+
MSITBranchBlock(d_thin, self.heads[i], self.windows[i])
|
| 231 |
+
for i in range(num_blocks)
|
| 232 |
+
])
|
| 233 |
+
|
| 234 |
+
# 6. Grow Projection
|
| 235 |
+
self.w_up = nn.Linear(d_thin, d_model, bias=False)
|
| 236 |
+
self.last_topk_indices = None
|
| 237 |
+
|
| 238 |
+
def forward(self, x_0: torch.Tensor, past_kvs=None, use_cache: bool = False, bidirectional: bool = False):
|
| 239 |
+
B, T, D = x_0.size()
|
| 240 |
+
n_tokens = B * T
|
| 241 |
+
|
| 242 |
+
# Step 1: Global Block
|
| 243 |
+
pkv_g = past_kvs[0] if past_kvs else None
|
| 244 |
+
x_1, nkv_g = self.global_block(x_0, pkv_g, use_cache, bidirectional)
|
| 245 |
+
|
| 246 |
+
# Step 2: Gated input stream
|
| 247 |
+
x_2 = x_1 + x_0
|
| 248 |
+
|
| 249 |
+
# Router scores
|
| 250 |
+
r_logits = self.w_router(self.router_ln(x_2)).view(n_tokens, self.num_blocks)
|
| 251 |
+
r_probs = F.softmax(r_logits, dim=-1)
|
| 252 |
+
|
| 253 |
+
# Per-expert capacity: k = (n * c) / e
|
| 254 |
+
k_capacity = max(1, int(round(n_tokens * self.capacity_factor / self.num_blocks)))
|
| 255 |
+
k_capacity = min(k_capacity, n_tokens)
|
| 256 |
+
|
| 257 |
+
# Expert Choice routing: topk over the token axis for each expert
|
| 258 |
+
expert_token_scores = r_probs.transpose(0, 1) # (num_blocks, n_tokens)
|
| 259 |
+
topk_scores, topk_token_idx = torch.topk(expert_token_scores, k_capacity, dim=-1)
|
| 260 |
+
self.last_topk_indices = topk_token_idx
|
| 261 |
+
|
| 262 |
+
# Load balancing is guaranteed by construction in Expert Choice
|
| 263 |
+
layer_aux_loss = x_2.new_zeros(())
|
| 264 |
+
|
| 265 |
+
# Shrink projection
|
| 266 |
+
x_2_thin = self.w_down(x_2) # (B, T, d_thin)
|
| 267 |
+
x_2_thin_flat = x_2_thin.view(n_tokens, self.d_thin)
|
| 268 |
+
|
| 269 |
+
# Expert computations
|
| 270 |
+
new_kvs = [nkv_g]
|
| 271 |
+
expert_outputs_flat = torch.zeros(n_tokens, self.d_model, device=x_2.device, dtype=x_2.dtype)
|
| 272 |
+
|
| 273 |
+
for i, block in enumerate(self.thin_blocks):
|
| 274 |
+
sel_idx = topk_token_idx[i]
|
| 275 |
+
bucket_in = x_2_thin_flat[sel_idx].unsqueeze(0) # (1, k_capacity, d_thin)
|
| 276 |
+
|
| 277 |
+
pkv_i = past_kvs[i + 1] if past_kvs else None
|
| 278 |
+
bucket_out, nkv_i = block(bucket_in, pkv_i, use_cache, bidirectional)
|
| 279 |
+
if use_cache:
|
| 280 |
+
new_kvs.append(nkv_i)
|
| 281 |
+
|
| 282 |
+
bucket_out = bucket_out.squeeze(0) # (k_capacity, d_thin)
|
| 283 |
+
bucket_out_full = self.w_up(bucket_out) # (k_capacity, d_model)
|
| 284 |
+
|
| 285 |
+
gate = topk_scores[i].unsqueeze(-1) # (k_capacity, 1)
|
| 286 |
+
expert_outputs_flat.index_add_(0, sel_idx, bucket_out_full * gate)
|
| 287 |
+
|
| 288 |
+
x_3_full = expert_outputs_flat.view(B, T, self.d_model)
|
| 289 |
+
out = x_2 + x_3_full
|
| 290 |
+
|
| 291 |
+
present_kvs = tuple(new_kvs) if use_cache else None
|
| 292 |
+
return out, present_kvs, layer_aux_loss
|
| 293 |
+
|
| 294 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 295 |
+
# 4. RAW MSIT-GPT-BERT MODEL
|
| 296 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 297 |
+
|
| 298 |
+
class MSITGPTBERTModel(nn.Module):
|
| 299 |
+
def __init__(self, cfg):
|
| 300 |
+
super().__init__()
|
| 301 |
+
self.cfg = cfg
|
| 302 |
+
self.wte = nn.Embedding(cfg.vocab_size, cfg.d_model)
|
| 303 |
+
self.drop_emb = nn.Dropout(cfg.dropout)
|
| 304 |
+
self.blocks = nn.ModuleList([
|
| 305 |
+
MoEPMSITBlock(
|
| 306 |
+
d_model=cfg.d_model,
|
| 307 |
+
d_thin=cfg.d_thin,
|
| 308 |
+
num_blocks=cfg.num_blocks,
|
| 309 |
+
capacity_factor=cfg.capacity_factor
|
| 310 |
+
)
|
| 311 |
+
for _ in range(cfg.num_layers)
|
| 312 |
+
])
|
| 313 |
+
self.ln_f = nn.LayerNorm(cfg.d_model)
|
| 314 |
+
self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
|
| 315 |
+
self.wte.weight = self.lm_head.weight
|
| 316 |
+
|
| 317 |
+
def forward(self, input_ids: torch.Tensor, targets: torch.Tensor = None, bidirectional: bool = False):
|
| 318 |
+
x = self.drop_emb(self.wte(input_ids))
|
| 319 |
+
total_aux_loss = 0.0
|
| 320 |
+
|
| 321 |
+
for block in self.blocks:
|
| 322 |
+
x, _, layer_aux = block(x, past_kvs=None, use_cache=False, bidirectional=bidirectional)
|
| 323 |
+
total_aux_loss += layer_aux
|
| 324 |
+
|
| 325 |
+
x = self.ln_f(x)
|
| 326 |
+
logits = self.lm_head(x)
|
| 327 |
+
|
| 328 |
+
loss = None
|
| 329 |
+
if targets is not None:
|
| 330 |
+
ce_loss = F.cross_entropy(logits.view(-1, self.cfg.vocab_size), targets.view(-1), ignore_index=-100)
|
| 331 |
+
avg_aux_loss = total_aux_loss / self.cfg.num_layers
|
| 332 |
+
loss = ce_loss + (0.01 * avg_aux_loss)
|
| 333 |
+
|
| 334 |
+
return logits, loss
|
| 335 |
+
|
| 336 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 337 |
+
# 5. HUGGING FACE MODEL WRAPPERS
|
| 338 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 339 |
+
|
| 340 |
+
class MSITGPTBERTModelWrapper(PreTrainedModel):
|
| 341 |
+
config_class = MSITGPTBERTHFConfig
|
| 342 |
+
base_model_prefix = "transformer"
|
| 343 |
+
|
| 344 |
+
def __init__(self, config: MSITGPTBERTHFConfig):
|
| 345 |
+
super().__init__(config)
|
| 346 |
+
self.wte = nn.Embedding(config.vocab_size, config.d_model)
|
| 347 |
+
self.drop_emb = nn.Dropout(config.dropout)
|
| 348 |
+
self.blocks = nn.ModuleList([
|
| 349 |
+
MoEPMSITBlock(config.d_model, config.d_thin, config.num_blocks, config.capacity_factor)
|
| 350 |
+
for _ in range(config.num_layers)
|
| 351 |
+
])
|
| 352 |
+
self.ln_f = nn.LayerNorm(config.d_model)
|
| 353 |
+
self.post_init()
|
| 354 |
+
|
| 355 |
+
def forward(self, input_ids, **kwargs):
|
| 356 |
+
x = self.drop_emb(self.wte(input_ids))
|
| 357 |
+
for block in self.blocks:
|
| 358 |
+
x, _, _ = block(x, past_kvs=None, use_cache=False, bidirectional=False)
|
| 359 |
+
x = self.ln_f(x)
|
| 360 |
+
return BaseModelOutputWithPast(last_hidden_state=x)
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
class MSITGPTBERTForCausalLM(PreTrainedModel, GenerationMixin):
|
| 364 |
+
config_class = MSITGPTBERTHFConfig
|
| 365 |
+
base_model_prefix = "transformer"
|
| 366 |
+
_no_split_modules = ["MoEPMSITBlock"]
|
| 367 |
+
_tied_weights_keys = {"transformer.lm_head.weight": "transformer.wte.weight"}
|
| 368 |
+
|
| 369 |
+
def __init__(self, config: MSITGPTBERTHFConfig):
|
| 370 |
+
super().__init__(config)
|
| 371 |
+
self.transformer = MSITGPTBERTModelWrapper(config)
|
| 372 |
+
self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
|
| 373 |
+
self.post_init()
|
| 374 |
+
|
| 375 |
+
# State-dict pre-hook for backwards compatibility with checkpoint key naming
|
| 376 |
+
def _prefix_cleaner(state_dict, prefix, local_metadata, Moore, missing_keys, unexpected_keys, error_msgs):
|
| 377 |
+
keys = list(state_dict.keys())
|
| 378 |
+
for k in keys:
|
| 379 |
+
if k.startswith("transformer."):
|
| 380 |
+
state_dict[k.replace("transformer.", "", 1)] = state_dict.pop(k)
|
| 381 |
+
elif f"{prefix}transformer." in k:
|
| 382 |
+
state_dict[k.replace("transformer.", "", 1)] = state_dict.pop(k)
|
| 383 |
+
|
| 384 |
+
self._register_load_state_dict_pre_hook(_prefix_cleaner)
|
| 385 |
+
|
| 386 |
+
def tie_weights(self, **kwargs):
|
| 387 |
+
if hasattr(self, "transformer") and hasattr(self.transformer, "wte") and hasattr(self.transformer, "lm_head"):
|
| 388 |
+
self.transformer.wte.weight = self.lm_head.weight
|
| 389 |
+
|
| 390 |
+
def get_input_embeddings(self):
|
| 391 |
+
return self.transformer.wte
|
| 392 |
+
|
| 393 |
+
def set_input_embeddings(self, new_embeddings):
|
| 394 |
+
self.transformer.wte = new_embeddings
|
| 395 |
+
|
| 396 |
+
def get_output_embeddings(self):
|
| 397 |
+
return self.lm_head
|
| 398 |
+
|
| 399 |
+
def set_output_embeddings(self, new_embeddings):
|
| 400 |
+
self.lm_head = new_embeddings
|
| 401 |
+
|
| 402 |
+
def forward(self,
|
| 403 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 404 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 405 |
+
labels: Optional[torch.LongTensor] = None,
|
| 406 |
+
**kwargs) -> CausalLMOutputWithPast:
|
| 407 |
+
outputs = self.transformer(input_ids)
|
| 408 |
+
hidden_states = outputs.last_hidden_state
|
| 409 |
+
logits = self.lm_head(hidden_states)
|
| 410 |
+
|
| 411 |
+
loss = None
|
| 412 |
+
if labels is not None:
|
| 413 |
+
shift_logits = logits[:, :-1, :].contiguous()
|
| 414 |
+
shift_labels = labels[:, 1:].contiguous()
|
| 415 |
+
loss = F.cross_entropy(
|
| 416 |
+
shift_logits.view(-1, self.config.vocab_size),
|
| 417 |
+
shift_labels.view(-1),
|
| 418 |
+
ignore_index=-100
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
return CausalLMOutputWithPast(
|
| 422 |
+
loss=loss,
|
| 423 |
+
logits=logits,
|
| 424 |
+
past_key_values=None,
|
| 425 |
+
hidden_states=None,
|
| 426 |
+
attentions=None,
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
def prepare_inputs_for_generation(self, input_ids, **kwargs):
|
| 430 |
+
return {"input_ids": input_ids}
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
# Register with auto-mapping
|
| 434 |
+
AutoConfig.register("msit_gptbert", MSITGPTBERTHFConfig)
|
| 435 |
+
AutoModel.register(MSITGPTBERTHFConfig, MSITGPTBERTModelWrapper)
|
| 436 |
+
AutoModelForCausalLM.register(MSITGPTBERTHFConfig, MSITGPTBERTForCausalLM)
|
chck_3M/pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e1b31fa8db02a964a158a0cb6954e3d53faac55ece287565252682e0f3d02e7f
|
| 3 |
+
size 135253367
|
chck_3M/tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
chck_3M/tokenizer_config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "tokenizers",
|
| 3 |
+
"bos_token": "[CLS]",
|
| 4 |
+
"eos_token": "[SEP]",
|
| 5 |
+
"mask_token": "[MASK]",
|
| 6 |
+
"model_max_length": 1000000000000000019884624838656,
|
| 7 |
+
"pad_token": "[PAD]",
|
| 8 |
+
"tokenizer_class": "TokenizersBackend",
|
| 9 |
+
"unk_token": "[UNK]"
|
| 10 |
+
}
|
chck_40M/config.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"auto_map": {
|
| 3 |
+
"AutoConfig": "modeling_msit.MSITGPTBERTHFConfig",
|
| 4 |
+
"AutoModel": "modeling_msit.MSITGPTBERTModelWrapper",
|
| 5 |
+
"AutoModelForCausalLM": "modeling_msit.MSITGPTBERTForCausalLM"
|
| 6 |
+
},
|
| 7 |
+
"vocab_size": 16384,
|
| 8 |
+
"block_size": 512,
|
| 9 |
+
"d_model": 384,
|
| 10 |
+
"hidden_size": 384,
|
| 11 |
+
"d_thin": 192,
|
| 12 |
+
"num_layers": 6,
|
| 13 |
+
"num_blocks": 6,
|
| 14 |
+
"capacity_factor": 2.0,
|
| 15 |
+
"dropout": 0.1,
|
| 16 |
+
"model_type": "msit_gptbert"
|
| 17 |
+
}
|
chck_40M/configuration_msit.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
|
| 3 |
+
class MSITGPTBERTHFConfig(PretrainedConfig):
|
| 4 |
+
model_type = "msit_gptbert"
|
| 5 |
+
|
| 6 |
+
def __init__(
|
| 7 |
+
self,
|
| 8 |
+
vocab_size: int = 16384,
|
| 9 |
+
block_size: int = 512,
|
| 10 |
+
d_model: int = 384,
|
| 11 |
+
d_thin: int = 192,
|
| 12 |
+
num_layers: int = 6,
|
| 13 |
+
num_blocks: int = 6,
|
| 14 |
+
capacity_factor: float = 2.0,
|
| 15 |
+
dropout: float = 0.1,
|
| 16 |
+
**kwargs
|
| 17 |
+
):
|
| 18 |
+
kwargs.setdefault("is_decoder", True)
|
| 19 |
+
kwargs.setdefault("bos_token_id", 2) # [CLS]
|
| 20 |
+
kwargs.setdefault("eos_token_id", 3) # [SEP]
|
| 21 |
+
kwargs.setdefault("pad_token_id", 1) # [PAD]
|
| 22 |
+
|
| 23 |
+
self.vocab_size = vocab_size
|
| 24 |
+
self.block_size = block_size
|
| 25 |
+
self.d_model = d_model
|
| 26 |
+
self.d_thin = d_thin
|
| 27 |
+
self.num_layers = num_layers
|
| 28 |
+
self.num_blocks = num_blocks
|
| 29 |
+
self.capacity_factor = capacity_factor
|
| 30 |
+
self.dropout = dropout
|
| 31 |
+
|
| 32 |
+
# Attribute parity for classification heads
|
| 33 |
+
self.hidden_size = d_model
|
| 34 |
+
|
| 35 |
+
super().__init__(**kwargs)
|
chck_40M/modeling_msit.py
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import math
|
| 3 |
+
import random
|
| 4 |
+
import inspect
|
| 5 |
+
from typing import Optional, Tuple, Dict, Any
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
|
| 12 |
+
from transformers import PretrainedConfig, PreTrainedModel, GenerationMixin, AutoConfig, AutoModel, AutoModelForCausalLM
|
| 13 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 14 |
+
|
| 15 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 16 |
+
# Configuration Classes
|
| 17 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 18 |
+
|
| 19 |
+
@dataclass
|
| 20 |
+
class MSITGPTBERTConfig:
|
| 21 |
+
vocab_size: int = 16384
|
| 22 |
+
block_size: int = 512
|
| 23 |
+
d_model: int = 384
|
| 24 |
+
d_thin: int = 192
|
| 25 |
+
num_layers: int = 6
|
| 26 |
+
num_blocks: int = 6
|
| 27 |
+
capacity_factor: float = 2.0
|
| 28 |
+
dropout: float = 0.1
|
| 29 |
+
|
| 30 |
+
class MSITGPTBERTHFConfig(PretrainedConfig):
|
| 31 |
+
model_type = "msit_gptbert"
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self,
|
| 35 |
+
vocab_size: int = 16384,
|
| 36 |
+
block_size: int = 512,
|
| 37 |
+
d_model: int = 384,
|
| 38 |
+
d_thin: int = 192,
|
| 39 |
+
num_layers: int = 6,
|
| 40 |
+
num_blocks: int = 6,
|
| 41 |
+
capacity_factor: float = 2.0,
|
| 42 |
+
dropout: float = 0.1,
|
| 43 |
+
**kwargs
|
| 44 |
+
):
|
| 45 |
+
kwargs.setdefault("is_decoder", True)
|
| 46 |
+
kwargs.setdefault("bos_token_id", 2) # [CLS]
|
| 47 |
+
kwargs.setdefault("eos_token_id", 3) # [SEP]
|
| 48 |
+
kwargs.setdefault("pad_token_id", 1) # [PAD]
|
| 49 |
+
|
| 50 |
+
self.vocab_size = vocab_size
|
| 51 |
+
self.block_size = block_size
|
| 52 |
+
self.d_model = d_model
|
| 53 |
+
self.d_thin = d_thin
|
| 54 |
+
self.num_layers = num_layers
|
| 55 |
+
self.num_blocks = num_blocks
|
| 56 |
+
self.capacity_factor = capacity_factor
|
| 57 |
+
self.dropout = dropout
|
| 58 |
+
|
| 59 |
+
# Attribute parity for classification heads
|
| 60 |
+
self.hidden_size = d_model
|
| 61 |
+
|
| 62 |
+
super().__init__(**kwargs)
|
| 63 |
+
|
| 64 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 65 |
+
# ROPE HELPERS
|
| 66 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 67 |
+
|
| 68 |
+
def _precompute_rope_freqs(head_dim: int, seq_len: int, device: torch.device, theta: float = 10000.0):
|
| 69 |
+
assert head_dim % 2 == 0, "head_dim must be divisible by 2 for RoPE"
|
| 70 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim))
|
| 71 |
+
t = torch.arange(seq_len, device=device).float()
|
| 72 |
+
freqs = torch.outer(t, inv_freq)
|
| 73 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 74 |
+
return emb.cos(), emb.sin()
|
| 75 |
+
|
| 76 |
+
def _apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor):
|
| 77 |
+
L = x.size(2)
|
| 78 |
+
cos = cos[:L, :].unsqueeze(0).unsqueeze(1)
|
| 79 |
+
sin = sin[:L, :].unsqueeze(0).unsqueeze(1)
|
| 80 |
+
|
| 81 |
+
half_dim = x.size(-1) // 2
|
| 82 |
+
x1 = x[..., :half_dim]
|
| 83 |
+
x2 = x[..., half_dim:]
|
| 84 |
+
rotated_x = torch.cat((-x2, x1), dim=-1)
|
| 85 |
+
|
| 86 |
+
return (x * cos) + (rotated_x * sin)
|
| 87 |
+
|
| 88 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 89 |
+
# 1. SLIDING WINDOW ATTENTION
|
| 90 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 91 |
+
|
| 92 |
+
class SlidingWindowAttention(nn.Module):
|
| 93 |
+
def __init__(self, dim: int, num_heads: int, window_size=None):
|
| 94 |
+
super().__init__()
|
| 95 |
+
assert dim % num_heads == 0, "dim must be divisible by num_heads"
|
| 96 |
+
self.num_heads = num_heads
|
| 97 |
+
self.window_size = window_size
|
| 98 |
+
self.head_dim = dim // num_heads
|
| 99 |
+
|
| 100 |
+
self.q_proj = nn.Linear(dim, dim, bias=False)
|
| 101 |
+
self.k_proj = nn.Linear(dim, dim, bias=False)
|
| 102 |
+
self.v_proj = nn.Linear(dim, dim, bias=False)
|
| 103 |
+
self.o_proj = nn.Linear(dim, dim, bias=False)
|
| 104 |
+
|
| 105 |
+
def forward(self, x: torch.Tensor,
|
| 106 |
+
past_kv=None,
|
| 107 |
+
use_cache: bool = False,
|
| 108 |
+
bidirectional: bool = False):
|
| 109 |
+
B, L, D = x.size()
|
| 110 |
+
|
| 111 |
+
q = self.q_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 112 |
+
k = self.k_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 113 |
+
v = self.v_proj(x).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
|
| 114 |
+
|
| 115 |
+
if past_kv is not None:
|
| 116 |
+
past_k, past_v = past_kv
|
| 117 |
+
past_len = past_k.size(2)
|
| 118 |
+
q_cos, q_sin = _precompute_rope_freqs(self.head_dim, past_len + L, x.device)
|
| 119 |
+
q = _apply_rope(q, q_cos[past_len:, :], q_sin[past_len:, :])
|
| 120 |
+
k = _apply_rope(k, q_cos[past_len:, :], q_sin[past_len:, :])
|
| 121 |
+
|
| 122 |
+
k = torch.cat([past_k, k], dim=2)
|
| 123 |
+
v = torch.cat([past_v, v], dim=2)
|
| 124 |
+
else:
|
| 125 |
+
cos, sin = _precompute_rope_freqs(self.head_dim, L, x.device)
|
| 126 |
+
q = _apply_rope(q, cos, sin)
|
| 127 |
+
k = _apply_rope(k, cos, sin)
|
| 128 |
+
|
| 129 |
+
L_kv = k.size(2)
|
| 130 |
+
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
|
| 131 |
+
|
| 132 |
+
if bidirectional:
|
| 133 |
+
if self.window_size is not None:
|
| 134 |
+
past_len = L_kv - L
|
| 135 |
+
pos_i = (past_len + torch.arange(L, device=x.device)).unsqueeze(1)
|
| 136 |
+
pos_j = torch.arange(L_kv, device=x.device).unsqueeze(0)
|
| 137 |
+
dist = torch.abs(pos_i - pos_j)
|
| 138 |
+
win_mask = dist < self.window_size
|
| 139 |
+
scores = scores.masked_fill(
|
| 140 |
+
~win_mask.unsqueeze(0).unsqueeze(0), float('-inf')
|
| 141 |
+
)
|
| 142 |
+
else:
|
| 143 |
+
past_len = L_kv - L
|
| 144 |
+
pos_i = (past_len + torch.arange(L, device=x.device)).unsqueeze(1)
|
| 145 |
+
pos_j = torch.arange(L_kv, device=x.device).unsqueeze(0)
|
| 146 |
+
dist = pos_i - pos_j
|
| 147 |
+
|
| 148 |
+
causal_mask = dist >= 0
|
| 149 |
+
if self.window_size is not None:
|
| 150 |
+
causal_mask = causal_mask & (dist < self.window_size)
|
| 151 |
+
|
| 152 |
+
scores = scores.masked_fill(
|
| 153 |
+
~causal_mask.unsqueeze(0).unsqueeze(0), float('-inf')
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
attn = torch.softmax(scores, dim=-1)
|
| 157 |
+
out = torch.matmul(attn, v)
|
| 158 |
+
out = out.transpose(1, 2).contiguous().view(B, L, D)
|
| 159 |
+
out = self.o_proj(out)
|
| 160 |
+
|
| 161 |
+
if use_cache:
|
| 162 |
+
if self.window_size is not None:
|
| 163 |
+
present_kv = (
|
| 164 |
+
k[:, :, -self.window_size:, :],
|
| 165 |
+
v[:, :, -self.window_size:, :]
|
| 166 |
+
)
|
| 167 |
+
else:
|
| 168 |
+
present_kv = (k, v)
|
| 169 |
+
else:
|
| 170 |
+
present_kv = None
|
| 171 |
+
|
| 172 |
+
return out, present_kv
|
| 173 |
+
|
| 174 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 175 |
+
# 2. MSIT BRANCH BLOCK (Pre-Norm)
|
| 176 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 177 |
+
|
| 178 |
+
class MSITBranchBlock(nn.Module):
|
| 179 |
+
def __init__(self, dim: int, num_heads: int, window_size):
|
| 180 |
+
super().__init__()
|
| 181 |
+
self.ln1 = nn.LayerNorm(dim)
|
| 182 |
+
self.attn = SlidingWindowAttention(dim, num_heads, window_size)
|
| 183 |
+
self.ln2 = nn.LayerNorm(dim)
|
| 184 |
+
self.ffn = nn.Sequential(
|
| 185 |
+
nn.Linear(dim, dim * 4, bias=False),
|
| 186 |
+
nn.GELU(),
|
| 187 |
+
nn.Linear(dim * 4, dim, bias=False),
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
def forward(self, x: torch.Tensor,
|
| 191 |
+
past_kv=None,
|
| 192 |
+
use_cache: bool = False,
|
| 193 |
+
bidirectional: bool = False):
|
| 194 |
+
attn_out, present_kv = self.attn(
|
| 195 |
+
self.ln1(x), past_kv, use_cache, bidirectional
|
| 196 |
+
)
|
| 197 |
+
x = x + attn_out
|
| 198 |
+
x = x + self.ffn(self.ln2(x))
|
| 199 |
+
return x, present_kv
|
| 200 |
+
|
| 201 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 202 |
+
# 3. MoEP-MSIT ARCHITECTURE BLOCK (Expert Choice routing)
|
| 203 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 204 |
+
|
| 205 |
+
class MoEPMSITBlock(nn.Module):
|
| 206 |
+
def __init__(self, d_model: int = 512, d_thin: int = 192, num_blocks: int = 14,
|
| 207 |
+
capacity_factor: float = 2.0):
|
| 208 |
+
super().__init__()
|
| 209 |
+
self.d_model = d_model
|
| 210 |
+
self.d_thin = d_thin
|
| 211 |
+
self.num_blocks = num_blocks
|
| 212 |
+
self.capacity_factor = capacity_factor
|
| 213 |
+
|
| 214 |
+
# 1. Global Block (Dense, d_model)
|
| 215 |
+
num_heads_global = max(1, d_model // 64)
|
| 216 |
+
self.global_block = MSITBranchBlock(d_model, num_heads_global, window_size=None)
|
| 217 |
+
|
| 218 |
+
# 2. Router
|
| 219 |
+
self.router_ln = nn.LayerNorm(d_model)
|
| 220 |
+
self.w_router = nn.Linear(d_model, num_blocks, bias=False)
|
| 221 |
+
|
| 222 |
+
# 3. Shrink Projection
|
| 223 |
+
self.w_down = nn.Linear(d_model, d_thin, bias=False)
|
| 224 |
+
|
| 225 |
+
# 4. Thin Parallel Blocks (d_thin)
|
| 226 |
+
self.windows = [None, 16, 8, 4, 2] + [None] * (num_blocks - 5)
|
| 227 |
+
self.heads = [max(1, d_thin // 64)] * num_blocks
|
| 228 |
+
|
| 229 |
+
self.thin_blocks = nn.ModuleList([
|
| 230 |
+
MSITBranchBlock(d_thin, self.heads[i], self.windows[i])
|
| 231 |
+
for i in range(num_blocks)
|
| 232 |
+
])
|
| 233 |
+
|
| 234 |
+
# 6. Grow Projection
|
| 235 |
+
self.w_up = nn.Linear(d_thin, d_model, bias=False)
|
| 236 |
+
self.last_topk_indices = None
|
| 237 |
+
|
| 238 |
+
def forward(self, x_0: torch.Tensor, past_kvs=None, use_cache: bool = False, bidirectional: bool = False):
|
| 239 |
+
B, T, D = x_0.size()
|
| 240 |
+
n_tokens = B * T
|
| 241 |
+
|
| 242 |
+
# Step 1: Global Block
|
| 243 |
+
pkv_g = past_kvs[0] if past_kvs else None
|
| 244 |
+
x_1, nkv_g = self.global_block(x_0, pkv_g, use_cache, bidirectional)
|
| 245 |
+
|
| 246 |
+
# Step 2: Gated input stream
|
| 247 |
+
x_2 = x_1 + x_0
|
| 248 |
+
|
| 249 |
+
# Router scores
|
| 250 |
+
r_logits = self.w_router(self.router_ln(x_2)).view(n_tokens, self.num_blocks)
|
| 251 |
+
r_probs = F.softmax(r_logits, dim=-1)
|
| 252 |
+
|
| 253 |
+
# Per-expert capacity: k = (n * c) / e
|
| 254 |
+
k_capacity = max(1, int(round(n_tokens * self.capacity_factor / self.num_blocks)))
|
| 255 |
+
k_capacity = min(k_capacity, n_tokens)
|
| 256 |
+
|
| 257 |
+
# Expert Choice routing: topk over the token axis for each expert
|
| 258 |
+
expert_token_scores = r_probs.transpose(0, 1) # (num_blocks, n_tokens)
|
| 259 |
+
topk_scores, topk_token_idx = torch.topk(expert_token_scores, k_capacity, dim=-1)
|
| 260 |
+
self.last_topk_indices = topk_token_idx
|
| 261 |
+
|
| 262 |
+
# Load balancing is guaranteed by construction in Expert Choice
|
| 263 |
+
layer_aux_loss = x_2.new_zeros(())
|
| 264 |
+
|
| 265 |
+
# Shrink projection
|
| 266 |
+
x_2_thin = self.w_down(x_2) # (B, T, d_thin)
|
| 267 |
+
x_2_thin_flat = x_2_thin.view(n_tokens, self.d_thin)
|
| 268 |
+
|
| 269 |
+
# Expert computations
|
| 270 |
+
new_kvs = [nkv_g]
|
| 271 |
+
expert_outputs_flat = torch.zeros(n_tokens, self.d_model, device=x_2.device, dtype=x_2.dtype)
|
| 272 |
+
|
| 273 |
+
for i, block in enumerate(self.thin_blocks):
|
| 274 |
+
sel_idx = topk_token_idx[i]
|
| 275 |
+
bucket_in = x_2_thin_flat[sel_idx].unsqueeze(0) # (1, k_capacity, d_thin)
|
| 276 |
+
|
| 277 |
+
pkv_i = past_kvs[i + 1] if past_kvs else None
|
| 278 |
+
bucket_out, nkv_i = block(bucket_in, pkv_i, use_cache, bidirectional)
|
| 279 |
+
if use_cache:
|
| 280 |
+
new_kvs.append(nkv_i)
|
| 281 |
+
|
| 282 |
+
bucket_out = bucket_out.squeeze(0) # (k_capacity, d_thin)
|
| 283 |
+
bucket_out_full = self.w_up(bucket_out) # (k_capacity, d_model)
|
| 284 |
+
|
| 285 |
+
gate = topk_scores[i].unsqueeze(-1) # (k_capacity, 1)
|
| 286 |
+
expert_outputs_flat.index_add_(0, sel_idx, bucket_out_full * gate)
|
| 287 |
+
|
| 288 |
+
x_3_full = expert_outputs_flat.view(B, T, self.d_model)
|
| 289 |
+
out = x_2 + x_3_full
|
| 290 |
+
|
| 291 |
+
present_kvs = tuple(new_kvs) if use_cache else None
|
| 292 |
+
return out, present_kvs, layer_aux_loss
|
| 293 |
+
|
| 294 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 295 |
+
# 4. RAW MSIT-GPT-BERT MODEL
|
| 296 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 297 |
+
|
| 298 |
+
class MSITGPTBERTModel(nn.Module):
|
| 299 |
+
def __init__(self, cfg):
|
| 300 |
+
super().__init__()
|
| 301 |
+
self.cfg = cfg
|
| 302 |
+
self.wte = nn.Embedding(cfg.vocab_size, cfg.d_model)
|
| 303 |
+
self.drop_emb = nn.Dropout(cfg.dropout)
|
| 304 |
+
self.blocks = nn.ModuleList([
|
| 305 |
+
MoEPMSITBlock(
|
| 306 |
+
d_model=cfg.d_model,
|
| 307 |
+
d_thin=cfg.d_thin,
|
| 308 |
+
num_blocks=cfg.num_blocks,
|
| 309 |
+
capacity_factor=cfg.capacity_factor
|
| 310 |
+
)
|
| 311 |
+
for _ in range(cfg.num_layers)
|
| 312 |
+
])
|
| 313 |
+
self.ln_f = nn.LayerNorm(cfg.d_model)
|
| 314 |
+
self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
|
| 315 |
+
self.wte.weight = self.lm_head.weight
|
| 316 |
+
|
| 317 |
+
def forward(self, input_ids: torch.Tensor, targets: torch.Tensor = None, bidirectional: bool = False):
|
| 318 |
+
x = self.drop_emb(self.wte(input_ids))
|
| 319 |
+
total_aux_loss = 0.0
|
| 320 |
+
|
| 321 |
+
for block in self.blocks:
|
| 322 |
+
x, _, layer_aux = block(x, past_kvs=None, use_cache=False, bidirectional=bidirectional)
|
| 323 |
+
total_aux_loss += layer_aux
|
| 324 |
+
|
| 325 |
+
x = self.ln_f(x)
|
| 326 |
+
logits = self.lm_head(x)
|
| 327 |
+
|
| 328 |
+
loss = None
|
| 329 |
+
if targets is not None:
|
| 330 |
+
ce_loss = F.cross_entropy(logits.view(-1, self.cfg.vocab_size), targets.view(-1), ignore_index=-100)
|
| 331 |
+
avg_aux_loss = total_aux_loss / self.cfg.num_layers
|
| 332 |
+
loss = ce_loss + (0.01 * avg_aux_loss)
|
| 333 |
+
|
| 334 |
+
return logits, loss
|
| 335 |
+
|
| 336 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 337 |
+
# 5. HUGGING FACE MODEL WRAPPERS
|
| 338 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 339 |
+
|
| 340 |
+
class MSITGPTBERTModelWrapper(PreTrainedModel):
|
| 341 |
+
config_class = MSITGPTBERTHFConfig
|
| 342 |
+
base_model_prefix = "transformer"
|
| 343 |
+
|
| 344 |
+
def __init__(self, config: MSITGPTBERTHFConfig):
|
| 345 |
+
super().__init__(config)
|
| 346 |
+
self.wte = nn.Embedding(config.vocab_size, config.d_model)
|
| 347 |
+
self.drop_emb = nn.Dropout(config.dropout)
|
| 348 |
+
self.blocks = nn.ModuleList([
|
| 349 |
+
MoEPMSITBlock(config.d_model, config.d_thin, config.num_blocks, config.capacity_factor)
|
| 350 |
+
for _ in range(config.num_layers)
|
| 351 |
+
])
|
| 352 |
+
self.ln_f = nn.LayerNorm(config.d_model)
|
| 353 |
+
self.post_init()
|
| 354 |
+
|
| 355 |
+
def forward(self, input_ids, **kwargs):
|
| 356 |
+
x = self.drop_emb(self.wte(input_ids))
|
| 357 |
+
for block in self.blocks:
|
| 358 |
+
x, _, _ = block(x, past_kvs=None, use_cache=False, bidirectional=False)
|
| 359 |
+
x = self.ln_f(x)
|
| 360 |
+
return BaseModelOutputWithPast(last_hidden_state=x)
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
class MSITGPTBERTForCausalLM(PreTrainedModel, GenerationMixin):
|
| 364 |
+
config_class = MSITGPTBERTHFConfig
|
| 365 |
+
base_model_prefix = "transformer"
|
| 366 |
+
_no_split_modules = ["MoEPMSITBlock"]
|
| 367 |
+
_tied_weights_keys = {"transformer.lm_head.weight": "transformer.wte.weight"}
|
| 368 |
+
|
| 369 |
+
def __init__(self, config: MSITGPTBERTHFConfig):
|
| 370 |
+
super().__init__(config)
|
| 371 |
+
self.transformer = MSITGPTBERTModelWrapper(config)
|
| 372 |
+
self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
|
| 373 |
+
self.post_init()
|
| 374 |
+
|
| 375 |
+
# State-dict pre-hook for backwards compatibility with checkpoint key naming
|
| 376 |
+
def _prefix_cleaner(state_dict, prefix, local_metadata, Moore, missing_keys, unexpected_keys, error_msgs):
|
| 377 |
+
keys = list(state_dict.keys())
|
| 378 |
+
for k in keys:
|
| 379 |
+
if k.startswith("transformer."):
|
| 380 |
+
state_dict[k.replace("transformer.", "", 1)] = state_dict.pop(k)
|
| 381 |
+
elif f"{prefix}transformer." in k:
|
| 382 |
+
state_dict[k.replace("transformer.", "", 1)] = state_dict.pop(k)
|
| 383 |
+
|
| 384 |
+
self._register_load_state_dict_pre_hook(_prefix_cleaner)
|
| 385 |
+
|
| 386 |
+
def tie_weights(self, **kwargs):
|
| 387 |
+
if hasattr(self, "transformer") and hasattr(self.transformer, "wte") and hasattr(self.transformer, "lm_head"):
|
| 388 |
+
self.transformer.wte.weight = self.lm_head.weight
|
| 389 |
+
|
| 390 |
+
def get_input_embeddings(self):
|
| 391 |
+
return self.transformer.wte
|
| 392 |
+
|
| 393 |
+
def set_input_embeddings(self, new_embeddings):
|
| 394 |
+
self.transformer.wte = new_embeddings
|
| 395 |
+
|
| 396 |
+
def get_output_embeddings(self):
|
| 397 |
+
return self.lm_head
|
| 398 |
+
|
| 399 |
+
def set_output_embeddings(self, new_embeddings):
|
| 400 |
+
self.lm_head = new_embeddings
|
| 401 |
+
|
| 402 |
+
def forward(self,
|
| 403 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 404 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 405 |
+
labels: Optional[torch.LongTensor] = None,
|
| 406 |
+
**kwargs) -> CausalLMOutputWithPast:
|
| 407 |
+
outputs = self.transformer(input_ids)
|
| 408 |
+
hidden_states = outputs.last_hidden_state
|
| 409 |
+
logits = self.lm_head(hidden_states)
|
| 410 |
+
|
| 411 |
+
loss = None
|
| 412 |
+
if labels is not None:
|
| 413 |
+
shift_logits = logits[:, :-1, :].contiguous()
|
| 414 |
+
shift_labels = labels[:, 1:].contiguous()
|
| 415 |
+
loss = F.cross_entropy(
|
| 416 |
+
shift_logits.view(-1, self.config.vocab_size),
|
| 417 |
+
shift_labels.view(-1),
|
| 418 |
+
ignore_index=-100
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
return CausalLMOutputWithPast(
|
| 422 |
+
loss=loss,
|
| 423 |
+
logits=logits,
|
| 424 |
+
past_key_values=None,
|
| 425 |
+
hidden_states=None,
|
| 426 |
+
attentions=None,
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
def prepare_inputs_for_generation(self, input_ids, **kwargs):
|
| 430 |
+
return {"input_ids": input_ids}
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
# Register with auto-mapping
|
| 434 |
+
AutoConfig.register("msit_gptbert", MSITGPTBERTHFConfig)
|
| 435 |
+
AutoModel.register(MSITGPTBERTHFConfig, MSITGPTBERTModelWrapper)
|
| 436 |
+
AutoModelForCausalLM.register(MSITGPTBERTHFConfig, MSITGPTBERTForCausalLM)
|
chck_40M/pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5f207c3828c6d6f7bb7b50580b81130a2d3b38fd7ef8e519718bffbc2bbd6e4a
|
| 3 |
+
size 135253367
|
chck_40M/tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
chck_40M/tokenizer_config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "tokenizers",
|
| 3 |
+
"bos_token": "[CLS]",
|
| 4 |
+
"eos_token": "[SEP]",
|
| 5 |
+
"mask_token": "[MASK]",
|
| 6 |
+
"model_max_length": 1000000000000000019884624838656,
|
| 7 |
+
"pad_token": "[PAD]",
|
| 8 |
+
"tokenizer_class": "TokenizersBackend",
|
| 9 |
+
"unk_token": "[UNK]"
|
| 10 |
+
}
|
chck_4M/config.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"auto_map": {
|
| 3 |
+
"AutoConfig": "modeling_msit.MSITGPTBERTHFConfig",
|
| 4 |
+
"AutoModel": "modeling_msit.MSITGPTBERTModelWrapper",
|
| 5 |
+
"AutoModelForCausalLM": "modeling_msit.MSITGPTBERTForCausalLM"
|
| 6 |
+
},
|
| 7 |
+
"vocab_size": 16384,
|
| 8 |
+
"block_size": 512,
|
| 9 |
+
"d_model": 384,
|
| 10 |
+
"hidden_size": 384,
|
| 11 |
+
"d_thin": 192,
|
| 12 |
+
"num_layers": 6,
|
| 13 |
+
"num_blocks": 6,
|
| 14 |
+
"capacity_factor": 2.0,
|
| 15 |
+
"dropout": 0.1,
|
| 16 |
+
"model_type": "msit_gptbert"
|
| 17 |
+
}
|