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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""HF-compatible inference wrapper for Slayer's trained BalancedLM weights."""
|
| 2 |
+
import math
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch import nn
|
| 6 |
+
from torch.nn import functional as F
|
| 7 |
+
from transformers import PretrainedConfig, PreTrainedModel
|
| 8 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class SlayerBalancedConfig(PretrainedConfig):
|
| 12 |
+
model_type = "slayer_balanced"
|
| 13 |
+
|
| 14 |
+
def __init__(self, vocab_size=24576, hidden_size=576, intermediate_size=2496,
|
| 15 |
+
num_hidden_layers=26, num_attention_heads=9, num_key_value_heads=3,
|
| 16 |
+
head_dim=64, max_position_embeddings=2048, rms_norm_eps=1e-6,
|
| 17 |
+
rope_parameters=None, tie_word_embeddings=True, **kwargs):
|
| 18 |
+
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
|
| 19 |
+
self.vocab_size = vocab_size
|
| 20 |
+
self.hidden_size = hidden_size
|
| 21 |
+
self.intermediate_size = intermediate_size
|
| 22 |
+
self.num_hidden_layers = num_hidden_layers
|
| 23 |
+
self.num_attention_heads = num_attention_heads
|
| 24 |
+
self.num_key_value_heads = num_key_value_heads
|
| 25 |
+
self.head_dim = head_dim
|
| 26 |
+
self.max_position_embeddings = max_position_embeddings
|
| 27 |
+
self.rms_norm_eps = rms_norm_eps
|
| 28 |
+
self.rope_parameters = rope_parameters or {"rope_theta": 10000.0, "rope_type": "default"}
|
| 29 |
+
self.use_cache = False
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class RMSNorm(nn.Module):
|
| 33 |
+
def __init__(self, width, eps):
|
| 34 |
+
super().__init__()
|
| 35 |
+
self.weight = nn.Parameter(torch.ones(width))
|
| 36 |
+
self.eps = eps
|
| 37 |
+
|
| 38 |
+
def forward(self, x):
|
| 39 |
+
dtype = x.dtype
|
| 40 |
+
x = x.float()
|
| 41 |
+
return self.weight * (x * torch.rsqrt(x.square().mean(-1, keepdim=True) + self.eps)).to(dtype)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class ValueProjection(nn.Linear):
|
| 45 |
+
def __init__(self, width, out, first):
|
| 46 |
+
super().__init__(width, out, bias=False)
|
| 47 |
+
if not first:
|
| 48 |
+
self.vr_lambda = nn.Parameter(torch.zeros(1))
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class SlayerAttention(nn.Module):
|
| 52 |
+
def __init__(self, c, index):
|
| 53 |
+
super().__init__()
|
| 54 |
+
h = c.hidden_size
|
| 55 |
+
self.heads, self.kv, self.d = c.num_attention_heads, c.num_key_value_heads, c.head_dim
|
| 56 |
+
self.first = index == 0
|
| 57 |
+
self.q_proj = nn.Linear(h, self.heads * self.d, bias=False)
|
| 58 |
+
self.k_proj = nn.Linear(h, self.kv * self.d, bias=False)
|
| 59 |
+
self.v_proj = ValueProjection(h, self.kv * self.d, self.first)
|
| 60 |
+
self.o_proj = nn.Linear(self.heads * self.d, h, bias=False)
|
| 61 |
+
self.q_norm, self.k_norm = RMSNorm(self.d, c.rms_norm_eps), RMSNorm(self.d, c.rms_norm_eps)
|
| 62 |
+
|
| 63 |
+
def forward(self, x, cos, sin, v0, attention_mask=None, output_attentions=False):
|
| 64 |
+
b, t, _ = x.shape
|
| 65 |
+
q = self.q_norm(self.q_proj(x).view(b, t, self.heads, self.d)).transpose(1, 2)
|
| 66 |
+
k = self.k_norm(self.k_proj(x).view(b, t, self.kv, self.d)).transpose(1, 2)
|
| 67 |
+
v = self.v_proj(x)
|
| 68 |
+
if self.first:
|
| 69 |
+
v0 = v
|
| 70 |
+
else:
|
| 71 |
+
v = v + self.v_proj.vr_lambda * v0
|
| 72 |
+
v = v.view(b, t, self.kv, self.d).transpose(1, 2)
|
| 73 |
+
if self.heads != self.kv:
|
| 74 |
+
rep = self.heads // self.kv
|
| 75 |
+
k = k.repeat_interleave(rep, dim=1)
|
| 76 |
+
v = v.repeat_interleave(rep, dim=1)
|
| 77 |
+
|
| 78 |
+
def rotate(z):
|
| 79 |
+
return torch.cat((-z[..., self.d // 2:], z[..., :self.d // 2]), dim=-1)
|
| 80 |
+
|
| 81 |
+
q, k = q * cos + rotate(q) * sin, k * cos + rotate(k) * sin
|
| 82 |
+
probs = None
|
| 83 |
+
if output_attentions:
|
| 84 |
+
scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.d)
|
| 85 |
+
causal = torch.ones((t, t), dtype=torch.bool, device=x.device).tril()
|
| 86 |
+
scores = scores.masked_fill(~causal, torch.finfo(scores.dtype).min)
|
| 87 |
+
if attention_mask is not None:
|
| 88 |
+
scores = scores.masked_fill(~attention_mask[:, None, None, :].bool(), torch.finfo(scores.dtype).min)
|
| 89 |
+
probs = scores.softmax(dim=-1)
|
| 90 |
+
out = probs @ v
|
| 91 |
+
else:
|
| 92 |
+
if attention_mask is None:
|
| 93 |
+
out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
|
| 94 |
+
else:
|
| 95 |
+
causal = torch.ones((t, t), dtype=torch.bool, device=x.device).tril()
|
| 96 |
+
allowed = causal[None, None] & attention_mask[:, None, None, :].bool()
|
| 97 |
+
out = F.scaled_dot_product_attention(q, k, v, attn_mask=allowed, is_causal=False)
|
| 98 |
+
out = self.o_proj(out.transpose(1, 2).contiguous().view(b, t, -1))
|
| 99 |
+
return out, v0, probs
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class SlayerMLP(nn.Module):
|
| 103 |
+
def __init__(self, c):
|
| 104 |
+
super().__init__()
|
| 105 |
+
h, f = c.hidden_size, c.intermediate_size
|
| 106 |
+
self.gate_proj = nn.Linear(h, f, bias=False)
|
| 107 |
+
self.up_proj = nn.Linear(h, f, bias=False)
|
| 108 |
+
self.down_proj = nn.Linear(f, h, bias=False)
|
| 109 |
+
|
| 110 |
+
def forward(self, x):
|
| 111 |
+
return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class SlayerBlock(nn.Module):
|
| 115 |
+
def __init__(self, c, index):
|
| 116 |
+
super().__init__()
|
| 117 |
+
self.self_attn = SlayerAttention(c, index)
|
| 118 |
+
self.mlp = SlayerMLP(c)
|
| 119 |
+
self.input_layernorm = RMSNorm(c.hidden_size, c.rms_norm_eps)
|
| 120 |
+
self.post_attention_layernorm = RMSNorm(c.hidden_size, c.rms_norm_eps)
|
| 121 |
+
|
| 122 |
+
def forward(self, x, cos, sin, v0, mask, output_attentions):
|
| 123 |
+
attn, v0, probs = self.self_attn(self.input_layernorm(x), cos, sin, v0, mask, output_attentions)
|
| 124 |
+
x = x + attn
|
| 125 |
+
return x + self.mlp(self.post_attention_layernorm(x)), v0, probs
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class SlayerBackbone(nn.Module):
|
| 129 |
+
def __init__(self, c):
|
| 130 |
+
super().__init__()
|
| 131 |
+
self.embed_tokens = nn.Embedding(c.vocab_size, c.hidden_size)
|
| 132 |
+
self.layers = nn.ModuleList(SlayerBlock(c, i) for i in range(c.num_hidden_layers))
|
| 133 |
+
self.norm = RMSNorm(c.hidden_size, c.rms_norm_eps)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class SlayerForCausalLM(PreTrainedModel):
|
| 137 |
+
config_class = SlayerBalancedConfig
|
| 138 |
+
base_model_prefix = "model"
|
| 139 |
+
_no_split_modules = ["SlayerBlock"]
|
| 140 |
+
_supports_sdpa = True
|
| 141 |
+
|
| 142 |
+
def __init__(self, config):
|
| 143 |
+
super().__init__(config)
|
| 144 |
+
self.model = SlayerBackbone(config)
|
| 145 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 146 |
+
self.post_init()
|
| 147 |
+
|
| 148 |
+
def get_input_embeddings(self):
|
| 149 |
+
return self.model.embed_tokens
|
| 150 |
+
|
| 151 |
+
def set_input_embeddings(self, value):
|
| 152 |
+
self.model.embed_tokens = value
|
| 153 |
+
|
| 154 |
+
def get_output_embeddings(self):
|
| 155 |
+
return self.lm_head
|
| 156 |
+
|
| 157 |
+
def set_output_embeddings(self, value):
|
| 158 |
+
self.lm_head = value
|
| 159 |
+
|
| 160 |
+
def forward(self, input_ids=None, attention_mask=None, position_ids=None, inputs_embeds=None, labels=None,
|
| 161 |
+
output_attentions=None, use_cache=None, return_dict=None, **kwargs):
|
| 162 |
+
if inputs_embeds is None:
|
| 163 |
+
inputs_embeds = self.model.embed_tokens(input_ids)
|
| 164 |
+
_, t, _ = inputs_embeds.shape
|
| 165 |
+
d = self.config.head_dim
|
| 166 |
+
theta = self.config.rope_parameters.get("rope_theta", 10000.0)
|
| 167 |
+
inv = 1.0 / theta ** (torch.arange(0, d, 2, device=inputs_embeds.device, dtype=torch.float32) / d)
|
| 168 |
+
if position_ids is None:
|
| 169 |
+
if attention_mask is None:
|
| 170 |
+
position_ids = torch.arange(t, device=inputs_embeds.device)[None, :].expand(inputs_embeds.shape[0], -1)
|
| 171 |
+
else:
|
| 172 |
+
position_ids = (attention_mask.long().cumsum(-1) - 1).clamp_min(0)
|
| 173 |
+
phase = position_ids.to(torch.float32).unsqueeze(-1) * inv
|
| 174 |
+
phase = torch.cat((phase, phase), dim=-1)
|
| 175 |
+
cos = phase.cos()[:, None].to(inputs_embeds.dtype)
|
| 176 |
+
sin = phase.sin()[:, None].to(inputs_embeds.dtype)
|
| 177 |
+
x, v0 = inputs_embeds, None
|
| 178 |
+
attentions = [] if output_attentions else None
|
| 179 |
+
for layer in self.model.layers:
|
| 180 |
+
x, v0, attn = layer(x, cos, sin, v0, attention_mask, bool(output_attentions))
|
| 181 |
+
if attentions is not None:
|
| 182 |
+
attentions.append(attn)
|
| 183 |
+
logits = self.lm_head(self.model.norm(x))
|
| 184 |
+
loss = None
|
| 185 |
+
if labels is not None:
|
| 186 |
+
loss = F.cross_entropy(logits[:, :-1].float().reshape(-1, logits.size(-1)), labels[:, 1:].reshape(-1))
|
| 187 |
+
return CausalLMOutputWithPast(
|
| 188 |
+
loss=loss, logits=logits, past_key_values=None,
|
| 189 |
+
attentions=tuple(attentions) if attentions is not None else None,
|
| 190 |
+
)
|