Text Generation
Transformers
Safetensors
English
sentinel_brain
sentinel-prime
Mixture of Experts
sparse-mixture-of-experts
from-scratch
custom-architecture
custom_code
Instructions to use qubitpage/sentinel-prime-350m with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use qubitpage/sentinel-prime-350m with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="qubitpage/sentinel-prime-350m", trust_remote_code=True)# Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("qubitpage/sentinel-prime-350m", trust_remote_code=True, dtype="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps
- vLLM
How to use qubitpage/sentinel-prime-350m with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "qubitpage/sentinel-prime-350m" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "qubitpage/sentinel-prime-350m", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/qubitpage/sentinel-prime-350m
- SGLang
How to use qubitpage/sentinel-prime-350m with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "qubitpage/sentinel-prime-350m" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "qubitpage/sentinel-prime-350m", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "qubitpage/sentinel-prime-350m" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "qubitpage/sentinel-prime-350m", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use qubitpage/sentinel-prime-350m with Docker Model Runner:
docker model run hf.co/qubitpage/sentinel-prime-350m
Upload hf_model.py with huggingface_hub
Browse files- hf_model.py +428 -0
hf_model.py
ADDED
|
@@ -0,0 +1,428 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
HuggingFace-compatible wrappers for SentinelBrain.
|
| 3 |
+
|
| 4 |
+
Provides:
|
| 5 |
+
- SentinelBrainConfig(PretrainedConfig) — serializes to config.json
|
| 6 |
+
- SentinelBrainForCausalLM(PreTrainedModel) — from_pretrained / save_pretrained
|
| 7 |
+
- Auto-registration for AutoConfig / AutoModelForCausalLM
|
| 8 |
+
|
| 9 |
+
Usage:
|
| 10 |
+
from hf_model import SentinelBrainForCausalLM, SentinelBrainConfig
|
| 11 |
+
model = SentinelBrainForCausalLM.from_pretrained("qubitpage/sentinel-prime-nano")
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import math
|
| 15 |
+
import torch
|
| 16 |
+
import torch.nn as nn
|
| 17 |
+
import torch.nn.functional as F
|
| 18 |
+
from typing import Optional, Tuple, Union
|
| 19 |
+
from transformers import PretrainedConfig, PreTrainedModel, AutoConfig, AutoModelForCausalLM
|
| 20 |
+
from transformers.generation import GenerationMixin
|
| 21 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# ---------------------------------------------------------------------------
|
| 25 |
+
# Config
|
| 26 |
+
# ---------------------------------------------------------------------------
|
| 27 |
+
|
| 28 |
+
class SentinelBrainConfig(PretrainedConfig):
|
| 29 |
+
"""HuggingFace-compatible config for SentinelBrain."""
|
| 30 |
+
|
| 31 |
+
model_type = "sentinel_brain"
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self,
|
| 35 |
+
vocab_size: int = 100277,
|
| 36 |
+
d_model: int = 768,
|
| 37 |
+
n_layers: int = 12,
|
| 38 |
+
n_heads: int = 12,
|
| 39 |
+
n_kv_heads: int = 4,
|
| 40 |
+
d_ff: int = 2048,
|
| 41 |
+
max_seq_len: int = 1024,
|
| 42 |
+
n_experts: int = 4,
|
| 43 |
+
n_active_experts: int = 2,
|
| 44 |
+
expert_capacity_factor: float = 1.25,
|
| 45 |
+
router_aux_loss_coeff: float = 0.01,
|
| 46 |
+
router_z_loss_coeff: float = 0.001,
|
| 47 |
+
rope_theta: float = 500000.0,
|
| 48 |
+
norm_eps: float = 1e-5,
|
| 49 |
+
dropout: float = 0.0,
|
| 50 |
+
expert_dropout: float = 0.0,
|
| 51 |
+
tie_embeddings: bool = True,
|
| 52 |
+
routing_mode: str = "token_choice",
|
| 53 |
+
# Standard HF fields
|
| 54 |
+
bos_token_id: int = None,
|
| 55 |
+
eos_token_id: int = 100257,
|
| 56 |
+
pad_token_id: int = 100257,
|
| 57 |
+
**kwargs,
|
| 58 |
+
):
|
| 59 |
+
super().__init__(
|
| 60 |
+
bos_token_id=bos_token_id,
|
| 61 |
+
eos_token_id=eos_token_id,
|
| 62 |
+
pad_token_id=pad_token_id,
|
| 63 |
+
tie_word_embeddings=tie_embeddings,
|
| 64 |
+
**kwargs,
|
| 65 |
+
)
|
| 66 |
+
self.vocab_size = vocab_size
|
| 67 |
+
self.d_model = d_model
|
| 68 |
+
self.n_layers = n_layers
|
| 69 |
+
self.n_heads = n_heads
|
| 70 |
+
self.n_kv_heads = n_kv_heads
|
| 71 |
+
self.d_ff = d_ff
|
| 72 |
+
self.max_seq_len = max_seq_len
|
| 73 |
+
self.n_experts = n_experts
|
| 74 |
+
self.n_active_experts = n_active_experts
|
| 75 |
+
self.expert_capacity_factor = expert_capacity_factor
|
| 76 |
+
self.router_aux_loss_coeff = router_aux_loss_coeff
|
| 77 |
+
self.router_z_loss_coeff = router_z_loss_coeff
|
| 78 |
+
self.rope_theta = rope_theta
|
| 79 |
+
self.norm_eps = norm_eps
|
| 80 |
+
self.dropout = dropout
|
| 81 |
+
self.expert_dropout = expert_dropout
|
| 82 |
+
self.tie_embeddings = tie_embeddings
|
| 83 |
+
self.routing_mode = routing_mode
|
| 84 |
+
# Derived
|
| 85 |
+
self.hidden_size = d_model # HF convention
|
| 86 |
+
self.num_hidden_layers = n_layers
|
| 87 |
+
self.num_attention_heads = n_heads
|
| 88 |
+
|
| 89 |
+
@property
|
| 90 |
+
def head_dim(self) -> int:
|
| 91 |
+
return self.d_model // self.n_heads
|
| 92 |
+
|
| 93 |
+
@property
|
| 94 |
+
def kv_dim(self) -> int:
|
| 95 |
+
return self.n_kv_heads * self.head_dim
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# ---------------------------------------------------------------------------
|
| 99 |
+
# Layers (self-contained, no cross-imports)
|
| 100 |
+
# ---------------------------------------------------------------------------
|
| 101 |
+
|
| 102 |
+
class _RMSNorm(nn.Module):
|
| 103 |
+
def __init__(self, dim: int, eps: float = 1e-5):
|
| 104 |
+
super().__init__()
|
| 105 |
+
self.eps = eps
|
| 106 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 107 |
+
|
| 108 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 109 |
+
norm = torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + self.eps)
|
| 110 |
+
return (x.float() * norm).type_as(x) * self.weight
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class _RotaryEmbedding(nn.Module):
|
| 114 |
+
def __init__(self, head_dim: int, max_seq_len: int = 8192,
|
| 115 |
+
theta: float = 500000.0):
|
| 116 |
+
super().__init__()
|
| 117 |
+
self.head_dim = head_dim
|
| 118 |
+
self.max_seq_len = max_seq_len
|
| 119 |
+
self.theta = theta
|
| 120 |
+
self._build_cache(max_seq_len)
|
| 121 |
+
|
| 122 |
+
def _build_cache(self, seq_len: int):
|
| 123 |
+
freqs = 1.0 / (self.theta ** (
|
| 124 |
+
torch.arange(0, self.head_dim, 2).float() / self.head_dim
|
| 125 |
+
))
|
| 126 |
+
t = torch.arange(seq_len).float()
|
| 127 |
+
angles = torch.outer(t, freqs)
|
| 128 |
+
self.register_buffer("cos_cached", angles.cos().unsqueeze(0).unsqueeze(0),
|
| 129 |
+
persistent=False)
|
| 130 |
+
self.register_buffer("sin_cached", angles.sin().unsqueeze(0).unsqueeze(0),
|
| 131 |
+
persistent=False)
|
| 132 |
+
|
| 133 |
+
def forward(self, seq_len: int):
|
| 134 |
+
if seq_len > self.max_seq_len:
|
| 135 |
+
self._build_cache(seq_len * 2)
|
| 136 |
+
self.max_seq_len = seq_len * 2
|
| 137 |
+
return self.cos_cached[:, :, :seq_len], self.sin_cached[:, :, :seq_len]
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _apply_rope(x, cos, sin):
|
| 141 |
+
d2 = x.shape[-1] // 2
|
| 142 |
+
x1, x2 = x[..., :d2], x[..., d2:]
|
| 143 |
+
return torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class _SwiGLUFFN(nn.Module):
|
| 147 |
+
def __init__(self, d_model: int, d_ff: int, dropout: float = 0.0):
|
| 148 |
+
super().__init__()
|
| 149 |
+
self.w_gate = nn.Linear(d_model, d_ff, bias=False)
|
| 150 |
+
self.w_up = nn.Linear(d_model, d_ff, bias=False)
|
| 151 |
+
self.w_down = nn.Linear(d_ff, d_model, bias=False)
|
| 152 |
+
self.dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
|
| 153 |
+
|
| 154 |
+
def forward(self, x):
|
| 155 |
+
return self.dropout(self.w_down(F.silu(self.w_gate(x)) * self.w_up(x)))
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class _GQA(nn.Module):
|
| 159 |
+
def __init__(self, d_model, n_heads, n_kv_heads, head_dim, dropout=0.0):
|
| 160 |
+
super().__init__()
|
| 161 |
+
self.n_heads = n_heads
|
| 162 |
+
self.n_kv_heads = n_kv_heads
|
| 163 |
+
self.head_dim = head_dim
|
| 164 |
+
self.n_rep = n_heads // n_kv_heads
|
| 165 |
+
self.wq = nn.Linear(d_model, n_heads * head_dim, bias=False)
|
| 166 |
+
self.wk = nn.Linear(d_model, n_kv_heads * head_dim, bias=False)
|
| 167 |
+
self.wv = nn.Linear(d_model, n_kv_heads * head_dim, bias=False)
|
| 168 |
+
self.wo = nn.Linear(n_heads * head_dim, d_model, bias=False)
|
| 169 |
+
self.attn_dropout = dropout
|
| 170 |
+
|
| 171 |
+
def forward(self, x, rope_cos, rope_sin, mask=None, kv_cache=None):
|
| 172 |
+
B, T, _ = x.shape
|
| 173 |
+
q = self.wq(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
|
| 174 |
+
k = self.wk(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)
|
| 175 |
+
v = self.wv(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)
|
| 176 |
+
|
| 177 |
+
q = _apply_rope(q, rope_cos, rope_sin)
|
| 178 |
+
k = _apply_rope(k, rope_cos, rope_sin)
|
| 179 |
+
|
| 180 |
+
if kv_cache is not None:
|
| 181 |
+
k = torch.cat([kv_cache[0], k], dim=2)
|
| 182 |
+
v = torch.cat([kv_cache[1], v], dim=2)
|
| 183 |
+
new_kv = (k, v)
|
| 184 |
+
|
| 185 |
+
if self.n_rep > 1:
|
| 186 |
+
k = k.repeat_interleave(self.n_rep, dim=1)
|
| 187 |
+
v = v.repeat_interleave(self.n_rep, dim=1)
|
| 188 |
+
|
| 189 |
+
out = F.scaled_dot_product_attention(
|
| 190 |
+
q, k, v, is_causal=(kv_cache is None and T > 1),
|
| 191 |
+
dropout_p=self.attn_dropout if self.training else 0.0,
|
| 192 |
+
)
|
| 193 |
+
out = out.transpose(1, 2).contiguous().view(B, T, -1)
|
| 194 |
+
return self.wo(out), new_kv
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class _ExpertRouter(nn.Module):
|
| 198 |
+
def __init__(self, d_model, n_experts, n_active, aux_coeff=0.01, z_coeff=0.001):
|
| 199 |
+
super().__init__()
|
| 200 |
+
self.n_experts = n_experts
|
| 201 |
+
self.n_active = n_active
|
| 202 |
+
self.aux_coeff = aux_coeff
|
| 203 |
+
self.z_coeff = z_coeff
|
| 204 |
+
self.gate = nn.Linear(d_model, n_experts, bias=False)
|
| 205 |
+
|
| 206 |
+
def forward(self, x):
|
| 207 |
+
logits = self.gate(x)
|
| 208 |
+
probs = F.softmax(logits, dim=-1)
|
| 209 |
+
topk_w, topk_idx = torch.topk(probs, self.n_active, dim=-1)
|
| 210 |
+
topk_w = topk_w / (topk_w.sum(dim=-1, keepdim=True) + 1e-9)
|
| 211 |
+
|
| 212 |
+
# Aux loss
|
| 213 |
+
B, T, E = probs.shape
|
| 214 |
+
flat_probs = probs.view(-1, E)
|
| 215 |
+
flat_idx = topk_idx.view(-1, self.n_active)
|
| 216 |
+
one_hot = F.one_hot(flat_idx, E).float()
|
| 217 |
+
f = one_hot.sum(1).mean(0)
|
| 218 |
+
P = flat_probs.mean(0)
|
| 219 |
+
aux = self.aux_coeff * E * (f * P).sum()
|
| 220 |
+
|
| 221 |
+
# Z loss
|
| 222 |
+
log_z = torch.logsumexp(logits, dim=-1)
|
| 223 |
+
z = self.z_coeff * log_z.square().mean()
|
| 224 |
+
|
| 225 |
+
return topk_w, topk_idx, aux, z
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
class _SparseMoE(nn.Module):
|
| 229 |
+
def __init__(self, d_model, d_ff, n_experts, n_active, dropout=0.0,
|
| 230 |
+
aux_coeff=0.01, z_coeff=0.001):
|
| 231 |
+
super().__init__()
|
| 232 |
+
self.n_experts = n_experts
|
| 233 |
+
self.n_active = n_active
|
| 234 |
+
self.router = _ExpertRouter(d_model, n_experts, n_active, aux_coeff, z_coeff)
|
| 235 |
+
self.experts = nn.ModuleList([
|
| 236 |
+
_SwiGLUFFN(d_model, d_ff, dropout) for _ in range(n_experts)
|
| 237 |
+
])
|
| 238 |
+
|
| 239 |
+
def forward(self, x):
|
| 240 |
+
B, T, D = x.shape
|
| 241 |
+
weights, indices, aux, z = self.router(x)
|
| 242 |
+
|
| 243 |
+
flat_x = x.view(-1, D)
|
| 244 |
+
flat_w = weights.view(-1, self.n_active)
|
| 245 |
+
flat_idx = indices.view(-1, self.n_active)
|
| 246 |
+
out = torch.zeros_like(flat_x)
|
| 247 |
+
|
| 248 |
+
for k in range(self.n_active):
|
| 249 |
+
expert_idx = flat_idx[:, k]
|
| 250 |
+
w = flat_w[:, k].unsqueeze(-1)
|
| 251 |
+
for e in range(self.n_experts):
|
| 252 |
+
mask = (expert_idx == e)
|
| 253 |
+
if mask.any():
|
| 254 |
+
out[mask] += w[mask] * self.experts[e](flat_x[mask])
|
| 255 |
+
|
| 256 |
+
return out.view(B, T, D), aux, z
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
class _TransformerBlock(nn.Module):
|
| 260 |
+
def __init__(self, cfg: SentinelBrainConfig, layer_idx: int):
|
| 261 |
+
super().__init__()
|
| 262 |
+
self.attn_norm = _RMSNorm(cfg.d_model, cfg.norm_eps)
|
| 263 |
+
self.attn = _GQA(cfg.d_model, cfg.n_heads, cfg.n_kv_heads,
|
| 264 |
+
cfg.head_dim, cfg.dropout)
|
| 265 |
+
self.ffn_norm = _RMSNorm(cfg.d_model, cfg.norm_eps)
|
| 266 |
+
|
| 267 |
+
if cfg.n_experts > 1:
|
| 268 |
+
self.ffn = _SparseMoE(cfg.d_model, cfg.d_ff, cfg.n_experts,
|
| 269 |
+
cfg.n_active_experts, cfg.expert_dropout,
|
| 270 |
+
cfg.router_aux_loss_coeff, cfg.router_z_loss_coeff)
|
| 271 |
+
self.is_moe = True
|
| 272 |
+
else:
|
| 273 |
+
self.ffn = _SwiGLUFFN(cfg.d_model, cfg.d_ff, cfg.dropout)
|
| 274 |
+
self.is_moe = False
|
| 275 |
+
|
| 276 |
+
def forward(self, x, rope_cos, rope_sin, kv_cache=None):
|
| 277 |
+
residual = x
|
| 278 |
+
x = self.attn_norm(x)
|
| 279 |
+
attn_out, new_kv = self.attn(x, rope_cos, rope_sin, kv_cache=kv_cache)
|
| 280 |
+
x = residual + attn_out
|
| 281 |
+
|
| 282 |
+
residual = x
|
| 283 |
+
x = self.ffn_norm(x)
|
| 284 |
+
aux, z = 0.0, 0.0
|
| 285 |
+
if self.is_moe:
|
| 286 |
+
ffn_out, aux, z = self.ffn(x)
|
| 287 |
+
else:
|
| 288 |
+
ffn_out = self.ffn(x)
|
| 289 |
+
x = residual + ffn_out
|
| 290 |
+
return x, new_kv, aux, z
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
# ---------------------------------------------------------------------------
|
| 294 |
+
# HF PreTrainedModel
|
| 295 |
+
# ---------------------------------------------------------------------------
|
| 296 |
+
|
| 297 |
+
class SentinelBrainForCausalLM(PreTrainedModel, GenerationMixin):
|
| 298 |
+
"""HuggingFace-compatible wrapper for SentinelBrain causal LM."""
|
| 299 |
+
|
| 300 |
+
config_class = SentinelBrainConfig
|
| 301 |
+
supports_gradient_checkpointing = True
|
| 302 |
+
_no_split_modules = ["_TransformerBlock"]
|
| 303 |
+
def __init__(self, config: SentinelBrainConfig):
|
| 304 |
+
super().__init__(config)
|
| 305 |
+
|
| 306 |
+
self.tok_emb = nn.Embedding(config.vocab_size, config.d_model)
|
| 307 |
+
self.rope = _RotaryEmbedding(config.head_dim, config.max_seq_len * 2,
|
| 308 |
+
config.rope_theta)
|
| 309 |
+
self.layers = nn.ModuleList([
|
| 310 |
+
_TransformerBlock(config, i) for i in range(config.n_layers)
|
| 311 |
+
])
|
| 312 |
+
self.norm = _RMSNorm(config.d_model, config.norm_eps)
|
| 313 |
+
self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
|
| 314 |
+
|
| 315 |
+
if getattr(config, "tie_embeddings", True) and getattr(config, "tie_word_embeddings", True):
|
| 316 |
+
self.lm_head.weight = self.tok_emb.weight
|
| 317 |
+
|
| 318 |
+
self.post_init()
|
| 319 |
+
|
| 320 |
+
def get_input_embeddings(self):
|
| 321 |
+
return self.tok_emb
|
| 322 |
+
|
| 323 |
+
def set_input_embeddings(self, value):
|
| 324 |
+
self.tok_emb = value
|
| 325 |
+
|
| 326 |
+
def get_output_embeddings(self):
|
| 327 |
+
return self.lm_head
|
| 328 |
+
|
| 329 |
+
def set_output_embeddings(self, new_embeddings):
|
| 330 |
+
self.lm_head = new_embeddings
|
| 331 |
+
|
| 332 |
+
def get_expanded_tied_weights_keys(self, all_submodels=False):
|
| 333 |
+
# Return empty dict — manual tying in __init__
|
| 334 |
+
return {}
|
| 335 |
+
|
| 336 |
+
def tie_weights(self, recompute_mapping=True):
|
| 337 |
+
# No-op — manual tying handled in __init__; bypass transformers tying machinery entirely
|
| 338 |
+
return
|
| 339 |
+
|
| 340 |
+
def forward(
|
| 341 |
+
self,
|
| 342 |
+
input_ids: torch.LongTensor = None,
|
| 343 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 344 |
+
past_key_values: Optional[list] = None,
|
| 345 |
+
labels: Optional[torch.LongTensor] = None,
|
| 346 |
+
use_cache: Optional[bool] = None,
|
| 347 |
+
output_attentions: Optional[bool] = None,
|
| 348 |
+
output_hidden_states: Optional[bool] = None,
|
| 349 |
+
return_dict: Optional[bool] = None,
|
| 350 |
+
**kwargs,
|
| 351 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 352 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 353 |
+
use_cache = use_cache if use_cache is not None else False
|
| 354 |
+
|
| 355 |
+
B, T = input_ids.shape
|
| 356 |
+
x = self.tok_emb(input_ids)
|
| 357 |
+
|
| 358 |
+
# Determine if we have valid past KV caches
|
| 359 |
+
has_past = False
|
| 360 |
+
past_len = 0
|
| 361 |
+
if past_key_values is not None and len(past_key_values) > 0:
|
| 362 |
+
first = past_key_values[0]
|
| 363 |
+
if first is not None:
|
| 364 |
+
if isinstance(first, (tuple, list)) and len(first) > 0 and first[0] is not None:
|
| 365 |
+
has_past = True
|
| 366 |
+
past_len = first[0].shape[2]
|
| 367 |
+
elif hasattr(first, 'shape'):
|
| 368 |
+
has_past = True
|
| 369 |
+
past_len = first.shape[2]
|
| 370 |
+
|
| 371 |
+
rope_cos, rope_sin = self.rope(past_len + T)
|
| 372 |
+
rope_cos = rope_cos[:, :, past_len:past_len + T].to(x.device)
|
| 373 |
+
rope_sin = rope_sin[:, :, past_len:past_len + T].to(x.device)
|
| 374 |
+
|
| 375 |
+
new_kv_caches = []
|
| 376 |
+
total_aux = 0.0
|
| 377 |
+
total_z = 0.0
|
| 378 |
+
|
| 379 |
+
for i, layer in enumerate(self.layers):
|
| 380 |
+
kv_cache = past_key_values[i] if has_past else None
|
| 381 |
+
x, new_kv, aux, z = layer(x, rope_cos, rope_sin, kv_cache=kv_cache)
|
| 382 |
+
new_kv_caches.append(new_kv)
|
| 383 |
+
total_aux += aux
|
| 384 |
+
total_z += z
|
| 385 |
+
|
| 386 |
+
x = self.norm(x)
|
| 387 |
+
logits = self.lm_head(x)
|
| 388 |
+
|
| 389 |
+
loss = None
|
| 390 |
+
if labels is not None:
|
| 391 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 392 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 393 |
+
loss = F.cross_entropy(
|
| 394 |
+
shift_logits.view(-1, shift_logits.size(-1)),
|
| 395 |
+
shift_labels.view(-1),
|
| 396 |
+
ignore_index=-100,
|
| 397 |
+
)
|
| 398 |
+
# Add MoE losses
|
| 399 |
+
n_moe = sum(1 for l in self.layers if l.is_moe)
|
| 400 |
+
if n_moe > 0:
|
| 401 |
+
loss = loss + total_aux / n_moe + total_z / n_moe
|
| 402 |
+
|
| 403 |
+
if not return_dict:
|
| 404 |
+
output = (logits, new_kv_caches if use_cache else None)
|
| 405 |
+
return ((loss,) + output) if loss is not None else output
|
| 406 |
+
|
| 407 |
+
return CausalLMOutputWithPast(
|
| 408 |
+
loss=loss,
|
| 409 |
+
logits=logits,
|
| 410 |
+
past_key_values=new_kv_caches if use_cache else None,
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **kwargs):
|
| 414 |
+
if past_key_values is not None:
|
| 415 |
+
input_ids = input_ids[:, -1:]
|
| 416 |
+
return {
|
| 417 |
+
"input_ids": input_ids,
|
| 418 |
+
"past_key_values": past_key_values,
|
| 419 |
+
"use_cache": True,
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
# ---------------------------------------------------------------------------
|
| 424 |
+
# Auto-registration
|
| 425 |
+
# ---------------------------------------------------------------------------
|
| 426 |
+
|
| 427 |
+
AutoConfig.register("sentinel_brain", SentinelBrainConfig)
|
| 428 |
+
AutoModelForCausalLM.register(SentinelBrainConfig, SentinelBrainForCausalLM)
|