File size: 6,529 Bytes
2353ae6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.checkpoint import checkpoint
from .attention import GQAAttention
from .rmsnorm import RMSNorm
from .rope import rope_cache
from .swiglu import SwiGLU
class AETHERConfig:
vocab_size = 32000
hidden_size = 768
num_hidden_layers = 12
num_attention_heads = 12
num_key_value_heads = 4
head_dim = 64
intermediate_size = 2048
max_position_embeddings = 2048
rope_theta = 10000.0
rms_norm_eps = 1e-6
tie_word_embeddings = True
bias = False
gradient_checkpointing = True
dropout = 0.0
class AETHERBlock(nn.Module):
def __init__(self, config):
super().__init__()
self.input_layernorm = RMSNorm(
config.hidden_size,
config.rms_norm_eps,
)
self.self_attn = GQAAttention(
hidden_size=config.hidden_size,
num_attention_heads=config.num_attention_heads,
num_key_value_heads=config.num_key_value_heads,
head_dim=config.head_dim,
bias=config.bias,
)
self.post_attention_layernorm = RMSNorm(
config.hidden_size,
config.rms_norm_eps,
)
self.mlp = SwiGLU(
hidden_size=config.hidden_size,
intermediate_size=config.intermediate_size,
bias=config.bias,
)
def forward(self, x, cos, sin):
x = x + self.self_attn(
self.input_layernorm(x),
cos,
sin,
)
x = x + self.mlp(
self.post_attention_layernorm(x)
)
return x
class AETHER100M(nn.Module):
def __init__(self, config=None):
super().__init__()
if config is None:
config = AETHERConfig()
self.config = config
self.embed = nn.Embedding(
config.vocab_size,
config.hidden_size,
)
self.layers = nn.ModuleList(
[
AETHERBlock(config)
for _ in range(config.num_hidden_layers)
]
)
self.norm = RMSNorm(
config.hidden_size,
config.rms_norm_eps,
)
self.lm_head = nn.Linear(
config.hidden_size,
config.vocab_size,
bias=False,
)
if config.tie_word_embeddings:
self.lm_head.weight = self.embed.weight
self._init_weights()
def _init_weights(self):
std = 0.02
nn.init.normal_(
self.embed.weight,
mean=0.0,
std=std,
)
for module in self.modules():
if isinstance(module, nn.Linear):
if module.weight is self.embed.weight:
continue
nn.init.normal_(
module.weight,
mean=0.0,
std=std,
)
if module.bias is not None:
nn.init.zeros_(module.bias)
residual_scale = 1.0 / math.sqrt(
2 * self.config.num_hidden_layers
)
for layer in self.layers:
layer.self_attn.o_proj.weight.data.mul_(
residual_scale
)
layer.mlp.down_proj.weight.data.mul_(
residual_scale
)
def forward(
self,
input_ids,
labels=None,
):
B, T = input_ids.shape
if T > self.config.max_position_embeddings:
raise ValueError(
f"Sequence length {T} exceeds "
f"maximum {self.config.max_position_embeddings}"
)
x = self.embed(input_ids)
cos, sin = rope_cache(
seq_len=T,
head_dim=self.config.head_dim,
theta=self.config.rope_theta,
device=input_ids.device,
)
for layer in self.layers:
if (
self.config.gradient_checkpointing
and self.training
):
x = checkpoint(
layer,
x,
cos,
sin,
use_reentrant=False,
)
else:
x = layer(
x,
cos,
sin,
)
x = self.norm(x)
loss = None
logits = None
if labels is not None:
shift_x = x[:, :-1, :].contiguous()
shift_labels = labels[:, 1:].contiguous()
B, T, H = shift_x.shape
# Avoid creating the enormous
# [B, T, vocab_size] tensor at once.
chunk_tokens = 64
total_loss = torch.zeros(
(),
device=x.device,
dtype=torch.float32,
)
total_tokens = 0
flat_x = shift_x.view(
-1,
H,
)
flat_labels = shift_labels.view(
-1,
)
for start in range(
0,
B * T,
chunk_tokens,
):
end = min(
start + chunk_tokens,
B * T,
)
hidden_chunk = flat_x[
start:end
]
label_chunk = flat_labels[
start:end
]
logits_chunk = self.lm_head(
hidden_chunk
)
chunk_loss = F.cross_entropy(
logits_chunk,
label_chunk,
reduction="sum",
)
total_loss += chunk_loss.float()
total_tokens += label_chunk.numel()
loss = (
total_loss /
total_tokens
)
else:
logits = self.lm_head(x)
return {
"logits": logits,
"loss": loss,
}
def count_parameters(model):
return sum(
p.numel()
for p in model.parameters()
) |