Upload checkpoint (step 2000)
Browse filesFiles changed (7)
- README.md+94
- ckpt_last.ptAdded+3
- config.jsonAdded+15
- generate.pyAdded+132
- model.pyAdded+271
- optim.pyAdded+69
- training_state.jsonAdded+5
123---license: apache-2.0---12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697---license: apache-2.0library_name: pytorchpipeline_tag: text-generationtags:- code- reasoning- gated-linear-attention- hybrid-attention- long-context- from-scratchlanguage:- en---# FLATest — Hybrid GLA + Attention code/reasoning LMA **308M-parameter** decoder-only language model trained **from scratch** on a singleRTX PRO 6000 (Blackwell). It mixes **Gated Linear Attention (GLA)** layers with sparsefull-attention layers — a hybrid sequence mixer in the spirit of Jamba / MiniMax —to get **O(N) long-context** behaviour while keeping the **exact associative recall**that pure linear attention loses.This is an **educational / research** model: trained on a single GPU for a limitedtoken budget. It is **not** a SOTA code assistant. Its purpose is to demonstrate acorrect, scalable architecture for long-context + reasoning, and the GrokAdamWoptimizer recipe.## Architecture| | ||---|---|| Params | ~308M || `d_model` | 1024 || Layers | 24 || Heads | 16 (GQA, 4 KV-heads) || Mixer | **hybrid** — GLA on most layers, attention every 4th layer (`gggAgggAgggAgggAgggAgggA`) || Train context | 4096 || Vocab | 49152 (StarCoder2 BPE) || Position | RoPE on attention layers; GLA uses learned decay (no RoPE) || Norm / MLP | RMSNorm + SwiGLU || Embeddings | tied input/output |**Why hybrid:** pure GLA fails exact associative recall (recall ≈ chance on aninduction probe), while a few interleaved attention layers restore it (recall ≈ 1.0).The GLA layers keep the model linear in context length, so the real payoff is**long-form generation**: in our decode benchmark GLA's recurrent state is **~8.7×faster and ~20× lighter** than an attention KV-cache at 64k output tokens.## Training- **Optimizer:** GrokAdamW — decoupled weight decay (0.1), betas (0.9, 0.95),cautious update, optional Grokfast EMA. The weight-decay-driven recipe was verifiedto reproduce **grokking** on modular addition (val acc 0 → 1.0).- **Data:** infinite mixed stream — code documents (`bigcode/starcoderdata`) +reasoning traces (`open-r1/OpenR1-Math-220k`, ratio 0.3). Reasoning examples are**prompt-masked** (loss only on `<think>…</think>` + answer).- **Schedule:** warmup + cosine, bf16 autocast, grad clip 1.0, effective batch 64(262k tokens/step), `torch.compile`.- **Throughput:** ~81k tok/s, ~58 GB peak on the PRO 6000.- **Reasoning format:** special tokens `<think>` / `</think>`; the model learns toreason in text before answering.Validation perplexity dropped steadily (ppl 33 → ~4 within a few thousand steps).See `config.json` and `training_state.json` for the exact step the uploadedcheckpoint corresponds to.## Files- `ckpt_last.pt` — checkpoint: `{model, opt, step, cfg}` (PyTorch).- `config.json` — the `ModelConfig` used to build the model.- `model.py`, `optim.py` — model + optimizer definitions (the `codetrain` package).- `generate.py` — inference / sampling script.## Inference```bashpip install torch transformers flash-linear-attentionpython generate.py --ckpt ckpt_last.pt --prompt "Write a Python function that reverses a linked list."````generate.py` seeds a `<think>` block to elicit reasoning, then samples the answer.Requires `flash-linear-attention` (Triton) for the GLA layers.## Limitations- Single-GPU, limited token budget → expect incoherent or repetitive output on hardprompts. It is a scaffold, not a product.- GLA layers require `flash-linear-attention` + a Triton-capable GPU.- `generate.py` uses full-recompute decoding (simple, correct for both layer types);the O(1) recurrent GLA decode that gives the long-context speedup is not yet wiredinto the sampler.## Citation / lineageBuilds on: Gated Linear Attention (Yang et al. 2023), Grokfast (Lee et al. 2024),grokking (Power et al. 2022), hybrid linear/attention stacks (Jamba, MiniMax).
123version https://git-lfs.github.com/spec/v1oid sha256:c97c327a41304598853f89ac14bd57b51900d09a02d01ca27f610fbccadb56fcsize 2152241611123456789101112131415{ "vocab_size": 49154, "d_model": 1024, "n_layers": 24, "n_heads": 16, "n_kv_heads": 4, "block_size": 4096, "mlp_ratio": 2.6666666666666665, "rope_theta": 100000.0, "dropout": 0.0, "grad_checkpoint": false, "mixer": "hybrid", "attn_every": 4, "gla_chunk": 64}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132"""generate.py — запуск обученной reasoning-модели по чекпойнту.
Даёшь задачу по коду/математике -> модель рассуждает в <think>...</think> ивыдаёт ответ. Декодинг: полный пересчёт растущей последовательности (просто икорректно для hybrid: и GLA-, и attn-слои работают через обычный forward).
Запуск: python generate.py --ckpt out_reason/ckpt_last.pt --prompt "Напиши функцию..." python generate.py --ckpt out_reason/ckpt_last.pt # интерактивно python generate.py --ckpt out_reason/ckpt_last.pt --no_think # без затравки <think>"""
import argparse, osimport torchimport torch.nn.functional as F
from codetrain.model import CodeLM, ModelConfig
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"THINK, ENDTHINK = "<think>", "</think>"
def load_model(ckpt_path): ck = torch.load(ckpt_path, map_location=DEVICE) cfg = ModelConfig(**ck["cfg"]) cfg.grad_checkpoint = False # инференс: без чекпойнтинга model = CodeLM(cfg).to(DEVICE).to(torch.bfloat16) model.load_state_dict(ck["model"]) model.eval() step = ck.get("step", "?") print(f"Загружен чекпойнт: шаг {step} | {model.num_params()/1e6:.0f}M " f"| ctx {cfg.block_size} | mixer {cfg.mixer}") return model, cfg
def build_tokenizer(name="bigcode/starcoder2-15b"): from transformers import AutoTokenizer tok = AutoTokenizer.from_pretrained(name) if tok.eos_token_id is None: tok.add_special_tokens({"eos_token": "<|endoftext|>"}) add = [t for t in (THINK, ENDTHINK) if t not in tok.get_vocab()] if add: tok.add_special_tokens({"additional_special_tokens": add}) return tok
def _sample(logits, temperature, top_p): """Один токен из распределения. temperature=0 -> жадно (argmax).""" if temperature <= 0: return int(logits.argmax(-1)) logits = logits / temperature probs = F.softmax(logits, dim=-1) if 0 < top_p < 1: # nucleus: оставляем ядро массы top_p sp, si = torch.sort(probs, descending=True) csum = torch.cumsum(sp, dim=-1) keep = csum - sp <= top_p # держим, пока кумулятив не превысил sp = sp * keep sp = sp / sp.sum() nxt = si[torch.multinomial(sp, 1)] return int(nxt) return int(torch.multinomial(probs, 1))
@torch.no_grad()def generate(model, cfg, tok, prompt, max_new=512, temperature=0.7, top_p=0.95, seed_think=True, stream=True): """Сгенерировать продолжение. seed_think=True добавляет '<think>\\n' к затравке, подталкивая модель сначала рассуждать. Останов по EOS. Печатает по токенам.""" text = prompt.rstrip() + "\n" if seed_think: text += THINK + "\n" ids = tok.encode(text) if stream: print("\n--- генерация ---") print(text, end="", flush=True) ids = torch.tensor([ids], device=DEVICE) eos = tok.eos_token_id out_ids = [] for _ in range(max_new): ctx = ids[:, -cfg.block_size:] # не выходим за обученный контекст logits, _ = model(ctx) # (1, 1, vocab) — последний шаг nxt = _sample(logits[0, -1], temperature, top_p) if nxt == eos: break out_ids.append(nxt) ids = torch.cat([ids, torch.tensor([[nxt]], device=DEVICE)], dim=1) if stream: print(tok.decode([nxt]), end="", flush=True) if stream: print("\n--- конец ---") return tok.decode(out_ids)
def main(): ap = argparse.ArgumentParser() ap.add_argument("--ckpt", required=True) ap.add_argument("--tokenizer", default="bigcode/starcoder2-15b") ap.add_argument("--prompt", default=None, help="одноразовый запрос (иначе интерактив)") ap.add_argument("--max_new", type=int, default=512) ap.add_argument("--temperature", type=float, default=0.7) ap.add_argument("--top_p", type=float, default=0.95) ap.add_argument("--no_think", action="store_true", help="не добавлять <think> в затравку (модель сама решит)") args = ap.parse_args()
if not os.path.exists(args.ckpt): print(f"Чекпойнт не найден: {args.ckpt}"); return tok = build_tokenizer(args.tokenizer) model, cfg = load_model(args.ckpt)
def run(p): generate(model, cfg, tok, p, max_new=args.max_new, temperature=args.temperature, top_p=args.top_p, seed_think=not args.no_think, stream=True)
if args.prompt is not None: run(args.prompt) else: print("Интерактив. Пустая строка / Ctrl-C — выход.") while True: try: p = input("\n>>> запрос: ").strip() except (EOFError, KeyboardInterrupt): print(); break if not p: break run(p)
if __name__ == "__main__": main()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271"""Современный decoder-only трансформер для обучения кодинг-модели с нуля.
Компоненты (всё — проверенная практика для код-моделей): - RoPE (rotary position embeddings): позволяет расширять контекст за пределы обученной длины; нет обучаемых позиционных эмбеддингов. - RMSNorm: дешевле и стабильнее LayerNorm. - SwiGLU MLP: лучше GELU при том же бюджете параметров. - Flash attention через F.scaled_dot_product_attention: память O(N) на практике, causal-маска бесплатно. - Gradient checkpointing (опц.): торгуем счёт за память -> длинный контекст на одной карте. - Tied embeddings (вход = выход): экономит параметры, обычно не вредит.
Конфиг масштабируется от ~120M до ~1B; дефолт ~0.35B комфортно влезает в 96GBс длинным контекстом и grad checkpointing."""
from dataclasses import dataclassimport mathimport torchimport torch.nn as nnimport torch.nn.functional as F
@dataclassclass ModelConfig: vocab_size: int = 49152 # StarCoder2 BPE d_model: int = 1024 n_layers: int = 24 n_heads: int = 16 n_kv_heads: int = 4 # GQA: меньше KV-голов -> дешевле память/кэш block_size: int = 4096 # тренируемый контекст mlp_ratio: float = 8 / 3 # SwiGLU -> hidden ~ 8/3 * d_model, кратно 256 rope_theta: float = 100_000.0 # большая база -> легче расширять контекст dropout: float = 0.0 grad_checkpoint: bool = True # выбор смесителя последовательности: # "attn" — обычное внимание во всех слоях (O(N^2), точный recall); # "gla" — линейное внимание fla во всех слоях (O(N), но без точного recall); # "hybrid" — GLA везде + attention каждый attn_every-й слой (O(N) + recall). mixer: str = "attn" attn_every: int = 4 # для hybrid: каждый attn_every-й слой = attention gla_chunk: int = 64 # размер чанка для fla chunk_gla
@property def head_dim(self): return self.d_model // self.n_heads
class RMSNorm(nn.Module): def __init__(self, dim, eps=1e-5): super().__init__() self.eps = eps self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x): dt = x.dtype x = x.float() x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) return (x * self.weight.float()).to(dt)
def build_rope_cache(seq_len, head_dim, theta, device, dtype): inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim)) t = torch.arange(seq_len, device=device).float() freqs = torch.outer(t, inv_freq) # (T, head_dim/2) cos = freqs.cos().to(dtype) sin = freqs.sin().to(dtype) return cos, sin
def apply_rope(x, cos, sin): # x: (B, H, T, D). Поворачиваем пары (x1, x2). T = x.shape[-2] cos, sin = cos[:T], sin[:T] x1, x2 = x[..., 0::2], x[..., 1::2] cos = cos[None, None]; sin = sin[None, None] rx1 = x1 * cos - x2 * sin rx2 = x1 * sin + x2 * cos out = torch.empty_like(x) out[..., 0::2] = rx1 out[..., 1::2] = rx2 return out
class Attention(nn.Module): """Causal multi-head attention с GQA и RoPE, flash через SDPA."""
def __init__(self, cfg: ModelConfig): super().__init__() self.n_heads = cfg.n_heads self.n_kv = cfg.n_kv_heads self.hd = cfg.head_dim assert cfg.n_heads % cfg.n_kv_heads == 0, "n_heads должно делиться на n_kv_heads" self.q_proj = nn.Linear(cfg.d_model, cfg.n_heads * self.hd, bias=False) self.k_proj = nn.Linear(cfg.d_model, self.n_kv * self.hd, bias=False) self.v_proj = nn.Linear(cfg.d_model, self.n_kv * self.hd, bias=False) self.o_proj = nn.Linear(cfg.n_heads * self.hd, cfg.d_model, bias=False) self.dropout = cfg.dropout
def forward(self, x, cos, sin): B, T, _ = x.shape q = self.q_proj(x).view(B, T, self.n_heads, self.hd).transpose(1, 2) k = self.k_proj(x).view(B, T, self.n_kv, self.hd).transpose(1, 2) v = self.v_proj(x).view(B, T, self.n_kv, self.hd).transpose(1, 2) q = apply_rope(q, cos, sin) k = apply_rope(k, cos, sin) if self.n_kv != self.n_heads: # GQA: расширяем KV-головы rep = self.n_heads // self.n_kv k = k.repeat_interleave(rep, dim=1) v = v.repeat_interleave(rep, dim=1) y = F.scaled_dot_product_attention( q, k, v, is_causal=True, dropout_p=self.dropout if self.training else 0.0) y = y.transpose(1, 2).contiguous().view(B, T, -1) return self.o_proj(y)
# fla (flash-linear-attention): рабочее fused Triton-ядро GLA (fwd+bwd).# Проверено на RTX PRO 6000: 4x быстрее flash-attn на 32k, обучается (recall грокнул).# Импорт защищён: если fla нет (нет triton/Blackwell), GLAMixer недоступен и train# должен откатиться на attention (см. _make_mixer).try: from fla.ops.gla import chunk_gla as _fla_chunk_gla _HAS_FLA = Trueexcept Exception: _fla_chunk_gla = None _HAS_FLA = False
class GLAMixer(nn.Module): """Gated Linear Attention через fla. O(N) по контексту, без RoPE (затухание само кодирует позицию). Обучаемый ВЕКТОРНЫЙ гейт затухания g = logsigmoid(W_g x) — каноническая форма GLA (мощнее скалярного gamma). Раскладка для fla 0.5.0: (B, T, H, K), без kwargs (откалибровано отдельно). GQA: KV-головы расширяются до n_heads (fla ждёт одинаковое число голов)."""
def __init__(self, cfg: ModelConfig): super().__init__() assert _HAS_FLA, "GLAMixer требует flash-linear-attention (pip install)" self.n_heads = cfg.n_heads self.n_kv = cfg.n_kv_heads self.hd = cfg.head_dim self.chunk = cfg.gla_chunk self.q_proj = nn.Linear(cfg.d_model, cfg.n_heads * self.hd, bias=False) self.k_proj = nn.Linear(cfg.d_model, self.n_kv * self.hd, bias=False) self.v_proj = nn.Linear(cfg.d_model, self.n_kv * self.hd, bias=False) # гейт затухания на каждый канал q-голов (в лог-пространстве через logsigmoid) self.g_proj = nn.Linear(cfg.d_model, cfg.n_heads * self.hd, bias=False) self.o_proj = nn.Linear(cfg.n_heads * self.hd, cfg.d_model, bias=False) # выходной гейт (как в GLA): сигмоида, стабилизирует амплитуду self.out_gate = nn.Linear(cfg.d_model, cfg.n_heads * self.hd, bias=False)
def forward(self, x, cos=None, sin=None): # cos/sin игнорируем: GLA без RoPE B, T, _ = x.shape H, KV, Dh = self.n_heads, self.n_kv, self.hd # fla ждёт раскладку (B, T, H, Dh) q = self.q_proj(x).view(B, T, H, Dh) k = self.k_proj(x).view(B, T, KV, Dh) v = self.v_proj(x).view(B, T, KV, Dh) if KV != H: # GQA -> расширяем KV до H голов rep = H // KV k = k.repeat_interleave(rep, dim=2) v = v.repeat_interleave(rep, dim=2) q = F.normalize(q, dim=-1) k = F.normalize(k, dim=-1) # лог-гейт затухания в (-inf, 0): logsigmoid -> устойчиво, gamma=exp(g) in (0,1) g = F.logsigmoid(self.g_proj(x).view(B, T, H, Dh).float()) # ЕДИНЫЙ dtype для fla: под autocast F.normalize даёт fp32, а v_proj — bf16; # fla-ядро падает на смешении типов в tl.dot. Приводим всё к dtype входа. dt = x.dtype q, k, v, g = q.to(dt), k.to(dt), v.to(dt), g.to(dt) out = _fla_chunk_gla(q, k, v, g) # (B, T, H, Dh), layout bthd o = out[0] if isinstance(out, (tuple, list)) else out o = o.reshape(B, T, H * Dh) * torch.sigmoid(self.out_gate(x)) return self.o_proj(o)
class SwiGLU(nn.Module): def __init__(self, cfg: ModelConfig): super().__init__() hidden = int(cfg.mlp_ratio * cfg.d_model) hidden = 256 * ((hidden + 255) // 256) # кратно 256 для тензорных ядер self.gate = nn.Linear(cfg.d_model, hidden, bias=False) self.up = nn.Linear(cfg.d_model, hidden, bias=False) self.down = nn.Linear(hidden, cfg.d_model, bias=False)
def forward(self, x): return self.down(F.silu(self.gate(x)) * self.up(x))
def _layer_is_attn(cfg: ModelConfig, layer_idx: int) -> bool: """Какой смеситель в слое layer_idx. hybrid: attention каждый attn_every-й слой (на индексах attn_every-1, 2*attn_every-1, ...), остальное — GLA.""" if cfg.mixer == "attn": return True if cfg.mixer == "gla": return False # hybrid return (layer_idx + 1) % cfg.attn_every == 0
class Block(nn.Module): def __init__(self, cfg: ModelConfig, layer_idx: int = 0): super().__init__() self.is_attn = _layer_is_attn(cfg, layer_idx) self.attn_norm = RMSNorm(cfg.d_model) self.mixer = Attention(cfg) if self.is_attn else GLAMixer(cfg) self.mlp_norm = RMSNorm(cfg.d_model) self.mlp = SwiGLU(cfg)
def forward(self, x, cos, sin): # GLA-слой игнорирует cos/sin (нет RoPE); attention использует. x = x + self.mixer(self.attn_norm(x), cos, sin) x = x + self.mlp(self.mlp_norm(x)) return x
class CodeLM(nn.Module): def __init__(self, cfg: ModelConfig): super().__init__() self.cfg = cfg self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.d_model) self.drop = nn.Dropout(cfg.dropout) self.blocks = nn.ModuleList([Block(cfg, i) for i in range(cfg.n_layers)]) self.norm_f = RMSNorm(cfg.d_model) self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False) self.lm_head.weight = self.tok_emb.weight # tied self._rope = None self.apply(self._init) # масштабирование инициализации остаточных проекций по глубине (GPT-2 трюк) for n, p in self.named_parameters(): if n.endswith("o_proj.weight") or n.endswith("down.weight"): nn.init.normal_(p, std=0.02 / math.sqrt(2 * cfg.n_layers))
def _init(self, m): if isinstance(m, nn.Linear): nn.init.normal_(m.weight, std=0.02) elif isinstance(m, nn.Embedding): nn.init.normal_(m.weight, std=0.02)
def _rope_cache(self, T, device, dtype): if self._rope is None or self._rope[0].shape[0] < T or self._rope[0].device != device: self._rope = build_rope_cache(max(T, self.cfg.block_size), self.cfg.head_dim, self.cfg.rope_theta, device, dtype) return self._rope
def forward(self, idx, targets=None): B, T = idx.shape x = self.drop(self.tok_emb(idx)) cos, sin = self._rope_cache(T, idx.device, x.dtype) for blk in self.blocks: if self.cfg.grad_checkpoint and self.training: x = torch.utils.checkpoint.checkpoint(blk, x, cos, sin, use_reentrant=False) else: x = blk(x, cos, sin) x = self.norm_f(x) if targets is None: # инференс: только последний шаг logits = self.lm_head(x[:, -1:]) return logits, None logits = self.lm_head(x) loss = F.cross_entropy(logits.reshape(-1, logits.size(-1)), targets.reshape(-1), ignore_index=-100) return logits, loss
def num_params(self, non_embed=True): n = sum(p.numel() for p in self.parameters()) if non_embed: n -= self.tok_emb.weight.numel() # tied -> один раз return n123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869"""GrokAdamW: AdamW c уклоном в обобщение.
- decoupled weight decay (только на матрицах, не на нормах/эмбеддингах); - cautious-маскинг (C-AdamW): применяем компоненты шага, согласованные по знаку с градиентом -> стабильнее и чуть быстрее сходимость; - Grokfast (опц., gf_lambda>0): усиление медленной компоненты градиента. Для большого претрейна обычно держим gf_lambda=0 (нужен для grokking на маленьких алгоритмических задачах, не для масштабного обучения)."""
import mathimport torch
class GrokAdamW(torch.optim.Optimizer): def __init__(self, params, lr=3e-4, betas=(0.9, 0.95), eps=1e-8, weight_decay=0.1, grokfast_lambda=0.0, grokfast_alpha=0.98, cautious=True): defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, grokfast_lambda=grokfast_lambda, grokfast_alpha=grokfast_alpha, cautious=cautious) super().__init__(params, defaults)
@torch.no_grad() def step(self, closure=None): loss = closure() if closure is not None else None for grp in self.param_groups: lr, (b1, b2), eps = grp["lr"], grp["betas"], grp["eps"] wd, gfl, gfa, caut = (grp["weight_decay"], grp["grokfast_lambda"], grp["grokfast_alpha"], grp["cautious"]) for p in grp["params"]: if p.grad is None: continue g = p.grad st = self.state[p] if not st: st["step"] = 0 st["m"] = torch.zeros_like(p) st["v"] = torch.zeros_like(p) if gfl > 0: st["ema"] = g.clone() if gfl > 0: ema = st["ema"]; ema.mul_(gfa).add_(g, alpha=1 - gfa) g = g.add(ema, alpha=gfl) m, v = st["m"], st["v"] st["step"] += 1; t = st["step"] m.mul_(b1).add_(g, alpha=1 - b1) v.mul_(b2).addcmul_(g, g, value=1 - b2) denom = (v.sqrt() / math.sqrt(1 - b2 ** t)).add_(eps) step_size = lr / (1 - b1 ** t) if wd != 0: p.mul_(1 - lr * wd) upd = m / denom if caut: mask = (upd * g > 0).to(upd.dtype) mask.mul_(mask.numel() / (mask.sum() + 1)) upd.mul_(mask) p.add_(upd, alpha=-step_size) return loss
def param_groups(model, weight_decay): decay, no_decay = [], [] for name, p in model.named_parameters(): if not p.requires_grad: continue (no_decay if p.ndim < 2 or name.endswith(".bias") else decay).append(p) return [{"params": decay, "weight_decay": weight_decay}, {"params": no_decay, "weight_decay": 0.0}]12345{ "step": 2000, "param_count": 408998912, "checkpoint": "ckpt_last.pt"}README.md+94
ckpt_last.ptAdded+3
config.jsonAdded+15
generate.pyAdded+132
model.pyAdded+271
optim.pyAdded+69
training_state.jsonAdded+5