Spaces:
Sleeping
Sleeping
Update model.py
Browse files
model.py
CHANGED
|
@@ -1,551 +1,557 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import math
|
| 3 |
-
from typing import List, Optional, Tuple, Union
|
| 4 |
-
import time
|
| 5 |
-
import inspect
|
| 6 |
-
from dataclasses import dataclass
|
| 7 |
-
import torch
|
| 8 |
-
import torch.nn as nn
|
| 9 |
-
from torch.nn import functional as F
|
| 10 |
-
import torch.utils.checkpoint
|
| 11 |
-
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 12 |
-
from torch.utils.data import DataLoader
|
| 13 |
-
|
| 14 |
-
from datasets import load_dataset
|
| 15 |
-
from transformers import GPT2Tokenizer
|
| 16 |
-
|
| 17 |
-
import pytorch_lightning as pl
|
| 18 |
-
from pytorch_lightning.callbacks import LearningRateMonitor, RichProgressBar
|
| 19 |
-
from pytorch_lightning.loggers import WandbLogger
|
| 20 |
-
from lightning.pytorch.callbacks.progress.rich_progress import RichProgressBarTheme
|
| 21 |
-
from pytorch_lightning.callbacks import ModelCheckpoint
|
| 22 |
-
|
| 23 |
-
@dataclass
|
| 24 |
-
class SmolLM2Config:
|
| 25 |
-
hidden_size: int = 576
|
| 26 |
-
intermediate_size: int = 1536
|
| 27 |
-
num_hidden_layers: int = 30
|
| 28 |
-
num_attention_heads: int = 9
|
| 29 |
-
num_key_value_heads: int = 3
|
| 30 |
-
hidden_act: str = "silu"
|
| 31 |
-
max_position_embeddings: int = 2048
|
| 32 |
-
initializer_range: float = 0.041666666666666664
|
| 33 |
-
rms_norm_eps: float = 1.0e-05
|
| 34 |
-
vocab_size: int = 49152
|
| 35 |
-
rope_theta: float = 10000.0
|
| 36 |
-
use_cache: bool = True
|
| 37 |
-
tie_word_embeddings: bool = True
|
| 38 |
-
torch_dtype: str = "float32"
|
| 39 |
-
block_size: int = 512
|
| 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 |
-
self.
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
self.
|
| 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 |
-
self
|
| 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 |
-
self.
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
self,
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
if past_key_value is not None:
|
| 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 |
-
if
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
attn_output =
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
self.
|
| 295 |
-
self.
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
(
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
hidden_states = residual + hidden_states
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
self.
|
| 361 |
-
self.
|
| 362 |
-
self.
|
| 363 |
-
|
| 364 |
-
self.
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
)
|
| 369 |
-
|
| 370 |
-
self.
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
def
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
#
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
#
|
| 454 |
-
|
| 455 |
-
#
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
self.
|
| 473 |
-
self.
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
)
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
#
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
)
|
| 549 |
-
|
| 550 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 551 |
return [optimizer], [scheduler]
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import math
|
| 3 |
+
from typing import List, Optional, Tuple, Union
|
| 4 |
+
import time
|
| 5 |
+
import inspect
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
from torch.nn import functional as F
|
| 10 |
+
import torch.utils.checkpoint
|
| 11 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 12 |
+
from torch.utils.data import DataLoader
|
| 13 |
+
|
| 14 |
+
from datasets import load_dataset
|
| 15 |
+
from transformers import GPT2Tokenizer
|
| 16 |
+
|
| 17 |
+
import pytorch_lightning as pl
|
| 18 |
+
from pytorch_lightning.callbacks import LearningRateMonitor, RichProgressBar
|
| 19 |
+
from pytorch_lightning.loggers import WandbLogger
|
| 20 |
+
from lightning.pytorch.callbacks.progress.rich_progress import RichProgressBarTheme
|
| 21 |
+
from pytorch_lightning.callbacks import ModelCheckpoint
|
| 22 |
+
|
| 23 |
+
@dataclass
|
| 24 |
+
class SmolLM2Config:
|
| 25 |
+
hidden_size: int = 576
|
| 26 |
+
intermediate_size: int = 1536
|
| 27 |
+
num_hidden_layers: int = 30
|
| 28 |
+
num_attention_heads: int = 9
|
| 29 |
+
num_key_value_heads: int = 3
|
| 30 |
+
hidden_act: str = "silu"
|
| 31 |
+
max_position_embeddings: int = 2048
|
| 32 |
+
initializer_range: float = 0.041666666666666664
|
| 33 |
+
rms_norm_eps: float = 1.0e-05
|
| 34 |
+
vocab_size: int = 49152
|
| 35 |
+
rope_theta: float = 10000.0
|
| 36 |
+
use_cache: bool = True
|
| 37 |
+
tie_word_embeddings: bool = True
|
| 38 |
+
torch_dtype: str = "float32"
|
| 39 |
+
block_size: int = 512
|
| 40 |
+
|
| 41 |
+
tokenizer: GPT2Tokenizer = GPT2Tokenizer.from_pretrained(
|
| 42 |
+
"HuggingFaceTB/cosmo2-tokenizer"
|
| 43 |
+
)
|
| 44 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 45 |
+
vocab_size = tokenizer.vocab_size
|
| 46 |
+
|
| 47 |
+
class SmolLM2RMSNorm(nn.Module):
|
| 48 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 49 |
+
"""
|
| 50 |
+
SmolLM2RMSNorm is equivalent to T5LayerNorm
|
| 51 |
+
"""
|
| 52 |
+
super().__init__()
|
| 53 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 54 |
+
self.variance_epsilon = eps
|
| 55 |
+
|
| 56 |
+
def forward(self, hidden_states):
|
| 57 |
+
input_dtype = hidden_states.dtype
|
| 58 |
+
variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
|
| 59 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 60 |
+
|
| 61 |
+
return (self.weight * hidden_states).to(input_dtype)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class SmolLM2RotaryEmbedding(torch.nn.Module):
|
| 65 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
| 66 |
+
super().__init__()
|
| 67 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
|
| 68 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 69 |
+
|
| 70 |
+
# Build here to make `torch.jit.trace` work.
|
| 71 |
+
self.max_seq_len_cached = max_position_embeddings
|
| 72 |
+
t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
|
| 73 |
+
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
| 74 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
| 75 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 76 |
+
dtype = torch.get_default_dtype()
|
| 77 |
+
self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
|
| 78 |
+
self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
|
| 79 |
+
|
| 80 |
+
def forward(self, x, seq_len=None):
|
| 81 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
| 82 |
+
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
|
| 83 |
+
if seq_len > self.max_seq_len_cached:
|
| 84 |
+
self.max_seq_len_cached = seq_len
|
| 85 |
+
t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
|
| 86 |
+
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
| 87 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
| 88 |
+
emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
|
| 89 |
+
self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(x.dtype), persistent=False)
|
| 90 |
+
self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(x.dtype), persistent=False)
|
| 91 |
+
return (
|
| 92 |
+
self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
| 93 |
+
self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def rotate_half(x):
|
| 98 |
+
"""Rotates half the hidden dims of the input."""
|
| 99 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 100 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 101 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
|
| 105 |
+
# The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
|
| 106 |
+
cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
|
| 107 |
+
sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
|
| 108 |
+
cos = cos.unsqueeze(0) # [bs, 1, seq_len, dim]
|
| 109 |
+
sin = sin.unsqueeze(0) # [bs, 1, seq_len, dim]
|
| 110 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 111 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 112 |
+
return q_embed, k_embed
|
| 113 |
+
|
| 114 |
+
def _precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0) -> torch.Tensor:
|
| 115 |
+
"""Precompute the frequency tensor for complex exponentials (cos + i*sin)"""
|
| 116 |
+
# Only compute frequencies for half the dimension
|
| 117 |
+
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
|
| 118 |
+
t = torch.arange(end)
|
| 119 |
+
freqs = torch.outer(t, freqs) # [seq_len, dim//2]
|
| 120 |
+
|
| 121 |
+
# Compute cos and sin
|
| 122 |
+
freqs_cos = torch.cos(freqs) # [seq_len, dim//2]
|
| 123 |
+
freqs_sin = torch.sin(freqs) # [seq_len, dim//2]
|
| 124 |
+
|
| 125 |
+
# Stack real and imaginary parts
|
| 126 |
+
freqs_cis = torch.stack([freqs_cos, freqs_sin], dim=-1) # [seq_len, dim//2, 2]
|
| 127 |
+
|
| 128 |
+
return freqs_cis
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class SmolLM2MLP(nn.Module):
|
| 132 |
+
def __init__(
|
| 133 |
+
self,
|
| 134 |
+
hidden_size: int,
|
| 135 |
+
intermediate_size: int,
|
| 136 |
+
hidden_act: str,
|
| 137 |
+
):
|
| 138 |
+
super().__init__()
|
| 139 |
+
self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
| 140 |
+
self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
|
| 141 |
+
self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
| 142 |
+
self.act_fn = nn.SiLU()
|
| 143 |
+
|
| 144 |
+
def forward(self, x):
|
| 145 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 146 |
+
|
| 147 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 148 |
+
"""
|
| 149 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 150 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 151 |
+
"""
|
| 152 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 153 |
+
if n_rep == 1:
|
| 154 |
+
return hidden_states
|
| 155 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 156 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class SmolLM2Attention(nn.Module):
|
| 160 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 161 |
+
|
| 162 |
+
def __init__(self, config: SmolLM2Config):
|
| 163 |
+
super().__init__()
|
| 164 |
+
self.config = config
|
| 165 |
+
self.hidden_size = config.hidden_size
|
| 166 |
+
self.num_heads = config.num_attention_heads
|
| 167 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 168 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 169 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 170 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 171 |
+
|
| 172 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
| 173 |
+
raise ValueError(
|
| 174 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
| 175 |
+
f" and `num_heads`: {self.num_heads})."
|
| 176 |
+
)
|
| 177 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
| 178 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
| 179 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
| 180 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
| 181 |
+
self.rotary_emb = SmolLM2RotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
|
| 182 |
+
|
| 183 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 184 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 185 |
+
|
| 186 |
+
def forward(
|
| 187 |
+
self,
|
| 188 |
+
hidden_states: torch.Tensor,
|
| 189 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 190 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 191 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 192 |
+
output_attentions: bool = False,
|
| 193 |
+
use_cache: bool = False,
|
| 194 |
+
is_sdpa: bool = True,
|
| 195 |
+
is_causal = None
|
| 196 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 197 |
+
bsz, q_len, _ = hidden_states.size()
|
| 198 |
+
|
| 199 |
+
query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 200 |
+
key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 201 |
+
value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 202 |
+
|
| 203 |
+
kv_seq_len = key_states.shape[-2]
|
| 204 |
+
if past_key_value is not None:
|
| 205 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
| 206 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
| 207 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
| 208 |
+
# [bsz, nh, t, hd]
|
| 209 |
+
|
| 210 |
+
if past_key_value is not None:
|
| 211 |
+
# reuse k, v, self_attention
|
| 212 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
| 213 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
| 214 |
+
|
| 215 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
| 216 |
+
|
| 217 |
+
if is_sdpa:
|
| 218 |
+
key = key_states
|
| 219 |
+
value = value_states
|
| 220 |
+
query = query_states
|
| 221 |
+
if self.num_key_value_groups:
|
| 222 |
+
key = repeat_kv(key, self.num_key_value_groups)
|
| 223 |
+
value = repeat_kv(value, self.num_key_value_groups)
|
| 224 |
+
|
| 225 |
+
causal_mask = attention_mask
|
| 226 |
+
if attention_mask is not None:
|
| 227 |
+
causal_mask = causal_mask[:, :, :, : key.shape[-2]]
|
| 228 |
+
|
| 229 |
+
# SDPA with memory-efficient backend is bugged with non-contiguous inputs and custom attn_mask for some torch versions
|
| 230 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
| 231 |
+
query = query.contiguous()
|
| 232 |
+
key = key.contiguous()
|
| 233 |
+
value = value.contiguous()
|
| 234 |
+
|
| 235 |
+
# We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
|
| 236 |
+
# in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
|
| 237 |
+
if is_causal is None:
|
| 238 |
+
is_causal = causal_mask is None and query.shape[2] > 1
|
| 239 |
+
|
| 240 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
| 241 |
+
query,
|
| 242 |
+
key,
|
| 243 |
+
value,
|
| 244 |
+
attn_mask=causal_mask,
|
| 245 |
+
dropout_p=0.0,
|
| 246 |
+
scale=self.head_dim**-0.5,
|
| 247 |
+
is_causal=is_causal,
|
| 248 |
+
)
|
| 249 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 250 |
+
else:
|
| 251 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
| 252 |
+
|
| 253 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
| 254 |
+
raise ValueError(
|
| 255 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
| 256 |
+
f" {attn_weights.size()}"
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
if attention_mask is not None:
|
| 260 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
| 261 |
+
raise ValueError(
|
| 262 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
| 263 |
+
)
|
| 264 |
+
attn_weights = attn_weights + attention_mask
|
| 265 |
+
attn_weights = torch.max(
|
| 266 |
+
attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min, device=attn_weights.device)
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
# upcast attention to fp32
|
| 270 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 271 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 272 |
+
|
| 273 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
| 274 |
+
raise ValueError(
|
| 275 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
| 276 |
+
f" {attn_output.size()}"
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
attn_output = attn_output.transpose(1, 2)
|
| 280 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
| 281 |
+
|
| 282 |
+
attn_output = self.o_proj(attn_output)
|
| 283 |
+
|
| 284 |
+
if not output_attentions:
|
| 285 |
+
attn_weights = None
|
| 286 |
+
|
| 287 |
+
return attn_output, attn_weights, past_key_value
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
class SmolLM2DecoderLayer(nn.Module):
|
| 291 |
+
def __init__(self, config: SmolLM2Config):
|
| 292 |
+
super().__init__()
|
| 293 |
+
self.hidden_size = config.hidden_size
|
| 294 |
+
self.self_attn = SmolLM2Attention(config=config)
|
| 295 |
+
self.mlp = SmolLM2MLP(
|
| 296 |
+
hidden_size=self.hidden_size,
|
| 297 |
+
intermediate_size=config.intermediate_size,
|
| 298 |
+
hidden_act=config.hidden_act,
|
| 299 |
+
)
|
| 300 |
+
self.input_layernorm = SmolLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 301 |
+
self.post_attention_layernorm = SmolLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 302 |
+
|
| 303 |
+
def forward(
|
| 304 |
+
self,
|
| 305 |
+
hidden_states: torch.Tensor,
|
| 306 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 307 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 308 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 309 |
+
output_attentions: Optional[bool] = False,
|
| 310 |
+
use_cache: Optional[bool] = False,
|
| 311 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 312 |
+
"""
|
| 313 |
+
Args:
|
| 314 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 315 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
| 316 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 317 |
+
output_attentions (`bool`, *optional*):
|
| 318 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 319 |
+
returned tensors for more detail.
|
| 320 |
+
use_cache (`bool`, *optional*):
|
| 321 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 322 |
+
(see `past_key_values`).
|
| 323 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
| 324 |
+
"""
|
| 325 |
+
|
| 326 |
+
residual = hidden_states
|
| 327 |
+
|
| 328 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 329 |
+
|
| 330 |
+
# Self Attention
|
| 331 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 332 |
+
hidden_states=hidden_states,
|
| 333 |
+
attention_mask=attention_mask,
|
| 334 |
+
position_ids=position_ids,
|
| 335 |
+
past_key_value=past_key_value,
|
| 336 |
+
output_attentions=output_attentions,
|
| 337 |
+
use_cache=use_cache,
|
| 338 |
+
)
|
| 339 |
+
hidden_states = residual + hidden_states
|
| 340 |
+
|
| 341 |
+
# Fully Connected
|
| 342 |
+
residual = hidden_states
|
| 343 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 344 |
+
hidden_states = self.mlp(hidden_states)
|
| 345 |
+
hidden_states = residual + hidden_states
|
| 346 |
+
|
| 347 |
+
outputs = (hidden_states,)
|
| 348 |
+
|
| 349 |
+
if output_attentions:
|
| 350 |
+
outputs += (self_attn_weights,)
|
| 351 |
+
|
| 352 |
+
if use_cache:
|
| 353 |
+
outputs += (present_key_value,)
|
| 354 |
+
|
| 355 |
+
return outputs
|
| 356 |
+
|
| 357 |
+
class SmolLM2Model(nn.Module):
|
| 358 |
+
def __init__(self, config: SmolLM2Config):
|
| 359 |
+
super().__init__()
|
| 360 |
+
self.config = config
|
| 361 |
+
self.vocab_size = config.vocab_size
|
| 362 |
+
self.head_dim = config.hidden_size // config.num_attention_heads
|
| 363 |
+
|
| 364 |
+
self.dtype = getattr(torch, config.torch_dtype) if hasattr(torch, config.torch_dtype) else torch.float32
|
| 365 |
+
|
| 366 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 367 |
+
self.layers = nn.ModuleList([SmolLM2DecoderLayer(config) for _ in range(config.num_hidden_layers)])
|
| 368 |
+
self.norm = SmolLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 369 |
+
|
| 370 |
+
self.freqs_cis = _precompute_freqs_cis(
|
| 371 |
+
self.head_dim,
|
| 372 |
+
config.max_position_embeddings,
|
| 373 |
+
config.rope_theta,
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
self.apply(self._init_weights)
|
| 377 |
+
|
| 378 |
+
self.to(self.dtype)
|
| 379 |
+
|
| 380 |
+
def _init_weights(self, module):
|
| 381 |
+
if isinstance(module, nn.Linear):
|
| 382 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
|
| 383 |
+
elif isinstance(module, nn.Embedding):
|
| 384 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
|
| 385 |
+
|
| 386 |
+
def forward(
|
| 387 |
+
self,
|
| 388 |
+
input_ids: torch.Tensor,
|
| 389 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 390 |
+
) -> torch.Tensor:
|
| 391 |
+
hidden_states = self.embed_tokens(input_ids)
|
| 392 |
+
|
| 393 |
+
if attention_mask is not None:
|
| 394 |
+
attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
|
| 395 |
+
attention_mask = attention_mask.to(dtype=hidden_states.dtype)
|
| 396 |
+
attention_mask = (1.0 - attention_mask) * torch.finfo(hidden_states.dtype).min
|
| 397 |
+
|
| 398 |
+
freqs_cis = self.freqs_cis.to(device=hidden_states.device, dtype=hidden_states.dtype)
|
| 399 |
+
|
| 400 |
+
for layer in self.layers:
|
| 401 |
+
hidden_states = layer(hidden_states, attention_mask, freqs_cis)[0]
|
| 402 |
+
|
| 403 |
+
hidden_states = self.norm(hidden_states)
|
| 404 |
+
return hidden_states
|
| 405 |
+
|
| 406 |
+
class SmolLM2ForCausalLM(nn.Module):
|
| 407 |
+
def __init__(self, config: SmolLM2Config):
|
| 408 |
+
super().__init__()
|
| 409 |
+
self.config = config
|
| 410 |
+
self.model = SmolLM2Model(config)
|
| 411 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 412 |
+
|
| 413 |
+
# Tie weights if configured
|
| 414 |
+
if config.tie_word_embeddings:
|
| 415 |
+
self.lm_head.weight = self.model.embed_tokens.weight
|
| 416 |
+
|
| 417 |
+
def forward(
|
| 418 |
+
self,
|
| 419 |
+
input_ids: torch.Tensor,
|
| 420 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 421 |
+
labels: Optional[torch.Tensor] = None,
|
| 422 |
+
) -> torch.Tensor:
|
| 423 |
+
hidden_states = self.model(input_ids, attention_mask)
|
| 424 |
+
logits = self.lm_head(hidden_states)
|
| 425 |
+
|
| 426 |
+
loss = None
|
| 427 |
+
if labels is not None:
|
| 428 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 429 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 430 |
+
loss = F.cross_entropy(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
|
| 431 |
+
|
| 432 |
+
return logits, loss
|
| 433 |
+
|
| 434 |
+
@torch.no_grad()
|
| 435 |
+
def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
|
| 436 |
+
"""
|
| 437 |
+
Generate text given a starting sequence of tokens.
|
| 438 |
+
Args:
|
| 439 |
+
idx (torch.Tensor): Starting token indices, shape (B, T)
|
| 440 |
+
max_new_tokens (int): Number of tokens to generate
|
| 441 |
+
temperature (float): Sampling temperature (1.0 = no change, < 1.0 = less random, > 1.0 = more random)
|
| 442 |
+
top_k (int): If specified, only sample from the top k most probable tokens
|
| 443 |
+
"""
|
| 444 |
+
for _ in range(max_new_tokens):
|
| 445 |
+
# if the sequence context is growing too long we must crop it at block_size
|
| 446 |
+
idx_cond = (
|
| 447 |
+
idx
|
| 448 |
+
if idx.size(1) <= self.config.block_size
|
| 449 |
+
else idx[:, -self.config.block_size :]
|
| 450 |
+
)
|
| 451 |
+
# forward the model to get the logits for the index in the sequence
|
| 452 |
+
logits, _ = self(idx_cond)
|
| 453 |
+
# pluck the logits at the final step and scale by desired temperature
|
| 454 |
+
logits = logits[:, -1, :] / temperature
|
| 455 |
+
# optionally crop the logits to only the top k options
|
| 456 |
+
if top_k is not None:
|
| 457 |
+
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
|
| 458 |
+
logits[logits < v[:, [-1]]] = -float("Inf")
|
| 459 |
+
# apply softmax to convert logits to (normalized) probabilities
|
| 460 |
+
probs = F.softmax(logits, dim=-1)
|
| 461 |
+
# sample from the distribution
|
| 462 |
+
idx_next = torch.multinomial(probs, num_samples=1)
|
| 463 |
+
# append sampled index to the running sequence
|
| 464 |
+
idx = torch.cat((idx, idx_next), dim=1)
|
| 465 |
+
|
| 466 |
+
return idx
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
class plSmolLM2(pl.LightningModule):
|
| 470 |
+
def __init__(self, config: SmolLM2Config, lr, warmup_steps, max_steps, step=None):
|
| 471 |
+
super().__init__()
|
| 472 |
+
self.save_hyperparameters()
|
| 473 |
+
self.config = config
|
| 474 |
+
self.model = SmolLM2ForCausalLM(self.config)
|
| 475 |
+
self.criterion = nn.CrossEntropyLoss()
|
| 476 |
+
self.tokenizer = tokenizer
|
| 477 |
+
self.generation_prompt = "Hello there! Today, we are going to talk about "
|
| 478 |
+
self._generating = False
|
| 479 |
+
self.start_step = step if step is not None else 0
|
| 480 |
+
|
| 481 |
+
def forward(self, x):
|
| 482 |
+
return self.model(x)
|
| 483 |
+
|
| 484 |
+
def training_step(self, batch, batch_idx):
|
| 485 |
+
input_ids = batch["input_ids"]
|
| 486 |
+
target_ids = batch["labels"]
|
| 487 |
+
logits, _ = self(input_ids)
|
| 488 |
+
loss = self.criterion(logits.view(-1, logits.size(-1)), target_ids.view(-1))
|
| 489 |
+
|
| 490 |
+
# Log the loss with 4 decimal precision
|
| 491 |
+
self.log(
|
| 492 |
+
"train_loss", loss, prog_bar=True, on_step=True, on_epoch=False, logger=True
|
| 493 |
+
)
|
| 494 |
+
print(f"Step: {self.start_step+self.global_step}, Train Loss: {loss}")
|
| 495 |
+
|
| 496 |
+
# Generate text every n steps, but only if we're not already generating
|
| 497 |
+
if (self.global_step) % log_every_n_steps == 0 and not self._generating:
|
| 498 |
+
self._generating = True
|
| 499 |
+
self.generate_and_log_sample()
|
| 500 |
+
self._generating = False
|
| 501 |
+
#self.step = self.step + 1
|
| 502 |
+
|
| 503 |
+
return loss
|
| 504 |
+
|
| 505 |
+
def generate_and_log_sample(self):
|
| 506 |
+
"""Generate and log a sample of text from the model"""
|
| 507 |
+
try:
|
| 508 |
+
# Encode the prompt
|
| 509 |
+
prompt_ids = self.tokenizer.encode(
|
| 510 |
+
self.generation_prompt, return_tensors="pt"
|
| 511 |
+
).to(self.device)
|
| 512 |
+
|
| 513 |
+
# Generate new tokens
|
| 514 |
+
generated_ids = self.model.generate(
|
| 515 |
+
prompt_ids, max_new_tokens=50, temperature=0.8, top_k=40
|
| 516 |
+
)
|
| 517 |
+
|
| 518 |
+
# Decode the generated tokens
|
| 519 |
+
generated_text = self.tokenizer.decode(generated_ids[0].tolist())
|
| 520 |
+
|
| 521 |
+
# Create a formatted message
|
| 522 |
+
message = (
|
| 523 |
+
f"\n{'='*40}\n"
|
| 524 |
+
f"Step {self.global_step} generation:\n"
|
| 525 |
+
f"Prompt: {self.generation_prompt}\n"
|
| 526 |
+
f"Generated: {generated_text}\n"
|
| 527 |
+
f"{'='*40}\n"
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
print(message)
|
| 531 |
+
|
| 532 |
+
# Log to WandB
|
| 533 |
+
if hasattr(self.logger, "experiment"):
|
| 534 |
+
self.logger.experiment.log(
|
| 535 |
+
{"generated_text": generated_text, "global_step": self.global_step}
|
| 536 |
+
)
|
| 537 |
+
except Exception as e:
|
| 538 |
+
print(f"Generation failed with error: {str(e)}")
|
| 539 |
+
|
| 540 |
+
def configure_optimizers(self):
|
| 541 |
+
optimizer = torch.optim.AdamW(self.parameters(), lr=self.hparams.lr)
|
| 542 |
+
|
| 543 |
+
def lr_lambda(current_step):
|
| 544 |
+
if current_step < self.hparams.warmup_steps:
|
| 545 |
+
return self.hparams.lr * (current_step + 1) / self.hparams.warmup_steps
|
| 546 |
+
elif current_step > self.hparams.max_steps:
|
| 547 |
+
return self.hparams.lr * 0.1
|
| 548 |
+
decay_ratio = (current_step - self.hparams.warmup_steps) / (
|
| 549 |
+
self.hparams.max_steps - self.hparams.warmup_steps
|
| 550 |
+
)
|
| 551 |
+
coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio))
|
| 552 |
+
return self.hparams.lr * 0.1 + coeff * (
|
| 553 |
+
self.hparams.lr - self.hparams.lr * 0.1
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
|
| 557 |
return [optimizer], [scheduler]
|