"""Central config for the Armenian LLM TPU project. Everything tunable lives here so train_tpu.py / prepare_data.py / launch.py stay in sync. Values are chosen for a SINGLE TPU v5e/v6e chip (16GB HBM) training from scratch. """ from __future__ import annotations from dataclasses import dataclass, asdict, field import json import os def _default_compute_dtype() -> str: """Compute dtype, chosen by backend at import time. TPU (v5e/v6e, Colab supervisor path) uses bfloat16 — that's the proven, still-running config; leave it untouched. GPU (Kaggle T4x2) has NO bf16 tensor cores (Turing sm_75), so bf16 there de-optimizes to fp32-upcast paths. The Kaggle launcher sets COMPUTE_DTYPE=float16 to use T4's native fp16 tensor cores instead. Env override keeps this file backend-safe: the SAME config.py is pulled from HF CODE_REPO by BOTH the TPU supervisor and the Kaggle kernel, so the split must be by env, never a hardcoded change. """ dt = os.environ.get("COMPUTE_DTYPE", "bfloat16").strip().lower() if dt not in ("bfloat16", "float16", "float32"): raise ValueError(f"COMPUTE_DTYPE must be bfloat16|float16|float32, got {dt!r}") return dt def _default_micro_batch() -> int: """Per-device micro-batch, chosen by backend at import time. TPU v5e1 (16GB HBM, single device, no pmap) fits micro=8 -> 8*ga(4) = 32 seq/step. Kaggle T4x2 runs DATA-PARALLEL (pmap) across 2 GPUs, so the same micro=8 would be 8*ga(4)*2 = 64 seq/step AND each T4 tried to allocate an ~8.85GB fp16 buffer -> RESOURCE_EXHAUSTED OOM (T4 has 16GB but XLA-GPU overhead + NCCL clique + fp16 activations eat the headroom). Setting MICRO_BATCH=4 on GPU halves the per-device activation footprint AND makes 4*ga(4)*2dev = 32 seq/step = EXACTLY the TPU baseline, so the LR schedule and the resumed checkpoint stay in sync (identical effective batch/math). Env override keeps config.py backend-safe (same file pulled by both paths). """ mb = os.environ.get("MICRO_BATCH", "8").strip() try: v = int(mb) except ValueError: raise ValueError(f"MICRO_BATCH must be a positive int, got {mb!r}") if v < 1: raise ValueError(f"MICRO_BATCH must be >= 1, got {v}") return v # ------------------------------------------------------------------ # Hugging Face repositories (durable storage across dead sessions) # ------------------------------------------------------------------ # Verified via HfApi.whoami() against the live HF_TOKEN (write scope). HF_USER = "ArthurYeghinyan" # Where the pretokenized corpus goes (dataset repo) and where code is pulled from. DATA_REPO = f"{HF_USER}/armenian-llm-data" # repo_type="dataset" CODE_REPO = f"{HF_USER}/armenian-llm-code" # repo_type="dataset" (holds train_tpu.py, model.py, config.py) # Checkpoint repo. Env-overridable so a run can be ISOLATED in its own repo — e.g. # a fresh from-scratch run must not share a repo with a still-live older kernel, # whose save() deletes older ckpts and whose high step numbers would hijack resume. CKPT_REPO = os.environ.get( "CKPT_REPO", f"{HF_USER}/armenian-llm-124m") # repo_type="model" (checkpoints + final) # ------------------------------------------------------------------ # Source dataset (phase 1: Wikipedia -> later swap to CulturaX) # ------------------------------------------------------------------ # Phase 1 default: cleaned Armenian Wikipedia. SOURCE_DATASET = "HuggingFaceFW/finewiki" SOURCE_CONFIG = "hy" SOURCE_SPLIT = "train" # For phase 2 scale-up, switch to: # SOURCE_DATASET = "uonlp/CulturaX"; SOURCE_CONFIG = "hy"; streaming=True @dataclass(frozen=True) class TokenizerConfig: vocab_size: int = 32000 model_type: str = "unigram" # SentencePiece unigram = strong for morphologically rich Armenian character_coverage: float = 0.9998 # Cap how much text is used to TRAIN the tokenizer (not the LM). train_sample_rows: int = 400_000 max_chars_per_row: int = 20_000 @dataclass(frozen=True) class ModelConfig: # ~124M params (GPT-2 small scale, modern Llama-style internals). vocab_size: int = 32000 n_layer: int = 12 n_head: int = 12 n_kv_head: int = 12 # == n_head -> plain MHA; set < n_head for GQA n_embd: int = 768 seq_len: int = 1024 ffn_mult: float = 8 / 3 # SwiGLU: hidden = round to multiple of 256 rope_theta: float = 10000.0 rms_eps: float = 1e-5 dtype: str = field(default_factory=_default_compute_dtype) # bf16 on TPU, fp16 on GPU (see fn) tie_embeddings: bool = True def ffn_hidden(self) -> int: h = int(self.n_embd * self.ffn_mult) return ((h + 255) // 256) * 256 @dataclass(frozen=True) class TrainConfig: # Global batch = micro_batch * grad_accum. Two separate OOMs were fixed here: # 1) HOST RAM at compile: the un-rematted jax.lax.scan grad-accum graph needed # ~46GB and got cgroup-OOM-killed under JAX 0.10.2 (a silent SIGKILL, no # traceback). Fixed by dropping scan for a python loop over a small jitted # micro_grad (train_tpu.py) — matches the working Whisper-TPU reference. # 2) DEVICE HBM at run: the python-loop keeps an fp32 grad accumulator resident # in HBM on top of params + adamw mu/nu + master weights, so micro=16 tipped # jit_micro_grad over the edge (wanted 14.00G, only 13.35G free -> a REAL # RESOURCE_EXHAUSTED with traceback, unlike the host kill). Fixed by halving # micro_batch: micro=8 x ga=16 = SAME 128 seq = 131k tok/step, identical # math, but half the per-micro activation footprint. micro_batch: int = field(default_factory=_default_micro_batch) # 8 on TPU, 4 on GPU (see fn) grad_accum: int = 4 # global batch = 32 seq/step (TPU) or 4*4*2dev = 32 (GPU pmap) max_steps: int = 60_000 warmup_steps: int = 500 lr: float = 6e-4 min_lr: float = 6e-5 weight_decay: float = 0.1 beta1: float = 0.9 beta2: float = 0.95 grad_clip: float = 1.0 # Durability: how often to push a checkpoint to HF Hub. save_every: int = 1000 eval_every: int = 1000 eval_iters: int = 100 log_every: int = 20 seed: int = 1337 TOKENIZER = TokenizerConfig() MODEL = ModelConfig() TRAIN = TrainConfig() def summary() -> dict: return { "data_repo": DATA_REPO, "code_repo": CODE_REPO, "ckpt_repo": CKPT_REPO, "source": f"{SOURCE_DATASET}:{SOURCE_CONFIG}", "tokenizer": asdict(TOKENIZER), "model": asdict(MODEL), "train": asdict(TRAIN), "ffn_hidden": MODEL.ffn_hidden(), } if __name__ == "__main__": print(json.dumps(summary(), indent=2, ensure_ascii=False))