Upload folder using huggingface_hub
Browse files- bangla30m/.gitignore +5 -0
- bangla30m/README.md +181 -0
- bangla30m/bangla30m/__init__.py +6 -0
- bangla30m/bangla30m/benchmark.py +118 -0
- bangla30m/bangla30m/checkpoint.py +63 -0
- bangla30m/bangla30m/config.py +206 -0
- bangla30m/bangla30m/data.py +214 -0
- bangla30m/bangla30m/evaluate.py +60 -0
- bangla30m/bangla30m/model.py +279 -0
- bangla30m/bangla30m/optim.py +48 -0
- bangla30m/bangla30m/tokenizer.py +138 -0
- bangla30m/bangla30m/trainer.py +225 -0
- bangla30m/notebooks/Bangla30M_Kaggle.ipynb +147 -0
- bangla30m/pytest.ini +3 -0
- bangla30m/requirements.txt +5 -0
- bangla30m/scripts/01_install.py +52 -0
- bangla30m/scripts/02_train_tokenizer.py +49 -0
- bangla30m/scripts/03_speed_test.py +58 -0
- bangla30m/scripts/04_train.py +72 -0
- bangla30m/scripts/05_evaluate.py +71 -0
- bangla30m/tests/test_config.py +55 -0
- bangla30m/tests/test_data.py +107 -0
- bangla30m/tests/test_model.py +116 -0
- bangla30m/tests/test_tokenizer.py +45 -0
- bangla30m/tests/test_trainer.py +78 -0
bangla30m/.gitignore
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
.pytest_cache/
|
| 4 |
+
artifacts/
|
| 5 |
+
*.egg-info/
|
bangla30m/README.md
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Bangla-30M
|
| 2 |
+
|
| 3 |
+
A from-scratch decoder-only Bangla language model, sized and tuned to pretrain
|
| 4 |
+
on **700M tokens of [B-CORE](https://huggingface.co/datasets/nahid-hub/B-CORE-bengali-corpus)**
|
| 5 |
+
on Kaggle's free **2x T4** GPUs.
|
| 6 |
+
|
| 7 |
+
```
|
| 8 |
+
Hugging Face (streaming) -> clean -> BPE tokenize -> pack into 512-token
|
| 9 |
+
blocks -> DDP across 2x T4, fp16 -> ~30-32M param transformer
|
| 10 |
+
```
|
| 11 |
+
|
| 12 |
+
## Architecture
|
| 13 |
+
|
| 14 |
+
| | |
|
| 15 |
+
|---|---|
|
| 16 |
+
| Params | **31.75M** (analytic == actual, see `tests/test_model.py`) |
|
| 17 |
+
| Vocab | 32,000 (byte-level BPE, trained on a B-CORE sample) |
|
| 18 |
+
| Hidden size | 432 |
|
| 19 |
+
| Layers | 8 |
|
| 20 |
+
| Heads | 8 (head_dim 54) |
|
| 21 |
+
| FFN | 1,152 (SwiGLU: gate/up/down) |
|
| 22 |
+
| Context | 512 |
|
| 23 |
+
| Position encoding | RoPE (θ=10,000) |
|
| 24 |
+
| Norm | RMSNorm, pre-norm |
|
| 25 |
+
| Embeddings | tied input/output |
|
| 26 |
+
| Attention | `F.scaled_dot_product_attention` (flash/mem-efficient kernels on CUDA automatically) |
|
| 27 |
+
|
| 28 |
+
**One deliberate deviation from the original plan:** the plan listed
|
| 29 |
+
`activation = SwiGLU/GELU` without picking one, sized for a plain 4x-hidden
|
| 30 |
+
GELU MLP (1,728). I went with **SwiGLU** (the LLaMA-family default and the
|
| 31 |
+
better choice per-FLOP at this scale) but shrank the FFN to **1,152**
|
| 32 |
+
(`8/3 x hidden`, LLaMA's standard ratio) so the *parameter budget* lands in
|
| 33 |
+
the same 30-32M range despite SwiGLU's third matrix. `ModelConfig.autotune_hidden_size()`
|
| 34 |
+
is there if you want to re-target a different exact parameter count later.
|
| 35 |
+
|
| 36 |
+
Run `python -m bangla30m.config` any time to print the exact breakdown.
|
| 37 |
+
|
| 38 |
+
## Repo layout
|
| 39 |
+
|
| 40 |
+
```
|
| 41 |
+
bangla30m/
|
| 42 |
+
config.py ModelConfig / TrainConfig (+ parameter accounting, autotune)
|
| 43 |
+
model.py RMSNorm, RoPE, SwiGLU/GELU, causal attention, the model itself
|
| 44 |
+
tokenizer.py BPE training + a dependency-free tokenizer wrapper
|
| 45 |
+
data.py streaming clean -> tokenize -> pack pipeline (distributed-safe)
|
| 46 |
+
optim.py AdamW param groups + warmup/cosine LR schedule
|
| 47 |
+
trainer.py accelerate-based training loop, deterministic token accounting
|
| 48 |
+
checkpoint.py token-milestone checkpointing + resume
|
| 49 |
+
benchmark.py the mandatory "measure before you commit 7-8h" speed test
|
| 50 |
+
evaluate.py held-out perplexity + sample generation
|
| 51 |
+
scripts/
|
| 52 |
+
01_install.py environment / GPU sanity check
|
| 53 |
+
02_train_tokenizer.py train the 32K BPE tokenizer on a B-CORE sample
|
| 54 |
+
03_speed_test.py 10M-token throughput benchmark -> time projection
|
| 55 |
+
04_train.py the full 700M-token run (resumable)
|
| 56 |
+
05_evaluate.py perplexity + sample generations from a checkpoint
|
| 57 |
+
tests/ 37 tests, all offline/CPU — see "Testing" below
|
| 58 |
+
notebooks/
|
| 59 |
+
Bangla30M_Kaggle.ipynb the same 5 stages as notebook cells
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
## Kaggle setup
|
| 63 |
+
|
| 64 |
+
1. New Kaggle notebook, **Settings -> Accelerator -> GPU T4 x2**, internet ON.
|
| 65 |
+
2. Upload/extract this folder to `/kaggle/working/bangla30m`.
|
| 66 |
+
3. Open `notebooks/Bangla30M_Kaggle.ipynb`, or run the cells below manually.
|
| 67 |
+
|
| 68 |
+
```python
|
| 69 |
+
import sys; sys.path.insert(0, "/kaggle/working/bangla30m")
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
**Stage 1 — environment check**
|
| 73 |
+
```bash
|
| 74 |
+
!python scripts/01_install.py
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
**Stage 2 — tokenizer** (streams a sample from B-CORE, does *not* download
|
| 78 |
+
the full 20.8GB corpus)
|
| 79 |
+
```bash
|
| 80 |
+
!python scripts/02_train_tokenizer.py --out artifacts/tokenizer
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
**Stage 3 — speed test.** Always run this before the full job — 7-8h is a
|
| 84 |
+
*target*, not a guarantee; it depends on the actual streaming + tokenization
|
| 85 |
+
throughput this session gets.
|
| 86 |
+
```python
|
| 87 |
+
from accelerate import notebook_launcher
|
| 88 |
+
from bangla30m.benchmark import run_speed_test
|
| 89 |
+
from bangla30m.config import ModelConfig, TrainConfig
|
| 90 |
+
|
| 91 |
+
model_cfg = ModelConfig()
|
| 92 |
+
train_cfg = TrainConfig(tokenizer_dir="artifacts/tokenizer")
|
| 93 |
+
notebook_launcher(run_speed_test, args=(model_cfg, train_cfg, 10_000_000),
|
| 94 |
+
num_processes=2)
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
**Stage 4 — the full run.** Same cell can be re-run after a Kaggle session
|
| 98 |
+
gets cut off — it resumes automatically from the latest 100M-token
|
| 99 |
+
checkpoint under `output_dir`.
|
| 100 |
+
```python
|
| 101 |
+
from accelerate import notebook_launcher
|
| 102 |
+
from bangla30m.config import ModelConfig, TrainConfig
|
| 103 |
+
from bangla30m.trainer import run_training
|
| 104 |
+
|
| 105 |
+
model_cfg = ModelConfig()
|
| 106 |
+
train_cfg = TrainConfig(
|
| 107 |
+
tokenizer_dir="artifacts/tokenizer",
|
| 108 |
+
output_dir="artifacts/runs/bangla30m",
|
| 109 |
+
per_device_batch_size=32,
|
| 110 |
+
gradient_accumulation_steps=2, # ~65.5K effective tokens/step, 2xT4
|
| 111 |
+
)
|
| 112 |
+
notebook_launcher(run_training, args=(model_cfg, train_cfg), num_processes=2)
|
| 113 |
+
```
|
| 114 |
+
|
| 115 |
+
**Stage 5 — evaluate**
|
| 116 |
+
```bash
|
| 117 |
+
!python scripts/05_evaluate.py --checkpoint artifacts/runs/bangla30m/checkpoints/tokens_000700000000
|
| 118 |
+
```
|
| 119 |
+
|
| 120 |
+
### Tuning batch size / accumulation for your measured throughput
|
| 121 |
+
|
| 122 |
+
`TrainConfig.tokens_per_step` x `world_size` is the effective tokens/optimizer-step.
|
| 123 |
+
The plan's two reference points:
|
| 124 |
+
|
| 125 |
+
| effective tokens/step | steps for 700M |
|
| 126 |
+
|---|---|
|
| 127 |
+
| 32,768 (accum=1) | ~21,362 |
|
| 128 |
+
| 65,536 (accum=2) | ~10,681 |
|
| 129 |
+
|
| 130 |
+
Start with `gradient_accumulation_steps=1` for the *speed test* (isolates raw
|
| 131 |
+
per-GPU throughput), then raise it for the real run only if you need fewer,
|
| 132 |
+
larger optimizer steps.
|
| 133 |
+
|
| 134 |
+
## Testing
|
| 135 |
+
|
| 136 |
+
Everything in `tests/` runs offline, on CPU, with synthetic Bangla text —
|
| 137 |
+
no GPU or Hugging Face network access required, so it runs the same way in
|
| 138 |
+
CI as it did here:
|
| 139 |
+
|
| 140 |
+
```bash
|
| 141 |
+
pip install -r requirements.txt
|
| 142 |
+
python -m pytest -v
|
| 143 |
+
```
|
| 144 |
+
|
| 145 |
+
37/37 passing, covering: exact analytic-vs-actual parameter counts for both
|
| 146 |
+
activations, RoPE shape/rotation-preserves-norm, causal masking (a later
|
| 147 |
+
token provably can't leak into an earlier position's logits), gradient-
|
| 148 |
+
checkpointing numerically matching the non-checkpointed forward pass, the
|
| 149 |
+
garbage-text filter, token packing/shifting, and — most importantly — three
|
| 150 |
+
full offline training runs that check loss actually decreases, checkpoints
|
| 151 |
+
land at the right token milestones, and resuming continues past the prior
|
| 152 |
+
run's step/token counts rather than restarting.
|
| 153 |
+
|
| 154 |
+
What's *not* tested here (no GPU, no internet to huggingface.co in this
|
| 155 |
+
environment): real B-CORE streaming throughput and actual multi-T4 DDP
|
| 156 |
+
communication. That's exactly what `scripts/03_speed_test.py` (stage 3
|
| 157 |
+
above) is for — run it first on Kaggle before trusting any time estimate.
|
| 158 |
+
|
| 159 |
+
## Design notes / where I made independent calls
|
| 160 |
+
|
| 161 |
+
- **`accelerate` over raw `torch.distributed`**: `notebook_launcher` is the
|
| 162 |
+
standard, well-tested way to get real 2-process DDP out of a single Kaggle
|
| 163 |
+
notebook cell, and the same `run_training()` entry point also works via
|
| 164 |
+
`accelerate launch` from a terminal — no code fork between the two paths.
|
| 165 |
+
- **Deterministic token accounting**: tokens-per-step is fixed by
|
| 166 |
+
`batch_size x seq_len x grad_accum x world_size`, so the training loop
|
| 167 |
+
never needs a collective (`all_reduce`) just to know how many tokens it's
|
| 168 |
+
processed — one less thing that can desync or slow down the hot loop.
|
| 169 |
+
Loss is still `gather`ed across ranks, but only at `log_every_steps`.
|
| 170 |
+
- **The dataset's own token cap carries a 10% safety margin** over the
|
| 171 |
+
trainer's target — the trainer's step counter is the real stopping
|
| 172 |
+
condition; the dataset cap is a backstop so `DataLoader(drop_last=True)`
|
| 173 |
+
discarding a trailing partial batch can't leave the run a fraction of a
|
| 174 |
+
step short of its target on a slow/short stream.
|
| 175 |
+
- **No attention/MLP biases, RMSNorm, SwiGLU, RoPE, tied embeddings** — the
|
| 176 |
+
now-standard "efficient small LM" recipe (LLaMA-family), which is also
|
| 177 |
+
exactly what the plan's config sketch was already pointing at.
|
| 178 |
+
- **Checkpoint pruning** keeps the last 3 checkpoints by default
|
| 179 |
+
(`checkpoint.prune_old_checkpoints`) so Kaggle's working-directory disk
|
| 180 |
+
quota doesn't fill up over a 700M-token run; change `keep_last` in
|
| 181 |
+
`trainer.py` if you want every milestone kept.
|
bangla30m/bangla30m/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Bangla-30M: a from-scratch decoder-only Bangla language model, tuned for
|
| 3 |
+
700M-token pretraining runs on Kaggle's free 2x T4 GPUs in a 7-8 hour window.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
__version__ = "1.0.0"
|
bangla30m/bangla30m/benchmark.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Speed test, per the plan: never launch the full 700M-token run blind.
|
| 3 |
+
Measure tokens/sec on a small slice first, then extrapolate.
|
| 4 |
+
|
| 5 |
+
expected_hours = target_tokens / measured_tokens_per_second / 3600
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import time
|
| 10 |
+
from dataclasses import dataclass
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
from accelerate import Accelerator
|
| 14 |
+
|
| 15 |
+
from .config import ModelConfig, TrainConfig
|
| 16 |
+
from .data import BCoreStreamingDataset, collate_fn
|
| 17 |
+
from .model import build_model
|
| 18 |
+
from .optim import build_optimizer
|
| 19 |
+
from .tokenizer import Bangla30MTokenizer
|
| 20 |
+
from .trainer import build_dataloader
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@dataclass
|
| 24 |
+
class BenchmarkResult:
|
| 25 |
+
benchmark_tokens: int
|
| 26 |
+
elapsed_seconds: float
|
| 27 |
+
tokens_per_second: float
|
| 28 |
+
steps: int
|
| 29 |
+
world_size: int
|
| 30 |
+
extrapolated_hours_for_target: float
|
| 31 |
+
gpu_name: str = ""
|
| 32 |
+
peak_gpu_mem_gb: float = 0.0
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def run_speed_test(
|
| 36 |
+
model_cfg: ModelConfig,
|
| 37 |
+
train_cfg: TrainConfig,
|
| 38 |
+
benchmark_tokens: int = 10_000_000,
|
| 39 |
+
target_tokens_for_estimate: int | None = None,
|
| 40 |
+
source_dataset=None,
|
| 41 |
+
) -> BenchmarkResult:
|
| 42 |
+
accelerator = Accelerator(mixed_precision=train_cfg.mixed_precision)
|
| 43 |
+
target_tokens_for_estimate = target_tokens_for_estimate or train_cfg.target_tokens
|
| 44 |
+
|
| 45 |
+
tokenizer = Bangla30MTokenizer.from_dir(train_cfg.tokenizer_dir)
|
| 46 |
+
model_cfg.vocab_size = tokenizer.vocab_size
|
| 47 |
+
model = build_model(model_cfg)
|
| 48 |
+
optimizer = build_optimizer(model, train_cfg)
|
| 49 |
+
|
| 50 |
+
world_size = accelerator.num_processes
|
| 51 |
+
dataloader = build_dataloader(
|
| 52 |
+
train_cfg, tokenizer, accelerator.process_index, world_size,
|
| 53 |
+
source_dataset=source_dataset,
|
| 54 |
+
)
|
| 55 |
+
model, optimizer, dataloader = accelerator.prepare(model, optimizer, dataloader)
|
| 56 |
+
|
| 57 |
+
if torch.cuda.is_available():
|
| 58 |
+
torch.cuda.reset_peak_memory_stats()
|
| 59 |
+
torch.cuda.synchronize()
|
| 60 |
+
|
| 61 |
+
model.train()
|
| 62 |
+
tokens_per_step = train_cfg.per_device_batch_size * train_cfg.seq_len * world_size
|
| 63 |
+
benchmark_steps = max(1, -(-benchmark_tokens // tokens_per_step))
|
| 64 |
+
|
| 65 |
+
# warm up a couple of steps (kernel autotune / cudnn benchmark) — not timed
|
| 66 |
+
warmup_steps = min(3, benchmark_steps)
|
| 67 |
+
data_iter = iter(dataloader)
|
| 68 |
+
for _ in range(warmup_steps):
|
| 69 |
+
batch = next(data_iter)
|
| 70 |
+
out = model(batch["input_ids"], labels=batch["labels"])
|
| 71 |
+
accelerator.backward(out.loss)
|
| 72 |
+
optimizer.step()
|
| 73 |
+
optimizer.zero_grad()
|
| 74 |
+
|
| 75 |
+
if torch.cuda.is_available():
|
| 76 |
+
torch.cuda.synchronize()
|
| 77 |
+
start = time.time()
|
| 78 |
+
steps_run = 0
|
| 79 |
+
for _ in range(benchmark_steps):
|
| 80 |
+
try:
|
| 81 |
+
batch = next(data_iter)
|
| 82 |
+
except StopIteration:
|
| 83 |
+
break
|
| 84 |
+
out = model(batch["input_ids"], labels=batch["labels"])
|
| 85 |
+
accelerator.backward(out.loss)
|
| 86 |
+
optimizer.step()
|
| 87 |
+
optimizer.zero_grad()
|
| 88 |
+
steps_run += 1
|
| 89 |
+
if torch.cuda.is_available():
|
| 90 |
+
torch.cuda.synchronize()
|
| 91 |
+
elapsed = time.time() - start
|
| 92 |
+
|
| 93 |
+
measured_tokens = steps_run * tokens_per_step
|
| 94 |
+
tok_per_sec = measured_tokens / max(1e-6, elapsed)
|
| 95 |
+
extrapolated_hours = target_tokens_for_estimate / max(1e-6, tok_per_sec) / 3600
|
| 96 |
+
|
| 97 |
+
peak_mem_gb = torch.cuda.max_memory_allocated() / 1e9 if torch.cuda.is_available() else 0.0
|
| 98 |
+
gpu_name = torch.cuda.get_device_name(0) if torch.cuda.is_available() else "cpu"
|
| 99 |
+
|
| 100 |
+
result = BenchmarkResult(
|
| 101 |
+
benchmark_tokens=measured_tokens,
|
| 102 |
+
elapsed_seconds=elapsed,
|
| 103 |
+
tokens_per_second=tok_per_sec,
|
| 104 |
+
steps=steps_run,
|
| 105 |
+
world_size=world_size,
|
| 106 |
+
extrapolated_hours_for_target=extrapolated_hours,
|
| 107 |
+
gpu_name=gpu_name,
|
| 108 |
+
peak_gpu_mem_gb=peak_mem_gb,
|
| 109 |
+
)
|
| 110 |
+
if accelerator.is_main_process:
|
| 111 |
+
accelerator.print(
|
| 112 |
+
f"[speed-test] {result.tokens_per_second/1000:.1f}K tok/s aggregate "
|
| 113 |
+
f"({world_size} process(es), {result.gpu_name}) -> "
|
| 114 |
+
f"~{result.extrapolated_hours_for_target:.2f}h for "
|
| 115 |
+
f"{target_tokens_for_estimate/1e6:.0f}M tokens "
|
| 116 |
+
f"(peak GPU mem {result.peak_gpu_mem_gb:.2f} GB)"
|
| 117 |
+
)
|
| 118 |
+
return result
|
bangla30m/bangla30m/checkpoint.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Checkpointing keyed by tokens-seen (per the plan's 100M/200M/.../700M
|
| 3 |
+
milestones), so a Kaggle session interruption never loses more than one
|
| 4 |
+
checkpoint interval of progress.
|
| 5 |
+
|
| 6 |
+
Works with an `accelerate.Accelerator` for the heavy model/optimizer state,
|
| 7 |
+
plus a small sidecar `progress.json` for the token/step counters and RNG-
|
| 8 |
+
independent bookkeeping that `accelerator.save_state` doesn't track for us.
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
import shutil
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Optional
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def checkpoint_dir(output_dir: str | Path, tokens_seen: int) -> Path:
|
| 19 |
+
return Path(output_dir) / "checkpoints" / f"tokens_{tokens_seen:012d}"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def latest_pointer(output_dir: str | Path) -> Path:
|
| 23 |
+
return Path(output_dir) / "checkpoints" / "latest.json"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def save_checkpoint(accelerator, output_dir: str | Path, tokens_seen: int, step: int, extra: Optional[dict] = None) -> Path:
|
| 27 |
+
ckpt_dir = checkpoint_dir(output_dir, tokens_seen)
|
| 28 |
+
accelerator.save_state(str(ckpt_dir))
|
| 29 |
+
if accelerator.is_main_process:
|
| 30 |
+
progress = {"tokens_seen": tokens_seen, "step": step, **(extra or {})}
|
| 31 |
+
(ckpt_dir / "progress.json").write_text(json.dumps(progress, indent=2))
|
| 32 |
+
latest_pointer(output_dir).parent.mkdir(parents=True, exist_ok=True)
|
| 33 |
+
latest_pointer(output_dir).write_text(json.dumps({"path": str(ckpt_dir), **progress}, indent=2))
|
| 34 |
+
accelerator.wait_for_everyone()
|
| 35 |
+
return ckpt_dir
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def find_latest_checkpoint(output_dir: str | Path) -> Optional[dict]:
|
| 39 |
+
ptr = latest_pointer(output_dir)
|
| 40 |
+
if not ptr.exists():
|
| 41 |
+
return None
|
| 42 |
+
info = json.loads(ptr.read_text())
|
| 43 |
+
if not Path(info["path"]).exists():
|
| 44 |
+
return None
|
| 45 |
+
return info
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def load_checkpoint(accelerator, ckpt_path: str | Path) -> dict:
|
| 49 |
+
accelerator.load_state(str(ckpt_path))
|
| 50 |
+
progress_file = Path(ckpt_path) / "progress.json"
|
| 51 |
+
return json.loads(progress_file.read_text()) if progress_file.exists() else {}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def prune_old_checkpoints(output_dir: str | Path, keep_last: int = 3) -> None:
|
| 55 |
+
ckdir = Path(output_dir) / "checkpoints"
|
| 56 |
+
if not ckdir.exists():
|
| 57 |
+
return
|
| 58 |
+
dirs = sorted(
|
| 59 |
+
[d for d in ckdir.iterdir() if d.is_dir() and d.name.startswith("tokens_")],
|
| 60 |
+
key=lambda d: d.name,
|
| 61 |
+
)
|
| 62 |
+
for d in dirs[:-keep_last] if keep_last > 0 else []:
|
| 63 |
+
shutil.rmtree(d, ignore_errors=True)
|
bangla30m/bangla30m/config.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Configuration objects for Bangla-30M.
|
| 3 |
+
|
| 4 |
+
Two dataclasses:
|
| 5 |
+
- ModelConfig: architecture (decoder-only transformer, RoPE, RMSNorm, SwiGLU/GELU)
|
| 6 |
+
- TrainConfig: data / optimization / Kaggle-T4x2 run settings
|
| 7 |
+
|
| 8 |
+
`ModelConfig` also carries the parameter-accounting math described in the plan
|
| 9 |
+
("print exact param count at startup, nudge hidden_size if needed"), exposed
|
| 10 |
+
as `count_parameters()` and `autotune_hidden_size()` so the shape can be
|
| 11 |
+
re-targeted without touching model code.
|
| 12 |
+
"""
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
from dataclasses import asdict, dataclass, field
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from typing import Literal, Optional
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass
|
| 22 |
+
class ModelConfig:
|
| 23 |
+
vocab_size: int = 32_000
|
| 24 |
+
hidden_size: int = 432
|
| 25 |
+
num_layers: int = 8
|
| 26 |
+
num_heads: int = 8
|
| 27 |
+
# FFN inner size. If None, it is derived from `activation`:
|
| 28 |
+
# gelu -> 4 * hidden_size (standard transformer MLP)
|
| 29 |
+
# swiglu -> round( (8/3) * hidden_size ) (LLaMA-style, 3 matrices
|
| 30 |
+
# instead of 2, so the
|
| 31 |
+
# ratio is shrunk to keep
|
| 32 |
+
# the same param budget)
|
| 33 |
+
ffn_size: Optional[int] = None
|
| 34 |
+
max_seq_len: int = 512
|
| 35 |
+
activation: Literal["swiglu", "gelu"] = "swiglu"
|
| 36 |
+
norm_eps: float = 1e-5
|
| 37 |
+
rope_theta: float = 10_000.0
|
| 38 |
+
tie_embeddings: bool = True
|
| 39 |
+
dropout: float = 0.0
|
| 40 |
+
attn_bias: bool = False
|
| 41 |
+
pad_token_id: int = 2
|
| 42 |
+
bos_token_id: int = 0
|
| 43 |
+
eos_token_id: int = 1
|
| 44 |
+
unk_token_id: int = 3
|
| 45 |
+
|
| 46 |
+
def __post_init__(self) -> None:
|
| 47 |
+
if self.hidden_size % self.num_heads != 0:
|
| 48 |
+
raise ValueError(
|
| 49 |
+
f"hidden_size ({self.hidden_size}) must be divisible by "
|
| 50 |
+
f"num_heads ({self.num_heads})"
|
| 51 |
+
)
|
| 52 |
+
if self.ffn_size is None:
|
| 53 |
+
self.ffn_size = self._default_ffn_size(self.hidden_size, self.activation)
|
| 54 |
+
|
| 55 |
+
@property
|
| 56 |
+
def head_dim(self) -> int:
|
| 57 |
+
return self.hidden_size // self.num_heads
|
| 58 |
+
|
| 59 |
+
@staticmethod
|
| 60 |
+
def _default_ffn_size(hidden_size: int, activation: str) -> int:
|
| 61 |
+
if activation == "swiglu":
|
| 62 |
+
raw = (8 / 3) * hidden_size
|
| 63 |
+
else:
|
| 64 |
+
raw = 4 * hidden_size
|
| 65 |
+
# round to nearest multiple of 8 for clean GPU tiling
|
| 66 |
+
return max(8, int(round(raw / 8) * 8))
|
| 67 |
+
|
| 68 |
+
# ---- parameter accounting -------------------------------------------------
|
| 69 |
+
def count_parameters(self) -> dict:
|
| 70 |
+
"""Exact analytic parameter count (matches the real nn.Module 1:1).
|
| 71 |
+
|
| 72 |
+
Returns a breakdown dict; total is under key 'total'.
|
| 73 |
+
"""
|
| 74 |
+
h, ffn, L = self.hidden_size, self.ffn_size, self.num_layers
|
| 75 |
+
|
| 76 |
+
embed = self.vocab_size * h
|
| 77 |
+
attn_per_layer = 4 * h * h + (4 * h if self.attn_bias else 0) # q,k,v,o
|
| 78 |
+
if self.activation == "swiglu":
|
| 79 |
+
ffn_per_layer = 3 * h * ffn # gate, up, down
|
| 80 |
+
else:
|
| 81 |
+
ffn_per_layer = 2 * h * ffn # up, down
|
| 82 |
+
norms_per_layer = 2 * h # pre-attn RMSNorm + pre-ffn RMSNorm
|
| 83 |
+
per_layer = attn_per_layer + ffn_per_layer + norms_per_layer
|
| 84 |
+
final_norm = h
|
| 85 |
+
lm_head = 0 if self.tie_embeddings else self.vocab_size * h
|
| 86 |
+
|
| 87 |
+
total = embed + per_layer * L + final_norm + lm_head
|
| 88 |
+
return {
|
| 89 |
+
"embedding": embed,
|
| 90 |
+
"per_layer": per_layer,
|
| 91 |
+
"all_layers": per_layer * L,
|
| 92 |
+
"final_norm": final_norm,
|
| 93 |
+
"lm_head": lm_head,
|
| 94 |
+
"total": total,
|
| 95 |
+
"total_millions": round(total / 1e6, 2),
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
def autotune_hidden_size(
|
| 99 |
+
self,
|
| 100 |
+
target_params: int = 30_000_000,
|
| 101 |
+
search_range: int = 96,
|
| 102 |
+
step: Optional[int] = None,
|
| 103 |
+
) -> "ModelConfig":
|
| 104 |
+
"""Return a copy with hidden_size nudged so total params sit closest
|
| 105 |
+
to `target_params`, keeping num_heads / num_layers / activation fixed
|
| 106 |
+
(and re-deriving ffn_size at each candidate, matching how the real
|
| 107 |
+
model would be sized).
|
| 108 |
+
"""
|
| 109 |
+
step = step or self.num_heads
|
| 110 |
+
best_cfg, best_diff = self, float("inf")
|
| 111 |
+
lo = max(self.num_heads, self.hidden_size - search_range)
|
| 112 |
+
hi = self.hidden_size + search_range
|
| 113 |
+
for h in range(lo, hi + 1, step):
|
| 114 |
+
candidate = ModelConfig(
|
| 115 |
+
vocab_size=self.vocab_size,
|
| 116 |
+
hidden_size=h,
|
| 117 |
+
num_layers=self.num_layers,
|
| 118 |
+
num_heads=self.num_heads,
|
| 119 |
+
ffn_size=None,
|
| 120 |
+
max_seq_len=self.max_seq_len,
|
| 121 |
+
activation=self.activation,
|
| 122 |
+
norm_eps=self.norm_eps,
|
| 123 |
+
rope_theta=self.rope_theta,
|
| 124 |
+
tie_embeddings=self.tie_embeddings,
|
| 125 |
+
dropout=self.dropout,
|
| 126 |
+
attn_bias=self.attn_bias,
|
| 127 |
+
)
|
| 128 |
+
diff = abs(candidate.count_parameters()["total"] - target_params)
|
| 129 |
+
if diff < best_diff:
|
| 130 |
+
best_cfg, best_diff = candidate, diff
|
| 131 |
+
return best_cfg
|
| 132 |
+
|
| 133 |
+
def save(self, path: str | Path) -> None:
|
| 134 |
+
Path(path).write_text(json.dumps(asdict(self), indent=2, ensure_ascii=False))
|
| 135 |
+
|
| 136 |
+
@classmethod
|
| 137 |
+
def load(cls, path: str | Path) -> "ModelConfig":
|
| 138 |
+
return cls(**json.loads(Path(path).read_text()))
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
@dataclass
|
| 142 |
+
class TrainConfig:
|
| 143 |
+
# data
|
| 144 |
+
dataset_name: str = "nahid-hub/B-CORE-bengali-corpus"
|
| 145 |
+
dataset_split: str = "train"
|
| 146 |
+
text_column: str = "text"
|
| 147 |
+
target_tokens: int = 700_000_000
|
| 148 |
+
seq_len: int = 512
|
| 149 |
+
min_chars: int = 20 # lightweight-clean: drop very short docs
|
| 150 |
+
max_repeat_char_run: int = 12 # drop obvious garbage/spam runs
|
| 151 |
+
|
| 152 |
+
# tokenizer
|
| 153 |
+
tokenizer_dir: str = "artifacts/tokenizer"
|
| 154 |
+
tokenizer_train_docs: int = 20_000_000 # ~10-30M tokens per the plan
|
| 155 |
+
|
| 156 |
+
# batching
|
| 157 |
+
per_device_batch_size: int = 32
|
| 158 |
+
gradient_accumulation_steps: int = 2
|
| 159 |
+
dataloader_workers: int = 2
|
| 160 |
+
|
| 161 |
+
# optimization
|
| 162 |
+
learning_rate: float = 3e-4
|
| 163 |
+
min_learning_rate_ratio: float = 0.1
|
| 164 |
+
weight_decay: float = 0.1
|
| 165 |
+
warmup_ratio: float = 0.02
|
| 166 |
+
grad_clip: float = 1.0
|
| 167 |
+
adam_beta1: float = 0.9
|
| 168 |
+
adam_beta2: float = 0.95
|
| 169 |
+
adam_eps: float = 1e-8
|
| 170 |
+
|
| 171 |
+
# precision / hardware
|
| 172 |
+
mixed_precision: Literal["fp16", "bf16", "no"] = "fp16"
|
| 173 |
+
gradient_checkpointing: bool = False # OFF initially per the plan
|
| 174 |
+
|
| 175 |
+
# checkpointing / logging
|
| 176 |
+
output_dir: str = "artifacts/runs/bangla30m"
|
| 177 |
+
checkpoint_every_tokens: int = 100_000_000
|
| 178 |
+
log_every_steps: int = 20
|
| 179 |
+
seed: int = 42
|
| 180 |
+
|
| 181 |
+
# misc
|
| 182 |
+
resume_from_checkpoint: bool = True
|
| 183 |
+
|
| 184 |
+
@property
|
| 185 |
+
def tokens_per_step(self) -> int:
|
| 186 |
+
# world_size is multiplied in at run time (trainer knows num_processes)
|
| 187 |
+
return self.per_device_batch_size * self.seq_len * self.gradient_accumulation_steps
|
| 188 |
+
|
| 189 |
+
def total_steps(self, world_size: int = 1) -> int:
|
| 190 |
+
eff = self.tokens_per_step * world_size
|
| 191 |
+
return max(1, -(-self.target_tokens // eff)) # ceil div
|
| 192 |
+
|
| 193 |
+
def save(self, path: str | Path) -> None:
|
| 194 |
+
Path(path).write_text(json.dumps(asdict(self), indent=2, ensure_ascii=False))
|
| 195 |
+
|
| 196 |
+
@classmethod
|
| 197 |
+
def load(cls, path: str | Path) -> "TrainConfig":
|
| 198 |
+
return cls(**json.loads(Path(path).read_text()))
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
if __name__ == "__main__":
|
| 202 |
+
cfg = ModelConfig()
|
| 203 |
+
stats = cfg.count_parameters()
|
| 204 |
+
print(f"activation={cfg.activation} hidden={cfg.hidden_size} ffn={cfg.ffn_size} "
|
| 205 |
+
f"layers={cfg.num_layers} heads={cfg.num_heads} (head_dim={cfg.head_dim})")
|
| 206 |
+
print(json.dumps(stats, indent=2))
|
bangla30m/bangla30m/data.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Data pipeline: HF streaming -> lightweight clean -> tokenize -> pack -> GPU.
|
| 3 |
+
|
| 4 |
+
B-CORE is already deduplicated/quality-filtered upstream (per its dataset
|
| 5 |
+
card), so this file intentionally does NOT re-run heavy cleaning -- only the
|
| 6 |
+
"obvious garbage" checks called for in the plan, so the CPU never becomes the
|
| 7 |
+
bottleneck feeding a 16GB T4.
|
| 8 |
+
|
| 9 |
+
Two entry points:
|
| 10 |
+
- `clean_text` / `TokenPacker` : pure, unit-testable logic
|
| 11 |
+
- `BCoreStreamingDataset` : torch IterableDataset wrapping
|
| 12 |
+
`datasets` streaming + sharding
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import re
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
from typing import Iterable, Iterator, Optional
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch.utils.data import IterableDataset, get_worker_info
|
| 22 |
+
|
| 23 |
+
from .tokenizer import Bangla30MTokenizer
|
| 24 |
+
|
| 25 |
+
_REPEAT_RE_CACHE: dict[int, re.Pattern] = {}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _repeat_pattern(n: int) -> re.Pattern:
|
| 29 |
+
if n not in _REPEAT_RE_CACHE:
|
| 30 |
+
_REPEAT_RE_CACHE[n] = re.compile(r"(.)\1{" + str(n) + r",}")
|
| 31 |
+
return _REPEAT_RE_CACHE[n]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def clean_text(text: Optional[str], min_chars: int = 20, max_repeat_char_run: int = 12) -> Optional[str]:
|
| 35 |
+
"""Lightweight garbage filter. Returns the (unicode-normalized-by-tokenizer-
|
| 36 |
+
later) stripped text, or None if the document should be dropped.
|
| 37 |
+
|
| 38 |
+
Checks, in order (cheapest first, so bad docs short-circuit fast):
|
| 39 |
+
1. exists / non-empty
|
| 40 |
+
2. minimum length
|
| 41 |
+
3. no pathological same-character run (spam/garbage)
|
| 42 |
+
4. reasonable printable-character ratio (catches binary/mojibake)
|
| 43 |
+
"""
|
| 44 |
+
if not text:
|
| 45 |
+
return None
|
| 46 |
+
text = text.strip()
|
| 47 |
+
if len(text) < min_chars:
|
| 48 |
+
return None
|
| 49 |
+
if _repeat_pattern(max_repeat_char_run).search(text):
|
| 50 |
+
return None
|
| 51 |
+
printable = sum(1 for c in text if c.isprintable() or c in "\n\t")
|
| 52 |
+
if printable / len(text) < 0.9:
|
| 53 |
+
return None
|
| 54 |
+
return text
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class TokenPacker:
|
| 58 |
+
"""Accumulates token-id lists into fixed-length (seq_len + 1) chunks.
|
| 59 |
+
|
| 60 |
+
The +1 is so the caller can build (input_ids, labels) via a single shift:
|
| 61 |
+
input_ids = chunk[:-1], labels = chunk[1:]. Leftover tokens are carried
|
| 62 |
+
over to the next document instead of being dropped, per the plan's
|
| 63 |
+
"packed sequences" optimization (no wasted padding).
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
def __init__(self, seq_len: int, eos_token_id: int):
|
| 67 |
+
self.chunk_len = seq_len + 1
|
| 68 |
+
self.eos_token_id = eos_token_id
|
| 69 |
+
self._buffer: list[int] = []
|
| 70 |
+
|
| 71 |
+
def feed(self, token_ids: list[int]) -> Iterator[list[int]]:
|
| 72 |
+
self._buffer.extend(token_ids)
|
| 73 |
+
self._buffer.append(self.eos_token_id)
|
| 74 |
+
while len(self._buffer) >= self.chunk_len:
|
| 75 |
+
yield self._buffer[: self.chunk_len]
|
| 76 |
+
self._buffer = self._buffer[self.chunk_len :]
|
| 77 |
+
|
| 78 |
+
def __len__(self) -> int:
|
| 79 |
+
return len(self._buffer)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@dataclass
|
| 83 |
+
class PipelineStats:
|
| 84 |
+
docs_seen: int = 0
|
| 85 |
+
docs_kept: int = 0
|
| 86 |
+
tokens_yielded: int = 0
|
| 87 |
+
examples_yielded: int = 0
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class BCoreStreamingDataset(IterableDataset):
|
| 91 |
+
"""Streams B-CORE (or any HF text dataset), cleans, tokenizes, and packs
|
| 92 |
+
into fixed-length blocks, stopping once this process has emitted its
|
| 93 |
+
share of `target_tokens`.
|
| 94 |
+
|
| 95 |
+
Distributed-safe: shards the underlying stream across `rank`/`world_size`
|
| 96 |
+
via `datasets.distributed.split_dataset_by_node`, so N processes together
|
| 97 |
+
cover ~target_tokens without duplicating documents.
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
def __init__(
|
| 101 |
+
self,
|
| 102 |
+
tokenizer: Bangla30MTokenizer,
|
| 103 |
+
seq_len: int = 512,
|
| 104 |
+
dataset_name: str = "nahid-hub/B-CORE-bengali-corpus",
|
| 105 |
+
dataset_split: str = "train",
|
| 106 |
+
text_column: str = "text",
|
| 107 |
+
target_tokens: int = 700_000_000,
|
| 108 |
+
min_chars: int = 20,
|
| 109 |
+
max_repeat_char_run: int = 12,
|
| 110 |
+
rank: int = 0,
|
| 111 |
+
world_size: int = 1,
|
| 112 |
+
skip_examples: int = 0,
|
| 113 |
+
source_dataset=None, # inject an already-built iterable for tests/offline use
|
| 114 |
+
):
|
| 115 |
+
super().__init__()
|
| 116 |
+
self.tokenizer = tokenizer
|
| 117 |
+
self.seq_len = seq_len
|
| 118 |
+
self.dataset_name = dataset_name
|
| 119 |
+
self.dataset_split = dataset_split
|
| 120 |
+
self.text_column = text_column
|
| 121 |
+
self.target_tokens_per_rank = max(1, target_tokens // max(1, world_size))
|
| 122 |
+
self.min_chars = min_chars
|
| 123 |
+
self.max_repeat_char_run = max_repeat_char_run
|
| 124 |
+
self.rank = rank
|
| 125 |
+
self.world_size = world_size
|
| 126 |
+
self.skip_examples = skip_examples
|
| 127 |
+
self._source_dataset = source_dataset
|
| 128 |
+
self.stats = PipelineStats()
|
| 129 |
+
|
| 130 |
+
# ---- source ---------------------------------------------------------
|
| 131 |
+
def _build_source(self):
|
| 132 |
+
if self._source_dataset is not None:
|
| 133 |
+
return self._source_dataset
|
| 134 |
+
import datasets as hf_datasets # local import: optional heavy dep
|
| 135 |
+
|
| 136 |
+
ds = hf_datasets.load_dataset(
|
| 137 |
+
self.dataset_name, split=self.dataset_split, streaming=True
|
| 138 |
+
)
|
| 139 |
+
if self.world_size > 1:
|
| 140 |
+
ds = hf_datasets.distributed.split_dataset_by_node(
|
| 141 |
+
ds, rank=self.rank, world_size=self.world_size
|
| 142 |
+
)
|
| 143 |
+
return ds
|
| 144 |
+
|
| 145 |
+
# ---- IterableDataset protocol ----------------------------------------
|
| 146 |
+
def __iter__(self) -> Iterator[dict]:
|
| 147 |
+
worker_info = get_worker_info()
|
| 148 |
+
source = self._build_source()
|
| 149 |
+
|
| 150 |
+
packer = TokenPacker(self.seq_len, self.tokenizer.eos_token_id)
|
| 151 |
+
local_tokens = 0
|
| 152 |
+
|
| 153 |
+
for idx, example in enumerate(source):
|
| 154 |
+
# further split across DataLoader workers within this process
|
| 155 |
+
if worker_info is not None and idx % worker_info.num_workers != worker_info.id:
|
| 156 |
+
continue
|
| 157 |
+
if idx < self.skip_examples:
|
| 158 |
+
continue
|
| 159 |
+
|
| 160 |
+
self.stats.docs_seen += 1
|
| 161 |
+
text = clean_text(example.get(self.text_column), self.min_chars, self.max_repeat_char_run)
|
| 162 |
+
if text is None:
|
| 163 |
+
continue
|
| 164 |
+
self.stats.docs_kept += 1
|
| 165 |
+
|
| 166 |
+
token_ids = self.tokenizer.encode(text, add_special_tokens=False)
|
| 167 |
+
for chunk in packer.feed(token_ids):
|
| 168 |
+
input_ids = torch.tensor(chunk[:-1], dtype=torch.long)
|
| 169 |
+
labels = torch.tensor(chunk[1:], dtype=torch.long)
|
| 170 |
+
n_new = len(chunk) - 1
|
| 171 |
+
local_tokens += n_new
|
| 172 |
+
self.stats.tokens_yielded += n_new
|
| 173 |
+
self.stats.examples_yielded += 1
|
| 174 |
+
yield {"input_ids": input_ids, "labels": labels}
|
| 175 |
+
|
| 176 |
+
if local_tokens >= self.target_tokens_per_rank:
|
| 177 |
+
return
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def collate_fn(batch: list[dict]) -> dict:
|
| 181 |
+
return {
|
| 182 |
+
"input_ids": torch.stack([b["input_ids"] for b in batch]),
|
| 183 |
+
"labels": torch.stack([b["labels"] for b in batch]),
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
if __name__ == "__main__":
|
| 188 |
+
# offline smoke test: no network / no real B-CORE access needed.
|
| 189 |
+
from .tokenizer import Bangla30MTokenizer, train_tokenizer
|
| 190 |
+
|
| 191 |
+
sample_docs = [
|
| 192 |
+
"আমি বাংলায় গান গাই। " * 5,
|
| 193 |
+
"কৃত্রিম বুদ্ধিমত্তা নিয়ে গবেষণা চলছে। " * 5,
|
| 194 |
+
"!!!!!!!!!!!!!!!!!!!!", # should be filtered (spam run)
|
| 195 |
+
"x", # should be filtered (too short)
|
| 196 |
+
"বাংলাদেশ দক্ষিণ এশিয়ার একটি দেশ। " * 5,
|
| 197 |
+
] * 20
|
| 198 |
+
|
| 199 |
+
train_tokenizer(sample_docs, vocab_size=800, save_dir="/tmp/bangla30m_tok_smoke2")
|
| 200 |
+
tok = Bangla30MTokenizer.from_dir("/tmp/bangla30m_tok_smoke2")
|
| 201 |
+
|
| 202 |
+
fake_source = ({"text": d} for d in sample_docs)
|
| 203 |
+
ds = BCoreStreamingDataset(
|
| 204 |
+
tokenizer=tok, seq_len=16, target_tokens=500,
|
| 205 |
+
source_dataset=fake_source,
|
| 206 |
+
)
|
| 207 |
+
n = 0
|
| 208 |
+
for batch in ds:
|
| 209 |
+
assert batch["input_ids"].shape == (16,)
|
| 210 |
+
assert batch["labels"].shape == (16,)
|
| 211 |
+
n += 1
|
| 212 |
+
print(f"packed examples: {n}, stats: {ds.stats}")
|
| 213 |
+
assert ds.stats.docs_kept < ds.stats.docs_seen, "garbage filter should have dropped some docs"
|
| 214 |
+
print("OK")
|
bangla30m/bangla30m/evaluate.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Evaluation utilities: perplexity on held-out data + qualitative samples."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import math
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from torch.utils.data import DataLoader
|
| 9 |
+
|
| 10 |
+
from .model import Bangla30M
|
| 11 |
+
from .tokenizer import Bangla30MTokenizer
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@dataclass
|
| 15 |
+
class EvalResult:
|
| 16 |
+
loss: float
|
| 17 |
+
perplexity: float
|
| 18 |
+
tokens_evaluated: int
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@torch.no_grad()
|
| 22 |
+
def compute_perplexity(model: Bangla30M, dataloader: DataLoader, max_batches: int = 200, device: str = "cpu") -> EvalResult:
|
| 23 |
+
model.eval()
|
| 24 |
+
total_loss, total_tokens, n_batches = 0.0, 0, 0
|
| 25 |
+
for batch in dataloader:
|
| 26 |
+
if n_batches >= max_batches:
|
| 27 |
+
break
|
| 28 |
+
input_ids = batch["input_ids"].to(device)
|
| 29 |
+
labels = batch["labels"].to(device)
|
| 30 |
+
out = model(input_ids, labels=labels)
|
| 31 |
+
n_tok = labels.numel()
|
| 32 |
+
total_loss += out.loss.item() * n_tok
|
| 33 |
+
total_tokens += n_tok
|
| 34 |
+
n_batches += 1
|
| 35 |
+
mean_loss = total_loss / max(1, total_tokens)
|
| 36 |
+
ppl = math.exp(min(20.0, mean_loss)) # clamp to avoid overflow on garbage models
|
| 37 |
+
return EvalResult(loss=mean_loss, perplexity=ppl, tokens_evaluated=total_tokens)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@torch.no_grad()
|
| 41 |
+
def generate_samples(
|
| 42 |
+
model: Bangla30M,
|
| 43 |
+
tokenizer: Bangla30MTokenizer,
|
| 44 |
+
prompts: list[str],
|
| 45 |
+
max_new_tokens: int = 64,
|
| 46 |
+
temperature: float = 0.8,
|
| 47 |
+
top_k: int = 50,
|
| 48 |
+
device: str = "cpu",
|
| 49 |
+
) -> list[dict]:
|
| 50 |
+
model.eval()
|
| 51 |
+
results = []
|
| 52 |
+
for prompt in prompts:
|
| 53 |
+
ids = torch.tensor([[tokenizer.bos_token_id] + tokenizer.encode(prompt, add_special_tokens=False)], device=device)
|
| 54 |
+
out_ids = model.generate(
|
| 55 |
+
ids, max_new_tokens=max_new_tokens, temperature=temperature,
|
| 56 |
+
top_k=top_k, eos_token_id=tokenizer.eos_token_id,
|
| 57 |
+
)
|
| 58 |
+
text = tokenizer.decode(out_ids[0].tolist())
|
| 59 |
+
results.append({"prompt": prompt, "completion": text})
|
| 60 |
+
return results
|
bangla30m/bangla30m/model.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Bangla-30M architecture: decoder-only, pre-norm transformer.
|
| 3 |
+
|
| 4 |
+
RMSNorm -> Multi-head self-attention (RoPE, causal, SDPA/flash) -> residual
|
| 5 |
+
RMSNorm -> MLP (SwiGLU or GELU) -> residual
|
| 6 |
+
|
| 7 |
+
Tied input/output embeddings. No positional embedding table (RoPE only).
|
| 8 |
+
No attention/MLP biases by default (standard for RMSNorm-based stacks).
|
| 9 |
+
|
| 10 |
+
Uses `torch.nn.functional.scaled_dot_product_attention`, which dispatches to
|
| 11 |
+
the fused flash-attention / memory-efficient kernels automatically on CUDA
|
| 12 |
+
when available, and to a correct math fallback on CPU (used here for tests).
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
from typing import Optional
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
import torch.nn as nn
|
| 22 |
+
import torch.nn.functional as F
|
| 23 |
+
|
| 24 |
+
from .config import ModelConfig
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# ------------------------------------------------------------------------- #
|
| 28 |
+
# Norm
|
| 29 |
+
# ------------------------------------------------------------------------- #
|
| 30 |
+
class RMSNorm(nn.Module):
|
| 31 |
+
def __init__(self, dim: int, eps: float = 1e-5):
|
| 32 |
+
super().__init__()
|
| 33 |
+
self.eps = eps
|
| 34 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 35 |
+
|
| 36 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 37 |
+
dtype = x.dtype
|
| 38 |
+
x = x.float()
|
| 39 |
+
norm = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 40 |
+
return (norm.to(dtype)) * self.weight
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# ------------------------------------------------------------------------- #
|
| 44 |
+
# Rotary position embeddings
|
| 45 |
+
# ------------------------------------------------------------------------- #
|
| 46 |
+
class RotaryEmbedding(nn.Module):
|
| 47 |
+
"""Precomputes cos/sin caches up to max_seq_len and applies RoPE."""
|
| 48 |
+
|
| 49 |
+
def __init__(self, head_dim: int, max_seq_len: int, theta: float = 10_000.0):
|
| 50 |
+
super().__init__()
|
| 51 |
+
assert head_dim % 2 == 0, "RoPE requires an even head_dim"
|
| 52 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim))
|
| 53 |
+
t = torch.arange(max_seq_len, dtype=torch.float32)
|
| 54 |
+
freqs = torch.outer(t, inv_freq) # [seq, head_dim/2]
|
| 55 |
+
emb = torch.cat([freqs, freqs], dim=-1) # [seq, head_dim]
|
| 56 |
+
self.register_buffer("cos_cached", emb.cos(), persistent=False)
|
| 57 |
+
self.register_buffer("sin_cached", emb.sin(), persistent=False)
|
| 58 |
+
|
| 59 |
+
def forward(self, seq_len: int, device, dtype):
|
| 60 |
+
return (
|
| 61 |
+
self.cos_cached[:seq_len].to(device=device, dtype=dtype),
|
| 62 |
+
self.sin_cached[:seq_len].to(device=device, dtype=dtype),
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _rotate_half(x: torch.Tensor) -> torch.Tensor:
|
| 67 |
+
x1, x2 = x.chunk(2, dim=-1)
|
| 68 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def apply_rotary_pos_emb(q, k, cos, sin):
|
| 72 |
+
# q, k: [batch, heads, seq, head_dim]; cos/sin: [seq, head_dim]
|
| 73 |
+
cos = cos[None, None, :, :]
|
| 74 |
+
sin = sin[None, None, :, :]
|
| 75 |
+
q_rot = (q * cos) + (_rotate_half(q) * sin)
|
| 76 |
+
k_rot = (k * cos) + (_rotate_half(k) * sin)
|
| 77 |
+
return q_rot, k_rot
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# ------------------------------------------------------------------------- #
|
| 81 |
+
# Attention
|
| 82 |
+
# ------------------------------------------------------------------------- #
|
| 83 |
+
class CausalSelfAttention(nn.Module):
|
| 84 |
+
def __init__(self, cfg: ModelConfig):
|
| 85 |
+
super().__init__()
|
| 86 |
+
self.n_heads = cfg.num_heads
|
| 87 |
+
self.head_dim = cfg.head_dim
|
| 88 |
+
self.hidden_size = cfg.hidden_size
|
| 89 |
+
self.dropout_p = cfg.dropout
|
| 90 |
+
|
| 91 |
+
self.q_proj = nn.Linear(cfg.hidden_size, cfg.hidden_size, bias=cfg.attn_bias)
|
| 92 |
+
self.k_proj = nn.Linear(cfg.hidden_size, cfg.hidden_size, bias=cfg.attn_bias)
|
| 93 |
+
self.v_proj = nn.Linear(cfg.hidden_size, cfg.hidden_size, bias=cfg.attn_bias)
|
| 94 |
+
self.o_proj = nn.Linear(cfg.hidden_size, cfg.hidden_size, bias=cfg.attn_bias)
|
| 95 |
+
|
| 96 |
+
self.rope = RotaryEmbedding(self.head_dim, cfg.max_seq_len, cfg.rope_theta)
|
| 97 |
+
|
| 98 |
+
def forward(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
|
| 99 |
+
B, T, C = x.shape
|
| 100 |
+
q = self.q_proj(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
|
| 101 |
+
k = self.k_proj(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
|
| 102 |
+
v = self.v_proj(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
|
| 103 |
+
|
| 104 |
+
cos, sin = self.rope(T, x.device, x.dtype)
|
| 105 |
+
q, k = apply_rotary_pos_emb(q, k, cos, sin)
|
| 106 |
+
|
| 107 |
+
# SDPA dispatches to flash / mem-efficient kernels on CUDA automatically.
|
| 108 |
+
out = F.scaled_dot_product_attention(
|
| 109 |
+
q, k, v,
|
| 110 |
+
attn_mask=attn_mask, # None -> use is_causal fast path
|
| 111 |
+
dropout_p=self.dropout_p if self.training else 0.0,
|
| 112 |
+
is_causal=attn_mask is None,
|
| 113 |
+
)
|
| 114 |
+
out = out.transpose(1, 2).contiguous().view(B, T, C)
|
| 115 |
+
return self.o_proj(out)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
# ------------------------------------------------------------------------- #
|
| 119 |
+
# MLP
|
| 120 |
+
# ------------------------------------------------------------------------- #
|
| 121 |
+
class SwiGLU(nn.Module):
|
| 122 |
+
def __init__(self, cfg: ModelConfig):
|
| 123 |
+
super().__init__()
|
| 124 |
+
self.gate_proj = nn.Linear(cfg.hidden_size, cfg.ffn_size, bias=False)
|
| 125 |
+
self.up_proj = nn.Linear(cfg.hidden_size, cfg.ffn_size, bias=False)
|
| 126 |
+
self.down_proj = nn.Linear(cfg.ffn_size, cfg.hidden_size, bias=False)
|
| 127 |
+
self.dropout = nn.Dropout(cfg.dropout)
|
| 128 |
+
|
| 129 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 130 |
+
return self.dropout(self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x)))
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class GELUMLp(nn.Module):
|
| 134 |
+
def __init__(self, cfg: ModelConfig):
|
| 135 |
+
super().__init__()
|
| 136 |
+
self.up_proj = nn.Linear(cfg.hidden_size, cfg.ffn_size, bias=False)
|
| 137 |
+
self.down_proj = nn.Linear(cfg.ffn_size, cfg.hidden_size, bias=False)
|
| 138 |
+
self.act = nn.GELU()
|
| 139 |
+
self.dropout = nn.Dropout(cfg.dropout)
|
| 140 |
+
|
| 141 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 142 |
+
return self.dropout(self.down_proj(self.act(self.up_proj(x))))
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def build_mlp(cfg: ModelConfig) -> nn.Module:
|
| 146 |
+
return SwiGLU(cfg) if cfg.activation == "swiglu" else GELUMLp(cfg)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# ------------------------------------------------------------------------- #
|
| 150 |
+
# Decoder block
|
| 151 |
+
# ------------------------------------------------------------------------- #
|
| 152 |
+
class DecoderBlock(nn.Module):
|
| 153 |
+
def __init__(self, cfg: ModelConfig):
|
| 154 |
+
super().__init__()
|
| 155 |
+
self.attn_norm = RMSNorm(cfg.hidden_size, cfg.norm_eps)
|
| 156 |
+
self.attn = CausalSelfAttention(cfg)
|
| 157 |
+
self.mlp_norm = RMSNorm(cfg.hidden_size, cfg.norm_eps)
|
| 158 |
+
self.mlp = build_mlp(cfg)
|
| 159 |
+
|
| 160 |
+
def forward(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
|
| 161 |
+
x = x + self.attn(self.attn_norm(x), attn_mask)
|
| 162 |
+
x = x + self.mlp(self.mlp_norm(x))
|
| 163 |
+
return x
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
# ------------------------------------------------------------------------- #
|
| 167 |
+
# Full model
|
| 168 |
+
# ------------------------------------------------------------------------- #
|
| 169 |
+
@dataclass
|
| 170 |
+
class Bangla30MOutput:
|
| 171 |
+
logits: torch.Tensor
|
| 172 |
+
loss: Optional[torch.Tensor] = None
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
class Bangla30M(nn.Module):
|
| 176 |
+
def __init__(self, cfg: ModelConfig):
|
| 177 |
+
super().__init__()
|
| 178 |
+
self.cfg = cfg
|
| 179 |
+
self.embed_tokens = nn.Embedding(cfg.vocab_size, cfg.hidden_size)
|
| 180 |
+
self.layers = nn.ModuleList([DecoderBlock(cfg) for _ in range(cfg.num_layers)])
|
| 181 |
+
self.final_norm = RMSNorm(cfg.hidden_size, cfg.norm_eps)
|
| 182 |
+
|
| 183 |
+
if cfg.tie_embeddings:
|
| 184 |
+
self.lm_head = None
|
| 185 |
+
else:
|
| 186 |
+
self.lm_head = nn.Linear(cfg.hidden_size, cfg.vocab_size, bias=False)
|
| 187 |
+
|
| 188 |
+
self.gradient_checkpointing = False
|
| 189 |
+
self.apply(self._init_weights)
|
| 190 |
+
self._scale_residual_projections()
|
| 191 |
+
|
| 192 |
+
# ---- init -----------------------------------------------------------
|
| 193 |
+
def _init_weights(self, module: nn.Module) -> None:
|
| 194 |
+
if isinstance(module, nn.Linear):
|
| 195 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 196 |
+
if module.bias is not None:
|
| 197 |
+
nn.init.zeros_(module.bias)
|
| 198 |
+
elif isinstance(module, nn.Embedding):
|
| 199 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 200 |
+
|
| 201 |
+
def _scale_residual_projections(self) -> None:
|
| 202 |
+
# GPT-2 style: scale down projections that feed directly into the
|
| 203 |
+
# residual stream, by 1/sqrt(2*num_layers), for training stability.
|
| 204 |
+
scale = 1.0 / math.sqrt(2 * self.cfg.num_layers)
|
| 205 |
+
for layer in self.layers:
|
| 206 |
+
with torch.no_grad():
|
| 207 |
+
layer.attn.o_proj.weight.mul_(scale)
|
| 208 |
+
layer.mlp.down_proj.weight.mul_(scale)
|
| 209 |
+
|
| 210 |
+
def enable_gradient_checkpointing(self, enabled: bool = True) -> None:
|
| 211 |
+
self.gradient_checkpointing = enabled
|
| 212 |
+
|
| 213 |
+
# ---- forward ----------------------------------------------------------
|
| 214 |
+
def forward(self, input_ids: torch.Tensor, labels: Optional[torch.Tensor] = None) -> Bangla30MOutput:
|
| 215 |
+
x = self.embed_tokens(input_ids)
|
| 216 |
+
for layer in self.layers:
|
| 217 |
+
if self.gradient_checkpointing and self.training:
|
| 218 |
+
x = torch.utils.checkpoint.checkpoint(layer, x, None, use_reentrant=False)
|
| 219 |
+
else:
|
| 220 |
+
x = layer(x)
|
| 221 |
+
x = self.final_norm(x)
|
| 222 |
+
|
| 223 |
+
head_weight = self.embed_tokens.weight if self.cfg.tie_embeddings else self.lm_head.weight
|
| 224 |
+
logits = F.linear(x, head_weight)
|
| 225 |
+
|
| 226 |
+
loss = None
|
| 227 |
+
if labels is not None:
|
| 228 |
+
loss = F.cross_entropy(
|
| 229 |
+
logits.view(-1, logits.size(-1)),
|
| 230 |
+
labels.view(-1),
|
| 231 |
+
ignore_index=self.cfg.pad_token_id,
|
| 232 |
+
)
|
| 233 |
+
return Bangla30MOutput(logits=logits, loss=loss)
|
| 234 |
+
|
| 235 |
+
@torch.no_grad()
|
| 236 |
+
def generate(
|
| 237 |
+
self,
|
| 238 |
+
input_ids: torch.Tensor,
|
| 239 |
+
max_new_tokens: int = 64,
|
| 240 |
+
temperature: float = 0.8,
|
| 241 |
+
top_k: int = 50,
|
| 242 |
+
eos_token_id: Optional[int] = None,
|
| 243 |
+
) -> torch.Tensor:
|
| 244 |
+
self.eval()
|
| 245 |
+
eos_token_id = self.cfg.eos_token_id if eos_token_id is None else eos_token_id
|
| 246 |
+
for _ in range(max_new_tokens):
|
| 247 |
+
ctx = input_ids[:, -self.cfg.max_seq_len:]
|
| 248 |
+
logits = self.forward(ctx).logits[:, -1, :] / max(temperature, 1e-6)
|
| 249 |
+
if top_k:
|
| 250 |
+
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
|
| 251 |
+
logits[logits < v[:, [-1]]] = -float("inf")
|
| 252 |
+
probs = F.softmax(logits, dim=-1)
|
| 253 |
+
next_token = torch.multinomial(probs, num_samples=1)
|
| 254 |
+
input_ids = torch.cat([input_ids, next_token], dim=1)
|
| 255 |
+
if eos_token_id is not None and bool((next_token == eos_token_id).all()):
|
| 256 |
+
break
|
| 257 |
+
return input_ids
|
| 258 |
+
|
| 259 |
+
# ---- accounting ---------------------------------------------------------
|
| 260 |
+
def num_parameters(self, trainable_only: bool = True) -> int:
|
| 261 |
+
params = (p for p in self.parameters() if (p.requires_grad or not trainable_only))
|
| 262 |
+
return sum(p.numel() for p in params)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def build_model(cfg: ModelConfig) -> Bangla30M:
|
| 266 |
+
return Bangla30M(cfg)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
if __name__ == "__main__":
|
| 270 |
+
cfg = ModelConfig()
|
| 271 |
+
model = build_model(cfg)
|
| 272 |
+
analytic = cfg.count_parameters()["total"]
|
| 273 |
+
actual = model.num_parameters()
|
| 274 |
+
print(f"analytic params : {analytic:,}")
|
| 275 |
+
print(f"actual params : {actual:,}")
|
| 276 |
+
assert analytic == actual, "analytic and actual parameter counts diverged"
|
| 277 |
+
x = torch.randint(0, cfg.vocab_size, (2, 32))
|
| 278 |
+
out = model(x, labels=x)
|
| 279 |
+
print("logits:", out.logits.shape, "loss:", out.loss.item())
|
bangla30m/bangla30m/optim.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Optimizer + LR schedule: AdamW with cosine decay and linear warmup."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import math
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch.optim import AdamW
|
| 8 |
+
from torch.optim.lr_scheduler import LambdaLR
|
| 9 |
+
|
| 10 |
+
from .config import TrainConfig
|
| 11 |
+
from .model import Bangla30M
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def build_optimizer(model: Bangla30M, cfg: TrainConfig) -> AdamW:
|
| 15 |
+
"""Standard GPT-style param grouping: no weight decay on norms/biases/embeddings."""
|
| 16 |
+
decay, no_decay = [], []
|
| 17 |
+
for name, p in model.named_parameters():
|
| 18 |
+
if not p.requires_grad:
|
| 19 |
+
continue
|
| 20 |
+
if p.ndim < 2 or "norm" in name.lower() or "embed_tokens" in name.lower():
|
| 21 |
+
no_decay.append(p)
|
| 22 |
+
else:
|
| 23 |
+
decay.append(p)
|
| 24 |
+
groups = [
|
| 25 |
+
{"params": decay, "weight_decay": cfg.weight_decay},
|
| 26 |
+
{"params": no_decay, "weight_decay": 0.0},
|
| 27 |
+
]
|
| 28 |
+
return AdamW(
|
| 29 |
+
groups,
|
| 30 |
+
lr=cfg.learning_rate,
|
| 31 |
+
betas=(cfg.adam_beta1, cfg.adam_beta2),
|
| 32 |
+
eps=cfg.adam_eps,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def build_scheduler(optimizer: AdamW, cfg: TrainConfig, total_steps: int) -> LambdaLR:
|
| 37 |
+
warmup_steps = max(1, int(total_steps * cfg.warmup_ratio))
|
| 38 |
+
min_ratio = cfg.min_learning_rate_ratio
|
| 39 |
+
|
| 40 |
+
def lr_lambda(step: int) -> float:
|
| 41 |
+
if step < warmup_steps:
|
| 42 |
+
return (step + 1) / warmup_steps
|
| 43 |
+
progress = (step - warmup_steps) / max(1, total_steps - warmup_steps)
|
| 44 |
+
progress = min(progress, 1.0)
|
| 45 |
+
cosine = 0.5 * (1.0 + math.cos(math.pi * progress))
|
| 46 |
+
return min_ratio + (1.0 - min_ratio) * cosine
|
| 47 |
+
|
| 48 |
+
return LambdaLR(optimizer, lr_lambda)
|
bangla30m/bangla30m/tokenizer.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
BPE tokenizer for Bangla-30M.
|
| 3 |
+
|
| 4 |
+
Per the plan: train on a representative sample (~10-30M tokens' worth of
|
| 5 |
+
text, not the full 4.32B-token corpus), then freeze it for the 700M-token
|
| 6 |
+
pretraining run.
|
| 7 |
+
|
| 8 |
+
Uses the Rust `tokenizers` library directly (byte-level BPE, same family as
|
| 9 |
+
GPT-2/RoBERTa) and saves a single tokenizer.json plus a small tokenizer_config
|
| 10 |
+
so it can be reloaded standalone (no dependency on `transformers`).
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import json
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Iterable, Iterator, Optional
|
| 17 |
+
|
| 18 |
+
from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers, processors
|
| 19 |
+
from tokenizers.models import BPE
|
| 20 |
+
from tokenizers.trainers import BpeTrainer
|
| 21 |
+
|
| 22 |
+
SPECIAL_TOKENS = ["<BOS>", "<EOS>", "<PAD>", "<UNK>"]
|
| 23 |
+
# fixed ids: keep in sync with ModelConfig defaults (bos=0, eos=1, pad=2, unk=3)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def build_raw_tokenizer() -> Tokenizer:
|
| 27 |
+
tok = Tokenizer(BPE(unk_token="<UNK>"))
|
| 28 |
+
# NFC normalization: Bengali text frequently mixes composed/decomposed
|
| 29 |
+
# conjuncts; NFC keeps the vocabulary from fragmenting on that.
|
| 30 |
+
tok.normalizer = normalizers.NFC()
|
| 31 |
+
tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
|
| 32 |
+
tok.decoder = decoders.ByteLevel()
|
| 33 |
+
return tok
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def train_tokenizer(
|
| 37 |
+
text_iterator: Iterable[str],
|
| 38 |
+
vocab_size: int = 32_000,
|
| 39 |
+
save_dir: str | Path = "artifacts/tokenizer",
|
| 40 |
+
min_frequency: int = 2,
|
| 41 |
+
) -> Tokenizer:
|
| 42 |
+
tok = build_raw_tokenizer()
|
| 43 |
+
trainer = BpeTrainer(
|
| 44 |
+
vocab_size=vocab_size,
|
| 45 |
+
min_frequency=min_frequency,
|
| 46 |
+
special_tokens=SPECIAL_TOKENS,
|
| 47 |
+
show_progress=True,
|
| 48 |
+
)
|
| 49 |
+
tok.train_from_iterator(text_iterator, trainer=trainer)
|
| 50 |
+
|
| 51 |
+
bos_id = tok.token_to_id("<BOS>")
|
| 52 |
+
eos_id = tok.token_to_id("<EOS>")
|
| 53 |
+
tok.post_processor = processors.TemplateProcessing(
|
| 54 |
+
single="<BOS> $A <EOS>",
|
| 55 |
+
pair="<BOS> $A <EOS> <BOS> $B <EOS>",
|
| 56 |
+
special_tokens=[("<BOS>", bos_id), ("<EOS>", eos_id)],
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
save_dir = Path(save_dir)
|
| 60 |
+
save_dir.mkdir(parents=True, exist_ok=True)
|
| 61 |
+
tok.save(str(save_dir / "tokenizer.json"))
|
| 62 |
+
(save_dir / "tokenizer_config.json").write_text(json.dumps({
|
| 63 |
+
"vocab_size": vocab_size,
|
| 64 |
+
"bos_token": "<BOS>", "bos_token_id": bos_id,
|
| 65 |
+
"eos_token": "<EOS>", "eos_token_id": eos_id,
|
| 66 |
+
"pad_token": "<PAD>", "pad_token_id": tok.token_to_id("<PAD>"),
|
| 67 |
+
"unk_token": "<UNK>", "unk_token_id": tok.token_to_id("<UNK>"),
|
| 68 |
+
"model_max_length": 512,
|
| 69 |
+
}, indent=2, ensure_ascii=False))
|
| 70 |
+
return tok
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class Bangla30MTokenizer:
|
| 74 |
+
"""Thin, dependency-free wrapper around a trained `tokenizers.Tokenizer`."""
|
| 75 |
+
|
| 76 |
+
def __init__(self, tok: Tokenizer, config: dict):
|
| 77 |
+
self._tok = tok
|
| 78 |
+
self.config = config
|
| 79 |
+
self.bos_token_id = config["bos_token_id"]
|
| 80 |
+
self.eos_token_id = config["eos_token_id"]
|
| 81 |
+
self.pad_token_id = config["pad_token_id"]
|
| 82 |
+
self.unk_token_id = config["unk_token_id"]
|
| 83 |
+
self.vocab_size = self._tok.get_vocab_size()
|
| 84 |
+
|
| 85 |
+
@classmethod
|
| 86 |
+
def from_dir(cls, save_dir: str | Path) -> "Bangla30MTokenizer":
|
| 87 |
+
save_dir = Path(save_dir)
|
| 88 |
+
tok = Tokenizer.from_file(str(save_dir / "tokenizer.json"))
|
| 89 |
+
config = json.loads((save_dir / "tokenizer_config.json").read_text())
|
| 90 |
+
return cls(tok, config)
|
| 91 |
+
|
| 92 |
+
def encode(self, text: str, add_special_tokens: bool = True) -> list[int]:
|
| 93 |
+
enc = self._tok.encode(text)
|
| 94 |
+
ids = enc.ids
|
| 95 |
+
if not add_special_tokens:
|
| 96 |
+
# post-processor already added BOS/EOS; strip them if unwanted
|
| 97 |
+
ids = [i for i in ids if i not in (self.bos_token_id, self.eos_token_id)]
|
| 98 |
+
return ids
|
| 99 |
+
|
| 100 |
+
def encode_batch(self, texts: list[str]) -> list[list[int]]:
|
| 101 |
+
return [e.ids for e in self._tok.encode_batch(texts)]
|
| 102 |
+
|
| 103 |
+
def decode(self, ids: list[int], skip_special_tokens: bool = True) -> str:
|
| 104 |
+
return self._tok.decode(ids, skip_special_tokens=skip_special_tokens)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def iter_texts_for_tokenizer_training(
|
| 108 |
+
streaming_dataset,
|
| 109 |
+
text_column: str,
|
| 110 |
+
max_docs: int,
|
| 111 |
+
) -> Iterator[str]:
|
| 112 |
+
"""Pulls `max_docs` raw texts out of a (possibly streaming) HF dataset,
|
| 113 |
+
for tokenizer training. Kept separate from the pretraining data pipeline
|
| 114 |
+
since it needs plain strings, not packed token tensors.
|
| 115 |
+
"""
|
| 116 |
+
n = 0
|
| 117 |
+
for example in streaming_dataset:
|
| 118 |
+
text = example.get(text_column)
|
| 119 |
+
if text:
|
| 120 |
+
yield text
|
| 121 |
+
n += 1
|
| 122 |
+
if n >= max_docs:
|
| 123 |
+
return
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
if __name__ == "__main__":
|
| 127 |
+
# smoke test on a tiny local sample; see scripts/02_train_tokenizer.py for
|
| 128 |
+
# the real B-CORE-backed entrypoint.
|
| 129 |
+
sample = [
|
| 130 |
+
"আমি বাংলায় গান গাই।",
|
| 131 |
+
"বাংলাদেশ দক্ষিণ এশিয়ার একটি দেশ।",
|
| 132 |
+
"কৃত্রিম বুদ্ধিমত্তা নিয়ে গবেষণা চলছে।",
|
| 133 |
+
] * 50
|
| 134 |
+
tok = train_tokenizer(sample, vocab_size=500, save_dir="/tmp/bangla30m_tok_smoke")
|
| 135 |
+
wrapper = Bangla30MTokenizer.from_dir("/tmp/bangla30m_tok_smoke")
|
| 136 |
+
ids = wrapper.encode("আমি বাংলায় গান গাই।")
|
| 137 |
+
print("ids:", ids)
|
| 138 |
+
print("decoded:", wrapper.decode(ids))
|
bangla30m/bangla30m/trainer.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Training loop for Bangla-30M, built on `accelerate` so the same entry point
|
| 3 |
+
works both as `accelerate launch scripts/04_train.py` (CLI, e.g. via a
|
| 4 |
+
Kaggle "Run as script" cell) and via `accelerate.notebook_launcher(train, ...)`
|
| 5 |
+
from inside a Kaggle notebook cell (the more common Kaggle T4x2 pattern).
|
| 6 |
+
|
| 7 |
+
Design choices that map directly onto the plan:
|
| 8 |
+
- fp16 mixed precision, DDP across the 2 T4s (`Accelerator(mixed_precision=...)`)
|
| 9 |
+
- gradient_accumulation_steps configurable (plan recommends starting at 1
|
| 10 |
+
and only raising it if a single-GPU batch can't hit good throughput)
|
| 11 |
+
- gradient checkpointing OFF by default (plan: memory over speed is the
|
| 12 |
+
wrong trade for a 30M model on a 16GB T4)
|
| 13 |
+
- deterministic token accounting (no extra collective ops in the hot loop):
|
| 14 |
+
tokens per optimizer step is fixed by (batch size x seq_len x grad_accum
|
| 15 |
+
x world_size), so tokens_seen is computed directly from step count
|
| 16 |
+
- checkpoints at 100M-token milestones (resumable, so a Kaggle session
|
| 17 |
+
limit never costs more than one interval)
|
| 18 |
+
"""
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import json
|
| 22 |
+
import time
|
| 23 |
+
from dataclasses import dataclass
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
from typing import Optional
|
| 26 |
+
|
| 27 |
+
import torch
|
| 28 |
+
from accelerate import Accelerator
|
| 29 |
+
from torch.utils.data import DataLoader
|
| 30 |
+
|
| 31 |
+
from . import checkpoint as ckpt
|
| 32 |
+
from .config import ModelConfig, TrainConfig
|
| 33 |
+
from .data import BCoreStreamingDataset, collate_fn
|
| 34 |
+
from .model import Bangla30M, build_model
|
| 35 |
+
from .optim import build_optimizer, build_scheduler
|
| 36 |
+
from .tokenizer import Bangla30MTokenizer
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@dataclass
|
| 40 |
+
class StepLog:
|
| 41 |
+
step: int
|
| 42 |
+
tokens_seen: int
|
| 43 |
+
loss: float
|
| 44 |
+
lr: float
|
| 45 |
+
tokens_per_sec: float
|
| 46 |
+
grad_norm: float
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _tokens_per_optimizer_step(train_cfg: TrainConfig, world_size: int) -> int:
|
| 50 |
+
return train_cfg.per_device_batch_size * train_cfg.seq_len * train_cfg.gradient_accumulation_steps * world_size
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def build_dataloader(
|
| 54 |
+
train_cfg: TrainConfig,
|
| 55 |
+
tokenizer: Bangla30MTokenizer,
|
| 56 |
+
rank: int,
|
| 57 |
+
world_size: int,
|
| 58 |
+
skip_examples: int = 0,
|
| 59 |
+
source_dataset=None,
|
| 60 |
+
) -> DataLoader:
|
| 61 |
+
dataset = BCoreStreamingDataset(
|
| 62 |
+
tokenizer=tokenizer,
|
| 63 |
+
seq_len=train_cfg.seq_len,
|
| 64 |
+
dataset_name=train_cfg.dataset_name,
|
| 65 |
+
dataset_split=train_cfg.dataset_split,
|
| 66 |
+
text_column=train_cfg.text_column,
|
| 67 |
+
# The trainer's own step counter (train_cfg.total_steps) is the
|
| 68 |
+
# authoritative stopping condition. The dataset's internal token cap
|
| 69 |
+
# is only a safety upper bound, so give it headroom -- otherwise
|
| 70 |
+
# DataLoader(drop_last=True) can discard a trailing partial batch
|
| 71 |
+
# right as the dataset's own cap is reached, stopping the run a
|
| 72 |
+
# fraction of a step short of total_steps. A 10% margin is trivial
|
| 73 |
+
# at the corpus's scale and simply prevents that race.
|
| 74 |
+
target_tokens=int(train_cfg.target_tokens * 1.10),
|
| 75 |
+
min_chars=train_cfg.min_chars,
|
| 76 |
+
max_repeat_char_run=train_cfg.max_repeat_char_run,
|
| 77 |
+
rank=rank,
|
| 78 |
+
world_size=world_size,
|
| 79 |
+
skip_examples=skip_examples,
|
| 80 |
+
source_dataset=source_dataset,
|
| 81 |
+
)
|
| 82 |
+
return DataLoader(
|
| 83 |
+
dataset,
|
| 84 |
+
batch_size=train_cfg.per_device_batch_size,
|
| 85 |
+
collate_fn=collate_fn,
|
| 86 |
+
num_workers=train_cfg.dataloader_workers,
|
| 87 |
+
drop_last=True,
|
| 88 |
+
pin_memory=torch.cuda.is_available(),
|
| 89 |
+
persistent_workers=train_cfg.dataloader_workers > 0,
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def run_training(
|
| 94 |
+
model_cfg: ModelConfig,
|
| 95 |
+
train_cfg: TrainConfig,
|
| 96 |
+
source_dataset=None, # override for tests / offline runs
|
| 97 |
+
max_steps_override: Optional[int] = None,
|
| 98 |
+
) -> dict:
|
| 99 |
+
accelerator = Accelerator(
|
| 100 |
+
mixed_precision=train_cfg.mixed_precision,
|
| 101 |
+
gradient_accumulation_steps=train_cfg.gradient_accumulation_steps,
|
| 102 |
+
)
|
| 103 |
+
torch.manual_seed(train_cfg.seed + accelerator.process_index)
|
| 104 |
+
|
| 105 |
+
output_dir = Path(train_cfg.output_dir)
|
| 106 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 107 |
+
|
| 108 |
+
tokenizer = Bangla30MTokenizer.from_dir(train_cfg.tokenizer_dir)
|
| 109 |
+
model_cfg.vocab_size = tokenizer.vocab_size
|
| 110 |
+
model_cfg.pad_token_id = tokenizer.pad_token_id
|
| 111 |
+
model_cfg.bos_token_id = tokenizer.bos_token_id
|
| 112 |
+
model_cfg.eos_token_id = tokenizer.eos_token_id
|
| 113 |
+
model_cfg.unk_token_id = tokenizer.unk_token_id
|
| 114 |
+
|
| 115 |
+
model = build_model(model_cfg)
|
| 116 |
+
if train_cfg.gradient_checkpointing:
|
| 117 |
+
model.enable_gradient_checkpointing(True)
|
| 118 |
+
|
| 119 |
+
if accelerator.is_main_process:
|
| 120 |
+
stats = model_cfg.count_parameters()
|
| 121 |
+
accelerator.print(
|
| 122 |
+
f"[bangla30m] {stats['total_millions']}M params "
|
| 123 |
+
f"(hidden={model_cfg.hidden_size}, layers={model_cfg.num_layers}, "
|
| 124 |
+
f"heads={model_cfg.num_heads}, ffn={model_cfg.ffn_size}, "
|
| 125 |
+
f"activation={model_cfg.activation})"
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
world_size = accelerator.num_processes
|
| 129 |
+
tokens_per_step = _tokens_per_optimizer_step(train_cfg, world_size)
|
| 130 |
+
total_steps = max_steps_override or train_cfg.total_steps(world_size)
|
| 131 |
+
|
| 132 |
+
optimizer = build_optimizer(model, train_cfg)
|
| 133 |
+
scheduler = build_scheduler(optimizer, train_cfg, total_steps)
|
| 134 |
+
|
| 135 |
+
start_step, start_tokens = 0, 0
|
| 136 |
+
resume_info = ckpt.find_latest_checkpoint(output_dir) if train_cfg.resume_from_checkpoint else None
|
| 137 |
+
skip_examples = 0
|
| 138 |
+
if resume_info:
|
| 139 |
+
skip_examples = resume_info.get("docs_seen", 0)
|
| 140 |
+
|
| 141 |
+
dataloader = build_dataloader(
|
| 142 |
+
train_cfg, tokenizer, accelerator.process_index, world_size,
|
| 143 |
+
skip_examples=skip_examples, source_dataset=source_dataset,
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
model, optimizer, dataloader, scheduler = accelerator.prepare(model, optimizer, dataloader, scheduler)
|
| 147 |
+
|
| 148 |
+
if resume_info:
|
| 149 |
+
ckpt.load_checkpoint(accelerator, resume_info["path"])
|
| 150 |
+
start_step = resume_info.get("step", 0)
|
| 151 |
+
start_tokens = resume_info.get("tokens_seen", 0)
|
| 152 |
+
accelerator.print(f"[bangla30m] resumed from {resume_info['path']} "
|
| 153 |
+
f"(step={start_step}, tokens_seen={start_tokens:,})")
|
| 154 |
+
|
| 155 |
+
model.train()
|
| 156 |
+
step = start_step
|
| 157 |
+
tokens_seen = start_tokens
|
| 158 |
+
next_ckpt_at = ((tokens_seen // train_cfg.checkpoint_every_tokens) + 1) * train_cfg.checkpoint_every_tokens
|
| 159 |
+
|
| 160 |
+
window_tokens, window_start_t = 0, time.time()
|
| 161 |
+
history: list[StepLog] = []
|
| 162 |
+
|
| 163 |
+
data_iter = iter(dataloader)
|
| 164 |
+
while step < total_steps and tokens_seen < train_cfg.target_tokens:
|
| 165 |
+
with accelerator.accumulate(model):
|
| 166 |
+
try:
|
| 167 |
+
batch = next(data_iter)
|
| 168 |
+
except StopIteration:
|
| 169 |
+
accelerator.print("[bangla30m] data stream exhausted before target_tokens reached")
|
| 170 |
+
break
|
| 171 |
+
out = model(batch["input_ids"], labels=batch["labels"])
|
| 172 |
+
loss = out.loss
|
| 173 |
+
accelerator.backward(loss)
|
| 174 |
+
grad_norm = torch.tensor(0.0)
|
| 175 |
+
if accelerator.sync_gradients:
|
| 176 |
+
grad_norm = accelerator.clip_grad_norm_(model.parameters(), train_cfg.grad_clip)
|
| 177 |
+
optimizer.step()
|
| 178 |
+
scheduler.step()
|
| 179 |
+
optimizer.zero_grad()
|
| 180 |
+
|
| 181 |
+
if accelerator.sync_gradients:
|
| 182 |
+
step += 1
|
| 183 |
+
tokens_seen = start_tokens + (step - start_step) * tokens_per_step
|
| 184 |
+
window_tokens += tokens_per_step
|
| 185 |
+
|
| 186 |
+
if step % train_cfg.log_every_steps == 0:
|
| 187 |
+
elapsed = max(1e-6, time.time() - window_start_t)
|
| 188 |
+
tok_per_sec = window_tokens / elapsed
|
| 189 |
+
logged_loss = accelerator.gather(loss.detach()).mean().item()
|
| 190 |
+
log = StepLog(
|
| 191 |
+
step=step, tokens_seen=tokens_seen, loss=logged_loss,
|
| 192 |
+
lr=scheduler.get_last_lr()[0], tokens_per_sec=tok_per_sec,
|
| 193 |
+
grad_norm=float(grad_norm),
|
| 194 |
+
)
|
| 195 |
+
history.append(log)
|
| 196 |
+
if accelerator.is_main_process:
|
| 197 |
+
accelerator.print(
|
| 198 |
+
f"step {log.step:>6} | tokens {log.tokens_seen:>12,} | "
|
| 199 |
+
f"loss {log.loss:6.3f} | lr {log.lr:.2e} | "
|
| 200 |
+
f"{log.tokens_per_sec/1000:6.1f}K tok/s | grad_norm {log.grad_norm:5.2f}"
|
| 201 |
+
)
|
| 202 |
+
window_tokens, window_start_t = 0, time.time()
|
| 203 |
+
|
| 204 |
+
if tokens_seen >= next_ckpt_at:
|
| 205 |
+
dataset_obj = dataloader.dataset if hasattr(dataloader, "dataset") else None
|
| 206 |
+
docs_seen = getattr(getattr(dataset_obj, "stats", None), "docs_seen", 0)
|
| 207 |
+
ckpt.save_checkpoint(
|
| 208 |
+
accelerator, output_dir, tokens_seen, step,
|
| 209 |
+
extra={"docs_seen": docs_seen},
|
| 210 |
+
)
|
| 211 |
+
if accelerator.is_main_process:
|
| 212 |
+
ckpt.prune_old_checkpoints(output_dir, keep_last=3)
|
| 213 |
+
accelerator.print(f"[bangla30m] checkpoint saved at {tokens_seen:,} tokens")
|
| 214 |
+
next_ckpt_at += train_cfg.checkpoint_every_tokens
|
| 215 |
+
|
| 216 |
+
# final checkpoint
|
| 217 |
+
final_docs_seen = getattr(getattr(dataloader.dataset, "stats", None), "docs_seen", 0)
|
| 218 |
+
ckpt.save_checkpoint(accelerator, output_dir, tokens_seen, step, extra={"docs_seen": final_docs_seen, "final": True})
|
| 219 |
+
if accelerator.is_main_process:
|
| 220 |
+
(output_dir / "train_log.json").write_text(
|
| 221 |
+
json.dumps([vars(h) for h in history], indent=2)
|
| 222 |
+
)
|
| 223 |
+
accelerator.print(f"[bangla30m] training complete: {tokens_seen:,} tokens, {step} steps")
|
| 224 |
+
|
| 225 |
+
return {"final_step": step, "final_tokens": tokens_seen, "history": history}
|
bangla30m/notebooks/Bangla30M_Kaggle.ipynb
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"# Bangla-30M — 700M tokens on Kaggle 2x T4\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"Settings -> Accelerator -> **GPU T4 x2**, internet **ON**, before running this notebook.\n",
|
| 10 |
+
"\n",
|
| 11 |
+
"Upload/extract the `bangla30m` project folder to `/kaggle/working/bangla30m` first (or `!git clone` / `!unzip` it in the cell below)."
|
| 12 |
+
]
|
| 13 |
+
},
|
| 14 |
+
{
|
| 15 |
+
"cell_type": "code",
|
| 16 |
+
"execution_count": null,
|
| 17 |
+
"metadata": {},
|
| 18 |
+
"outputs": [],
|
| 19 |
+
"source": [
|
| 20 |
+
"import sys\n",
|
| 21 |
+
"sys.path.insert(0, \"/kaggle/working/bangla30m\")"
|
| 22 |
+
]
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"cell_type": "markdown",
|
| 26 |
+
"metadata": {},
|
| 27 |
+
"source": ["## Stage 1 — environment check"]
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"cell_type": "code",
|
| 31 |
+
"execution_count": null,
|
| 32 |
+
"metadata": {},
|
| 33 |
+
"outputs": [],
|
| 34 |
+
"source": [
|
| 35 |
+
"!python /kaggle/working/bangla30m/scripts/01_install.py"
|
| 36 |
+
]
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"cell_type": "markdown",
|
| 40 |
+
"metadata": {},
|
| 41 |
+
"source": [
|
| 42 |
+
"## Stage 2 — train the 32K BPE tokenizer\n",
|
| 43 |
+
"Streams a representative sample from B-CORE (does **not** download the full 20.8GB corpus)."
|
| 44 |
+
]
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
"cell_type": "code",
|
| 48 |
+
"execution_count": null,
|
| 49 |
+
"metadata": {},
|
| 50 |
+
"outputs": [],
|
| 51 |
+
"source": [
|
| 52 |
+
"!python /kaggle/working/bangla30m/scripts/02_train_tokenizer.py \\\n",
|
| 53 |
+
" --out /kaggle/working/artifacts/tokenizer \\\n",
|
| 54 |
+
" --max-docs 200000 \\\n",
|
| 55 |
+
" --vocab-size 32000"
|
| 56 |
+
]
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"cell_type": "markdown",
|
| 60 |
+
"metadata": {},
|
| 61 |
+
"source": [
|
| 62 |
+
"## Stage 3 — speed test (run this before committing to the full job)\n",
|
| 63 |
+
"7-8h is a *target*, not a guarantee — it depends on this session's actual streaming + tokenization throughput. This benchmarks ~10M tokens on both T4s and extrapolates."
|
| 64 |
+
]
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"cell_type": "code",
|
| 68 |
+
"execution_count": null,
|
| 69 |
+
"metadata": {},
|
| 70 |
+
"outputs": [],
|
| 71 |
+
"source": [
|
| 72 |
+
"from accelerate import notebook_launcher\n",
|
| 73 |
+
"from bangla30m.benchmark import run_speed_test\n",
|
| 74 |
+
"from bangla30m.config import ModelConfig, TrainConfig\n",
|
| 75 |
+
"\n",
|
| 76 |
+
"model_cfg = ModelConfig() # ~31.75M params — see bangla30m/config.py\n",
|
| 77 |
+
"train_cfg = TrainConfig(tokenizer_dir=\"/kaggle/working/artifacts/tokenizer\")\n",
|
| 78 |
+
"\n",
|
| 79 |
+
"notebook_launcher(\n",
|
| 80 |
+
" run_speed_test,\n",
|
| 81 |
+
" args=(model_cfg, train_cfg, 10_000_000),\n",
|
| 82 |
+
" num_processes=2,\n",
|
| 83 |
+
")"
|
| 84 |
+
]
|
| 85 |
+
},
|
| 86 |
+
{
|
| 87 |
+
"cell_type": "markdown",
|
| 88 |
+
"metadata": {},
|
| 89 |
+
"source": [
|
| 90 |
+
"## Stage 4 — the full 700M-token run\n",
|
| 91 |
+
"Re-running this cell after a Kaggle session gets cut off resumes automatically from the latest 100M-token checkpoint under `output_dir`."
|
| 92 |
+
]
|
| 93 |
+
},
|
| 94 |
+
{
|
| 95 |
+
"cell_type": "code",
|
| 96 |
+
"execution_count": null,
|
| 97 |
+
"metadata": {},
|
| 98 |
+
"outputs": [],
|
| 99 |
+
"source": [
|
| 100 |
+
"from accelerate import notebook_launcher\n",
|
| 101 |
+
"from bangla30m.config import ModelConfig, TrainConfig\n",
|
| 102 |
+
"from bangla30m.trainer import run_training\n",
|
| 103 |
+
"\n",
|
| 104 |
+
"model_cfg = ModelConfig()\n",
|
| 105 |
+
"train_cfg = TrainConfig(\n",
|
| 106 |
+
" tokenizer_dir=\"/kaggle/working/artifacts/tokenizer\",\n",
|
| 107 |
+
" output_dir=\"/kaggle/working/artifacts/runs/bangla30m\",\n",
|
| 108 |
+
" target_tokens=700_000_000,\n",
|
| 109 |
+
" per_device_batch_size=32,\n",
|
| 110 |
+
" gradient_accumulation_steps=2, # ~65.5K effective tokens/step across 2xT4\n",
|
| 111 |
+
" checkpoint_every_tokens=100_000_000,\n",
|
| 112 |
+
")\n",
|
| 113 |
+
"\n",
|
| 114 |
+
"notebook_launcher(run_training, args=(model_cfg, train_cfg), num_processes=2)"
|
| 115 |
+
]
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
"cell_type": "markdown",
|
| 119 |
+
"metadata": {},
|
| 120 |
+
"source": ["## Stage 5 — evaluate the final checkpoint"]
|
| 121 |
+
},
|
| 122 |
+
{
|
| 123 |
+
"cell_type": "code",
|
| 124 |
+
"execution_count": null,
|
| 125 |
+
"metadata": {},
|
| 126 |
+
"outputs": [],
|
| 127 |
+
"source": [
|
| 128 |
+
"!python /kaggle/working/bangla30m/scripts/05_evaluate.py \\\n",
|
| 129 |
+
" --checkpoint /kaggle/working/artifacts/runs/bangla30m/checkpoints/tokens_000700000000 \\\n",
|
| 130 |
+
" --tokenizer-dir /kaggle/working/artifacts/tokenizer"
|
| 131 |
+
]
|
| 132 |
+
}
|
| 133 |
+
],
|
| 134 |
+
"metadata": {
|
| 135 |
+
"kernelspec": {
|
| 136 |
+
"display_name": "Python 3",
|
| 137 |
+
"language": "python",
|
| 138 |
+
"name": "python3"
|
| 139 |
+
},
|
| 140 |
+
"language_info": {
|
| 141 |
+
"name": "python",
|
| 142 |
+
"version": "3.10"
|
| 143 |
+
}
|
| 144 |
+
},
|
| 145 |
+
"nbformat": 4,
|
| 146 |
+
"nbformat_minor": 5
|
| 147 |
+
}
|
bangla30m/pytest.ini
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[pytest]
|
| 2 |
+
testpaths = tests
|
| 3 |
+
python_files = test_*.py
|
bangla30m/requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch>=2.2
|
| 2 |
+
accelerate>=0.30
|
| 3 |
+
datasets>=2.19
|
| 4 |
+
tokenizers>=0.19
|
| 5 |
+
pytest>=7.0
|
bangla30m/scripts/01_install.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
01_install.py — environment setup / sanity check for Kaggle T4x2.
|
| 4 |
+
|
| 5 |
+
Run first in a Kaggle notebook cell:
|
| 6 |
+
!python scripts/01_install.py
|
| 7 |
+
"""
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
REQUIREMENTS = [
|
| 13 |
+
"torch>=2.2",
|
| 14 |
+
"accelerate>=0.30",
|
| 15 |
+
"datasets>=2.19",
|
| 16 |
+
"tokenizers>=0.19",
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def pip_install(packages: list[str]) -> None:
|
| 21 |
+
subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", *packages])
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def main() -> None:
|
| 25 |
+
print("Installing/upgrading requirements...")
|
| 26 |
+
pip_install(REQUIREMENTS)
|
| 27 |
+
|
| 28 |
+
import torch
|
| 29 |
+
print(f"\ntorch {torch.__version__}")
|
| 30 |
+
print(f"CUDA available: {torch.cuda.is_available()}")
|
| 31 |
+
if torch.cuda.is_available():
|
| 32 |
+
n = torch.cuda.device_count()
|
| 33 |
+
print(f"GPU count: {n}")
|
| 34 |
+
for i in range(n):
|
| 35 |
+
props = torch.cuda.get_device_properties(i)
|
| 36 |
+
print(f" [{i}] {props.name} — {props.total_memory / 1e9:.1f} GB")
|
| 37 |
+
if n < 2:
|
| 38 |
+
print("WARNING: plan assumes Kaggle T4 x2. Only "
|
| 39 |
+
f"{n} GPU visible — check the notebook's accelerator setting.")
|
| 40 |
+
else:
|
| 41 |
+
print("WARNING: no CUDA device visible. Training will fall back to CPU "
|
| 42 |
+
"(fine for the unit tests in tests/, not for a real 700M-token run).")
|
| 43 |
+
|
| 44 |
+
import accelerate, datasets, tokenizers
|
| 45 |
+
print(f"\naccelerate {accelerate.__version__}")
|
| 46 |
+
print(f"datasets {datasets.__version__}")
|
| 47 |
+
print(f"tokenizers {tokenizers.__version__}")
|
| 48 |
+
print("\nEnvironment OK.")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
if __name__ == "__main__":
|
| 52 |
+
main()
|
bangla30m/scripts/02_train_tokenizer.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
02_train_tokenizer.py — train the 32K BPE tokenizer on a representative
|
| 4 |
+
sample of B-CORE (not the full 4.32B-token corpus — the plan calls for
|
| 5 |
+
~10-30M tokens' worth of representative text).
|
| 6 |
+
|
| 7 |
+
Usage:
|
| 8 |
+
python scripts/02_train_tokenizer.py \
|
| 9 |
+
--dataset nahid-hub/B-CORE-bengali-corpus \
|
| 10 |
+
--max-docs 20000000 \
|
| 11 |
+
--vocab-size 32000 \
|
| 12 |
+
--out artifacts/tokenizer
|
| 13 |
+
"""
|
| 14 |
+
import argparse
|
| 15 |
+
import sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 19 |
+
|
| 20 |
+
from bangla30m.tokenizer import iter_texts_for_tokenizer_training, train_tokenizer
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def main() -> None:
|
| 24 |
+
p = argparse.ArgumentParser()
|
| 25 |
+
p.add_argument("--dataset", default="nahid-hub/B-CORE-bengali-corpus")
|
| 26 |
+
p.add_argument("--split", default="train")
|
| 27 |
+
p.add_argument("--text-column", default="text")
|
| 28 |
+
p.add_argument("--max-docs", type=int, default=200_000,
|
| 29 |
+
help="Number of *documents* sampled for tokenizer training "
|
| 30 |
+
"(the plan targets ~10-30M tokens' worth of text — "
|
| 31 |
+
"a few hundred thousand short/medium docs is plenty; "
|
| 32 |
+
"raise this if your corpus has very short documents).")
|
| 33 |
+
p.add_argument("--vocab-size", type=int, default=32_000)
|
| 34 |
+
p.add_argument("--out", default="artifacts/tokenizer")
|
| 35 |
+
args = p.parse_args()
|
| 36 |
+
|
| 37 |
+
import datasets as hf_datasets
|
| 38 |
+
|
| 39 |
+
print(f"Streaming {args.dataset} (split={args.split}) for tokenizer training sample...")
|
| 40 |
+
ds = hf_datasets.load_dataset(args.dataset, split=args.split, streaming=True)
|
| 41 |
+
texts = iter_texts_for_tokenizer_training(ds, args.text_column, args.max_docs)
|
| 42 |
+
|
| 43 |
+
print(f"Training BPE tokenizer (vocab_size={args.vocab_size})...")
|
| 44 |
+
train_tokenizer(texts, vocab_size=args.vocab_size, save_dir=args.out)
|
| 45 |
+
print(f"Saved tokenizer to {args.out}")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
if __name__ == "__main__":
|
| 49 |
+
main()
|
bangla30m/scripts/03_speed_test.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
03_speed_test.py — measure real tokens/sec on this GPU/session before
|
| 4 |
+
launching the full 700M-token run. Per the plan: never train blind.
|
| 5 |
+
|
| 6 |
+
Single process (1 GPU):
|
| 7 |
+
python scripts/03_speed_test.py --benchmark-tokens 10000000
|
| 8 |
+
|
| 9 |
+
Both T4s (2 processes) — from a notebook cell:
|
| 10 |
+
from accelerate import notebook_launcher
|
| 11 |
+
from scripts.03_speed_test import main
|
| 12 |
+
notebook_launcher(main, num_processes=2)
|
| 13 |
+
|
| 14 |
+
Or from a terminal:
|
| 15 |
+
accelerate launch --num_processes 2 scripts/03_speed_test.py
|
| 16 |
+
"""
|
| 17 |
+
import argparse
|
| 18 |
+
import sys
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 22 |
+
|
| 23 |
+
from bangla30m.benchmark import run_speed_test
|
| 24 |
+
from bangla30m.config import ModelConfig, TrainConfig
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def main() -> None:
|
| 28 |
+
p = argparse.ArgumentParser()
|
| 29 |
+
p.add_argument("--tokenizer-dir", default="artifacts/tokenizer")
|
| 30 |
+
p.add_argument("--dataset", default="nahid-hub/B-CORE-bengali-corpus")
|
| 31 |
+
p.add_argument("--target-tokens", type=int, default=700_000_000)
|
| 32 |
+
p.add_argument("--benchmark-tokens", type=int, default=10_000_000)
|
| 33 |
+
p.add_argument("--seq-len", type=int, default=512)
|
| 34 |
+
p.add_argument("--per-device-batch-size", type=int, default=32)
|
| 35 |
+
args = p.parse_args()
|
| 36 |
+
|
| 37 |
+
model_cfg = ModelConfig() # ~30-32M params, see bangla30m/config.py
|
| 38 |
+
train_cfg = TrainConfig(
|
| 39 |
+
dataset_name=args.dataset,
|
| 40 |
+
tokenizer_dir=args.tokenizer_dir,
|
| 41 |
+
target_tokens=args.target_tokens,
|
| 42 |
+
seq_len=args.seq_len,
|
| 43 |
+
per_device_batch_size=args.per_device_batch_size,
|
| 44 |
+
gradient_accumulation_steps=1, # plan: benchmark with accumulation=1 first
|
| 45 |
+
mixed_precision="fp16",
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
result = run_speed_test(model_cfg, train_cfg, benchmark_tokens=args.benchmark_tokens)
|
| 49 |
+
|
| 50 |
+
print("\n--- Projection table (plan section 15) ---")
|
| 51 |
+
for rate_k in (20, 25, 26, 30):
|
| 52 |
+
hours = args.target_tokens / (rate_k * 1000) / 3600
|
| 53 |
+
marker = " <- measured" if abs(rate_k - result.tokens_per_second / 1000) < 1.5 else ""
|
| 54 |
+
print(f" {rate_k:>3}K tok/s -> {hours:5.2f}h for {args.target_tokens/1e6:.0f}M tokens{marker}")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
if __name__ == "__main__":
|
| 58 |
+
main()
|
bangla30m/scripts/04_train.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
04_train.py — the full 700M-token Bangla-30M pretraining run.
|
| 4 |
+
|
| 5 |
+
From a Kaggle notebook cell (recommended: both T4s, DDP + fp16):
|
| 6 |
+
from accelerate import notebook_launcher
|
| 7 |
+
from scripts.__dict__ # (see README for the exact notebook cell)
|
| 8 |
+
|
| 9 |
+
Simplest notebook usage — copy this into a cell:
|
| 10 |
+
import sys; sys.path.insert(0, "/kaggle/working/bangla30m")
|
| 11 |
+
from accelerate import notebook_launcher
|
| 12 |
+
from bangla30m.config import ModelConfig, TrainConfig
|
| 13 |
+
from bangla30m.trainer import run_training
|
| 14 |
+
|
| 15 |
+
model_cfg = ModelConfig()
|
| 16 |
+
train_cfg = TrainConfig(tokenizer_dir="artifacts/tokenizer",
|
| 17 |
+
output_dir="artifacts/runs/bangla30m")
|
| 18 |
+
notebook_launcher(run_training, args=(model_cfg, train_cfg), num_processes=2)
|
| 19 |
+
|
| 20 |
+
From a terminal / Kaggle "Run as script":
|
| 21 |
+
accelerate launch --num_processes 2 scripts/04_train.py
|
| 22 |
+
|
| 23 |
+
Re-running this script (or re-running the notebook cell) after an
|
| 24 |
+
interruption automatically resumes from the latest checkpoint under
|
| 25 |
+
--output-dir (TrainConfig.resume_from_checkpoint defaults to True).
|
| 26 |
+
"""
|
| 27 |
+
import argparse
|
| 28 |
+
import sys
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
|
| 31 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 32 |
+
|
| 33 |
+
from bangla30m.config import ModelConfig, TrainConfig
|
| 34 |
+
from bangla30m.trainer import run_training
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def main() -> None:
|
| 38 |
+
p = argparse.ArgumentParser()
|
| 39 |
+
p.add_argument("--tokenizer-dir", default="artifacts/tokenizer")
|
| 40 |
+
p.add_argument("--dataset", default="nahid-hub/B-CORE-bengali-corpus")
|
| 41 |
+
p.add_argument("--output-dir", default="artifacts/runs/bangla30m")
|
| 42 |
+
p.add_argument("--target-tokens", type=int, default=700_000_000)
|
| 43 |
+
p.add_argument("--seq-len", type=int, default=512)
|
| 44 |
+
p.add_argument("--per-device-batch-size", type=int, default=32)
|
| 45 |
+
p.add_argument("--grad-accum", type=int, default=2)
|
| 46 |
+
p.add_argument("--learning-rate", type=float, default=3e-4)
|
| 47 |
+
p.add_argument("--checkpoint-every-tokens", type=int, default=100_000_000)
|
| 48 |
+
p.add_argument("--gradient-checkpointing", action="store_true")
|
| 49 |
+
p.add_argument("--no-resume", action="store_true")
|
| 50 |
+
p.add_argument("--activation", choices=["swiglu", "gelu"], default="swiglu")
|
| 51 |
+
args = p.parse_args()
|
| 52 |
+
|
| 53 |
+
model_cfg = ModelConfig(activation=args.activation)
|
| 54 |
+
train_cfg = TrainConfig(
|
| 55 |
+
dataset_name=args.dataset,
|
| 56 |
+
tokenizer_dir=args.tokenizer_dir,
|
| 57 |
+
output_dir=args.output_dir,
|
| 58 |
+
target_tokens=args.target_tokens,
|
| 59 |
+
seq_len=args.seq_len,
|
| 60 |
+
per_device_batch_size=args.per_device_batch_size,
|
| 61 |
+
gradient_accumulation_steps=args.grad_accum,
|
| 62 |
+
learning_rate=args.learning_rate,
|
| 63 |
+
checkpoint_every_tokens=args.checkpoint_every_tokens,
|
| 64 |
+
gradient_checkpointing=args.gradient_checkpointing,
|
| 65 |
+
resume_from_checkpoint=not args.no_resume,
|
| 66 |
+
mixed_precision="fp16",
|
| 67 |
+
)
|
| 68 |
+
run_training(model_cfg, train_cfg)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
if __name__ == "__main__":
|
| 72 |
+
main()
|
bangla30m/scripts/05_evaluate.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
05_evaluate.py — load a checkpoint, report held-out perplexity, and print a
|
| 4 |
+
few sample generations.
|
| 5 |
+
|
| 6 |
+
python scripts/05_evaluate.py --checkpoint artifacts/runs/bangla30m/checkpoints/tokens_000700000000
|
| 7 |
+
"""
|
| 8 |
+
import argparse
|
| 9 |
+
import sys
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
from accelerate import Accelerator
|
| 16 |
+
from torch.utils.data import DataLoader
|
| 17 |
+
|
| 18 |
+
from bangla30m.config import ModelConfig, TrainConfig
|
| 19 |
+
from bangla30m.data import BCoreStreamingDataset, collate_fn
|
| 20 |
+
from bangla30m.evaluate import compute_perplexity, generate_samples
|
| 21 |
+
from bangla30m.model import build_model
|
| 22 |
+
from bangla30m.tokenizer import Bangla30MTokenizer
|
| 23 |
+
|
| 24 |
+
DEFAULT_PROMPTS = [
|
| 25 |
+
"বাংলাদেশের রাজধানী হলো",
|
| 26 |
+
"কৃত্রিম বুদ্ধিমত্তা ভবিষ্যতে",
|
| 27 |
+
"আজকের আবহাওয়া",
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def main() -> None:
|
| 32 |
+
p = argparse.ArgumentParser()
|
| 33 |
+
p.add_argument("--checkpoint", required=True)
|
| 34 |
+
p.add_argument("--tokenizer-dir", default="artifacts/tokenizer")
|
| 35 |
+
p.add_argument("--dataset", default="nahid-hub/B-CORE-bengali-corpus")
|
| 36 |
+
p.add_argument("--eval-batches", type=int, default=200)
|
| 37 |
+
p.add_argument("--seq-len", type=int, default=512)
|
| 38 |
+
p.add_argument("--max-new-tokens", type=int, default=80)
|
| 39 |
+
args = p.parse_args()
|
| 40 |
+
|
| 41 |
+
tokenizer = Bangla30MTokenizer.from_dir(args.tokenizer_dir)
|
| 42 |
+
model_cfg = ModelConfig(vocab_size=tokenizer.vocab_size, max_seq_len=args.seq_len)
|
| 43 |
+
model = build_model(model_cfg)
|
| 44 |
+
|
| 45 |
+
accelerator = Accelerator()
|
| 46 |
+
model = accelerator.prepare(model)
|
| 47 |
+
accelerator.load_state(args.checkpoint)
|
| 48 |
+
device = accelerator.device
|
| 49 |
+
|
| 50 |
+
train_cfg = TrainConfig(dataset_name=args.dataset, tokenizer_dir=args.tokenizer_dir, seq_len=args.seq_len)
|
| 51 |
+
# held-out slice: skip the docs used for training (approx, via a large skip offset)
|
| 52 |
+
ds = BCoreStreamingDataset(
|
| 53 |
+
tokenizer=tokenizer, seq_len=args.seq_len, dataset_name=args.dataset,
|
| 54 |
+
target_tokens=args.eval_batches * args.seq_len * 8, skip_examples=2_000_000,
|
| 55 |
+
)
|
| 56 |
+
dl = DataLoader(ds, batch_size=8, collate_fn=collate_fn)
|
| 57 |
+
|
| 58 |
+
result = compute_perplexity(accelerator.unwrap_model(model), dl, max_batches=args.eval_batches, device=device)
|
| 59 |
+
print(f"loss={result.loss:.4f} perplexity={result.perplexity:.2f} tokens={result.tokens_evaluated:,}")
|
| 60 |
+
|
| 61 |
+
print("\nSample generations:")
|
| 62 |
+
samples = generate_samples(
|
| 63 |
+
accelerator.unwrap_model(model), tokenizer, DEFAULT_PROMPTS,
|
| 64 |
+
max_new_tokens=args.max_new_tokens, device=device,
|
| 65 |
+
)
|
| 66 |
+
for s in samples:
|
| 67 |
+
print(f"\n[prompt] {s['prompt']}\n[completion] {s['completion']}")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
if __name__ == "__main__":
|
| 71 |
+
main()
|
bangla30m/tests/test_config.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from bangla30m.config import ModelConfig, TrainConfig
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def test_default_config_hits_target_param_range():
|
| 5 |
+
cfg = ModelConfig()
|
| 6 |
+
stats = cfg.count_parameters()
|
| 7 |
+
# plan targets "30-32M parameters"
|
| 8 |
+
assert 29_000_000 <= stats["total"] <= 33_000_000, stats
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_ffn_size_derivation_gelu_vs_swiglu_same_param_budget():
|
| 12 |
+
swiglu_cfg = ModelConfig(activation="swiglu")
|
| 13 |
+
gelu_cfg = ModelConfig(activation="gelu")
|
| 14 |
+
swiglu_total = swiglu_cfg.count_parameters()["total"]
|
| 15 |
+
gelu_total = gelu_cfg.count_parameters()["total"]
|
| 16 |
+
# both should land in the same ballpark despite swiglu using 3 matrices
|
| 17 |
+
# vs gelu's 2, because ffn_size is derived to compensate
|
| 18 |
+
assert abs(swiglu_total - gelu_total) / gelu_total < 0.02
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def test_hidden_size_must_divide_num_heads():
|
| 22 |
+
import pytest
|
| 23 |
+
with pytest.raises(ValueError):
|
| 24 |
+
ModelConfig(hidden_size=100, num_heads=8)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def test_autotune_hidden_size_hits_target_closely():
|
| 28 |
+
cfg = ModelConfig(hidden_size=256) # deliberately far from target
|
| 29 |
+
tuned = cfg.autotune_hidden_size(target_params=30_000_000, search_range=512)
|
| 30 |
+
total = tuned.count_parameters()["total"]
|
| 31 |
+
assert abs(total - 30_000_000) < abs(cfg.count_parameters()["total"] - 30_000_000)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def test_model_config_roundtrip_save_load(tmp_path):
|
| 35 |
+
cfg = ModelConfig(hidden_size=256, num_heads=4)
|
| 36 |
+
path = tmp_path / "model_config.json"
|
| 37 |
+
cfg.save(path)
|
| 38 |
+
loaded = ModelConfig.load(path)
|
| 39 |
+
assert loaded == cfg
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def test_train_config_total_steps_scales_with_world_size():
|
| 43 |
+
cfg = TrainConfig(target_tokens=1_000_000, per_device_batch_size=8, seq_len=512, gradient_accumulation_steps=1)
|
| 44 |
+
steps_1gpu = cfg.total_steps(world_size=1)
|
| 45 |
+
steps_2gpu = cfg.total_steps(world_size=2)
|
| 46 |
+
assert steps_2gpu <= steps_1gpu
|
| 47 |
+
assert steps_1gpu > 0 and steps_2gpu > 0
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_train_config_roundtrip_save_load(tmp_path):
|
| 51 |
+
cfg = TrainConfig(learning_rate=1e-4, per_device_batch_size=16)
|
| 52 |
+
path = tmp_path / "train_config.json"
|
| 53 |
+
cfg.save(path)
|
| 54 |
+
loaded = TrainConfig.load(path)
|
| 55 |
+
assert loaded == cfg
|
bangla30m/tests/test_data.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
from bangla30m.data import BCoreStreamingDataset, TokenPacker, clean_text, collate_fn
|
| 4 |
+
from bangla30m.tokenizer import Bangla30MTokenizer, train_tokenizer
|
| 5 |
+
|
| 6 |
+
BANGLA_SAMPLE = ["আমি বাংলায় গান গাই এবং কবিতা লিখি।", "কৃত্রিম বুদ্ধিমত্তা নিয়ে গবেষণা চলছে।"] * 200
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# ---- clean_text -----------------------------------------------------------
|
| 10 |
+
def test_clean_text_keeps_normal_text():
|
| 11 |
+
assert clean_text("এটি একটি স্বাভাবিক এবং যথেষ্ট দীর্ঘ বাক্য।") is not None
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_clean_text_drops_empty_or_none():
|
| 15 |
+
assert clean_text(None) is None
|
| 16 |
+
assert clean_text("") is None
|
| 17 |
+
assert clean_text(" ") is None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def test_clean_text_drops_too_short():
|
| 21 |
+
assert clean_text("ছোট", min_chars=20) is None
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_clean_text_drops_repeated_char_spam():
|
| 25 |
+
assert clean_text("এটি একটি ভালো বাক্য" + "!" * 30) is None
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_clean_text_drops_low_printable_ratio():
|
| 29 |
+
junk = "".join(chr(i) for i in range(1, 15)) * 5 # control chars
|
| 30 |
+
assert clean_text(junk) is None
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# ---- TokenPacker ------------------------------------------------------------
|
| 34 |
+
def test_token_packer_yields_fixed_length_chunks():
|
| 35 |
+
packer = TokenPacker(seq_len=4, eos_token_id=999)
|
| 36 |
+
chunks = list(packer.feed([1, 2, 3, 4, 5, 6]))
|
| 37 |
+
assert all(len(c) == 5 for c in chunks) # seq_len + 1
|
| 38 |
+
# 6 tokens + 1 eos = 7 tokens -> one full chunk of 5, 2 left in buffer
|
| 39 |
+
assert len(chunks) == 1
|
| 40 |
+
assert len(packer) == 2
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_token_packer_carries_over_leftover_across_feeds():
|
| 44 |
+
packer = TokenPacker(seq_len=4, eos_token_id=999)
|
| 45 |
+
list(packer.feed([1, 2])) # 2 + eos = 3 tokens, buffered
|
| 46 |
+
chunks = list(packer.feed([3, 4])) # 3 + [3,4] + eos = 6 -> one chunk, 1 left
|
| 47 |
+
assert len(chunks) == 1
|
| 48 |
+
assert len(packer) == 1
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# ---- BCoreStreamingDataset --------------------------------------------------
|
| 52 |
+
def _build_tokenizer(tmp_path):
|
| 53 |
+
train_tokenizer(BANGLA_SAMPLE, vocab_size=800, save_dir=tmp_path)
|
| 54 |
+
return Bangla30MTokenizer.from_dir(tmp_path)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_streaming_dataset_packs_and_respects_token_budget(tmp_path):
|
| 58 |
+
tok = _build_tokenizer(tmp_path)
|
| 59 |
+
|
| 60 |
+
def source(n=500):
|
| 61 |
+
for i in range(n):
|
| 62 |
+
yield {"text": BANGLA_SAMPLE[i % len(BANGLA_SAMPLE)] + f" {i}।"}
|
| 63 |
+
|
| 64 |
+
ds = BCoreStreamingDataset(tokenizer=tok, seq_len=16, target_tokens=200, source_dataset=source())
|
| 65 |
+
batches = list(ds)
|
| 66 |
+
assert len(batches) > 0
|
| 67 |
+
for b in batches:
|
| 68 |
+
assert b["input_ids"].shape == (16,)
|
| 69 |
+
assert b["labels"].shape == (16,)
|
| 70 |
+
assert torch.equal(b["labels"][:-1], b["input_ids"][1:]) # shifted-by-one
|
| 71 |
+
assert ds.stats.tokens_yielded >= 200
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def test_streaming_dataset_filters_garbage_docs(tmp_path):
|
| 75 |
+
tok = _build_tokenizer(tmp_path)
|
| 76 |
+
|
| 77 |
+
def source():
|
| 78 |
+
for i in range(50):
|
| 79 |
+
yield {"text": "x"} # too short, always filtered
|
| 80 |
+
for i in range(50):
|
| 81 |
+
yield {"text": BANGLA_SAMPLE[i % len(BANGLA_SAMPLE)]}
|
| 82 |
+
|
| 83 |
+
ds = BCoreStreamingDataset(tokenizer=tok, seq_len=16, target_tokens=100, source_dataset=source())
|
| 84 |
+
list(ds)
|
| 85 |
+
assert ds.stats.docs_seen > ds.stats.docs_kept
|
| 86 |
+
assert ds.stats.docs_kept > 0
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def test_streaming_dataset_shards_by_rank_without_overlap(tmp_path):
|
| 90 |
+
tok = _build_tokenizer(tmp_path)
|
| 91 |
+
docs = [{"text": BANGLA_SAMPLE[i % len(BANGLA_SAMPLE)] + f" {i}।"} for i in range(200)]
|
| 92 |
+
|
| 93 |
+
# simulate 2-way node split the way datasets.distributed.split_dataset_by_node does:
|
| 94 |
+
# here we just assert our own rank-skip-within-worker logic doesn't crash and
|
| 95 |
+
# that feeding the *same* full stream to two "ranks" via source_dataset (which
|
| 96 |
+
# bypasses split_dataset_by_node) still yields consistent packed shapes.
|
| 97 |
+
ds0 = BCoreStreamingDataset(tokenizer=tok, seq_len=16, target_tokens=100, source_dataset=iter(docs))
|
| 98 |
+
out0 = list(ds0)
|
| 99 |
+
assert len(out0) > 0
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def test_collate_fn_stacks_batch():
|
| 103 |
+
a = {"input_ids": torch.tensor([1, 2, 3]), "labels": torch.tensor([2, 3, 4])}
|
| 104 |
+
b = {"input_ids": torch.tensor([5, 6, 7]), "labels": torch.tensor([6, 7, 8])}
|
| 105 |
+
batch = collate_fn([a, b])
|
| 106 |
+
assert batch["input_ids"].shape == (2, 3)
|
| 107 |
+
assert batch["labels"].shape == (2, 3)
|
bangla30m/tests/test_model.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from bangla30m.config import ModelConfig
|
| 5 |
+
from bangla30m.model import Bangla30M, RMSNorm, apply_rotary_pos_emb, RotaryEmbedding, build_model
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def small_cfg(**overrides):
|
| 9 |
+
base = dict(vocab_size=200, hidden_size=32, num_layers=2, num_heads=4, max_seq_len=16)
|
| 10 |
+
base.update(overrides)
|
| 11 |
+
return ModelConfig(**base)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_analytic_param_count_matches_actual_module():
|
| 15 |
+
cfg = small_cfg()
|
| 16 |
+
model = build_model(cfg)
|
| 17 |
+
assert model.num_parameters() == cfg.count_parameters()["total"]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@pytest.mark.parametrize("activation", ["swiglu", "gelu"])
|
| 21 |
+
def test_forward_shapes_and_loss(activation):
|
| 22 |
+
cfg = small_cfg(activation=activation)
|
| 23 |
+
model = build_model(cfg)
|
| 24 |
+
x = torch.randint(0, cfg.vocab_size, (3, 10))
|
| 25 |
+
out = model(x, labels=x)
|
| 26 |
+
assert out.logits.shape == (3, 10, cfg.vocab_size)
|
| 27 |
+
assert out.loss.item() > 0
|
| 28 |
+
assert torch.isfinite(out.loss)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def test_backward_pass_populates_gradients():
|
| 32 |
+
cfg = small_cfg()
|
| 33 |
+
model = build_model(cfg)
|
| 34 |
+
x = torch.randint(0, cfg.vocab_size, (2, 8))
|
| 35 |
+
out = model(x, labels=x)
|
| 36 |
+
out.loss.backward()
|
| 37 |
+
grad_norms = [p.grad.norm().item() for p in model.parameters() if p.grad is not None]
|
| 38 |
+
assert len(grad_norms) > 0
|
| 39 |
+
assert all(torch.isfinite(torch.tensor(g)) for g in grad_norms)
|
| 40 |
+
assert sum(grad_norms) > 0
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_tied_embeddings_share_storage():
|
| 44 |
+
cfg = small_cfg(tie_embeddings=True)
|
| 45 |
+
model = build_model(cfg)
|
| 46 |
+
assert model.lm_head is None
|
| 47 |
+
x = torch.randint(0, cfg.vocab_size, (1, 5))
|
| 48 |
+
out = model(x)
|
| 49 |
+
assert out.logits.shape == (1, 5, cfg.vocab_size)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_untied_embeddings_use_separate_head():
|
| 53 |
+
cfg = small_cfg(tie_embeddings=False)
|
| 54 |
+
model = build_model(cfg)
|
| 55 |
+
assert model.lm_head is not None
|
| 56 |
+
assert model.lm_head.weight.data_ptr() != model.embed_tokens.weight.data_ptr()
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def test_causal_masking_future_tokens_dont_affect_earlier_logits():
|
| 60 |
+
cfg = small_cfg()
|
| 61 |
+
model = build_model(cfg)
|
| 62 |
+
model.eval()
|
| 63 |
+
x = torch.randint(0, cfg.vocab_size, (1, 6))
|
| 64 |
+
logits_full = model(x).logits[0, 2] # logits at position 2 with full sequence
|
| 65 |
+
|
| 66 |
+
x_truncated = x[:, :3] # only first 3 tokens (positions 0,1,2)
|
| 67 |
+
logits_truncated = model(x_truncated).logits[0, 2]
|
| 68 |
+
|
| 69 |
+
assert torch.allclose(logits_full, logits_truncated, atol=1e-4)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def test_rotary_embedding_shapes():
|
| 73 |
+
head_dim, seq_len = 8, 16
|
| 74 |
+
rope = RotaryEmbedding(head_dim, seq_len)
|
| 75 |
+
cos, sin = rope(seq_len, "cpu", torch.float32)
|
| 76 |
+
assert cos.shape == (seq_len, head_dim)
|
| 77 |
+
assert sin.shape == (seq_len, head_dim)
|
| 78 |
+
|
| 79 |
+
q = torch.randn(1, 2, seq_len, head_dim)
|
| 80 |
+
k = torch.randn(1, 2, seq_len, head_dim)
|
| 81 |
+
q_rot, k_rot = apply_rotary_pos_emb(q, k, cos, sin)
|
| 82 |
+
assert q_rot.shape == q.shape
|
| 83 |
+
assert k_rot.shape == k.shape
|
| 84 |
+
# RoPE preserves vector norm (it's a rotation)
|
| 85 |
+
assert torch.allclose(q_rot.norm(dim=-1), q.norm(dim=-1), atol=1e-4)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def test_rmsnorm_output_has_unit_ish_scale():
|
| 89 |
+
norm = RMSNorm(16)
|
| 90 |
+
x = torch.randn(4, 16) * 5
|
| 91 |
+
out = norm(x)
|
| 92 |
+
rms = out.pow(2).mean(-1).sqrt()
|
| 93 |
+
assert torch.allclose(rms, torch.ones(4), atol=0.1)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def test_generate_produces_longer_sequence():
|
| 97 |
+
cfg = small_cfg()
|
| 98 |
+
model = build_model(cfg)
|
| 99 |
+
x = torch.tensor([[cfg.bos_token_id]])
|
| 100 |
+
out = model.generate(x, max_new_tokens=5, eos_token_id=None)
|
| 101 |
+
assert out.shape[1] == 1 + 5
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def test_gradient_checkpointing_matches_normal_forward_loss():
|
| 105 |
+
torch.manual_seed(0)
|
| 106 |
+
cfg = small_cfg()
|
| 107 |
+
model = build_model(cfg)
|
| 108 |
+
x = torch.randint(0, cfg.vocab_size, (2, 8))
|
| 109 |
+
|
| 110 |
+
model.train()
|
| 111 |
+
out_normal = model(x, labels=x)
|
| 112 |
+
|
| 113 |
+
model.enable_gradient_checkpointing(True)
|
| 114 |
+
out_ckpt = model(x, labels=x)
|
| 115 |
+
|
| 116 |
+
assert torch.allclose(out_normal.loss, out_ckpt.loss, atol=1e-5)
|
bangla30m/tests/test_tokenizer.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from bangla30m.tokenizer import Bangla30MTokenizer, train_tokenizer
|
| 2 |
+
|
| 3 |
+
BANGLA_SAMPLE = [
|
| 4 |
+
"আমি বাংলায় গান গাই।",
|
| 5 |
+
"বাংলাদেশ দক্ষিণ এশিয়ার একটি দেশ।",
|
| 6 |
+
"কৃত্রিম বুদ্ধিমত্তা নিয়ে গবেষণা চলছে।",
|
| 7 |
+
"শিক্ষার্থীরা বিশ্ববিদ্যালয়ে পড়াশোনা করে।",
|
| 8 |
+
] * 100
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_train_and_reload(tmp_path):
|
| 12 |
+
train_tokenizer(BANGLA_SAMPLE, vocab_size=600, save_dir=tmp_path)
|
| 13 |
+
tok = Bangla30MTokenizer.from_dir(tmp_path)
|
| 14 |
+
assert tok.vocab_size <= 600
|
| 15 |
+
assert tok.bos_token_id == 0
|
| 16 |
+
assert tok.eos_token_id == 1
|
| 17 |
+
assert tok.pad_token_id == 2
|
| 18 |
+
assert tok.unk_token_id == 3
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def test_encode_decode_roundtrip(tmp_path):
|
| 22 |
+
train_tokenizer(BANGLA_SAMPLE, vocab_size=600, save_dir=tmp_path)
|
| 23 |
+
tok = Bangla30MTokenizer.from_dir(tmp_path)
|
| 24 |
+
text = "আমি বাংলায় গান গাই।"
|
| 25 |
+
ids = tok.encode(text)
|
| 26 |
+
assert ids[0] == tok.bos_token_id
|
| 27 |
+
assert ids[-1] == tok.eos_token_id
|
| 28 |
+
decoded = tok.decode(ids)
|
| 29 |
+
assert decoded.replace(" ", "") == text.replace(" ", "") or decoded == text
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def test_encode_without_special_tokens(tmp_path):
|
| 33 |
+
train_tokenizer(BANGLA_SAMPLE, vocab_size=600, save_dir=tmp_path)
|
| 34 |
+
tok = Bangla30MTokenizer.from_dir(tmp_path)
|
| 35 |
+
ids = tok.encode("আমি বাংলায় গান গাই।", add_special_tokens=False)
|
| 36 |
+
assert tok.bos_token_id not in ids
|
| 37 |
+
assert tok.eos_token_id not in ids
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def test_encode_batch(tmp_path):
|
| 41 |
+
train_tokenizer(BANGLA_SAMPLE, vocab_size=600, save_dir=tmp_path)
|
| 42 |
+
tok = Bangla30MTokenizer.from_dir(tmp_path)
|
| 43 |
+
batch = tok.encode_batch(["আমি বাংলায় গান গাই।", "বাংলাদেশ দক্ষিণ এশিয়ার একটি দেশ।"])
|
| 44 |
+
assert len(batch) == 2
|
| 45 |
+
assert all(isinstance(ids, list) and len(ids) > 0 for ids in batch)
|
bangla30m/tests/test_trainer.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import shutil
|
| 2 |
+
|
| 3 |
+
from bangla30m.config import ModelConfig, TrainConfig
|
| 4 |
+
from bangla30m.tokenizer import train_tokenizer
|
| 5 |
+
|
| 6 |
+
BANGLA_SAMPLE = ["আমি বাংলায় গান গাই এবং কবিতা লিখি।", "কৃত্রিম বুদ্ধিমত্তা নিয়ে গবেষণা চলছে।"]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _make_source(n=4000):
|
| 10 |
+
def gen():
|
| 11 |
+
for i in range(n):
|
| 12 |
+
yield {"text": BANGLA_SAMPLE[i % 2] + f" নম্বর {i}।"}
|
| 13 |
+
return gen()
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _tiny_configs(tmp_path, **train_overrides):
|
| 17 |
+
tok_dir = tmp_path / "tok"
|
| 18 |
+
train_tokenizer(BANGLA_SAMPLE * 200, vocab_size=600, save_dir=tok_dir)
|
| 19 |
+
model_cfg = ModelConfig(vocab_size=600, hidden_size=32, num_layers=2, num_heads=4, max_seq_len=16)
|
| 20 |
+
base = dict(
|
| 21 |
+
seq_len=16, per_device_batch_size=4, gradient_accumulation_steps=1,
|
| 22 |
+
dataloader_workers=0, mixed_precision="no", log_every_steps=5,
|
| 23 |
+
tokenizer_dir=str(tok_dir), output_dir=str(tmp_path / "run"),
|
| 24 |
+
)
|
| 25 |
+
base.update(train_overrides)
|
| 26 |
+
return model_cfg, TrainConfig(**base)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_training_loop_reduces_loss(tmp_path):
|
| 30 |
+
from bangla30m.trainer import run_training
|
| 31 |
+
model_cfg, train_cfg = _tiny_configs(
|
| 32 |
+
tmp_path, target_tokens=10_000, checkpoint_every_tokens=50_000, resume_from_checkpoint=False,
|
| 33 |
+
)
|
| 34 |
+
result = run_training(model_cfg, train_cfg, source_dataset=_make_source())
|
| 35 |
+
losses = [h.loss for h in result["history"]]
|
| 36 |
+
assert len(losses) >= 3
|
| 37 |
+
# average of the last third should be meaningfully lower than the first third
|
| 38 |
+
third = max(1, len(losses) // 3)
|
| 39 |
+
assert sum(losses[-third:]) / third < sum(losses[:third]) / third
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def test_training_produces_token_accounted_checkpoints(tmp_path):
|
| 43 |
+
from bangla30m import checkpoint as ckpt
|
| 44 |
+
from bangla30m.trainer import run_training
|
| 45 |
+
model_cfg, train_cfg = _tiny_configs(
|
| 46 |
+
tmp_path, target_tokens=12_000, checkpoint_every_tokens=4_000, resume_from_checkpoint=False,
|
| 47 |
+
)
|
| 48 |
+
run_training(model_cfg, train_cfg, source_dataset=_make_source())
|
| 49 |
+
latest = ckpt.find_latest_checkpoint(train_cfg.output_dir)
|
| 50 |
+
assert latest is not None
|
| 51 |
+
assert latest["tokens_seen"] >= 4_000
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_resume_continues_past_previous_step_count(tmp_path):
|
| 55 |
+
from bangla30m.trainer import run_training
|
| 56 |
+
model_cfg, cfg1 = _tiny_configs(
|
| 57 |
+
tmp_path, target_tokens=8_000, checkpoint_every_tokens=4_000, resume_from_checkpoint=False,
|
| 58 |
+
)
|
| 59 |
+
r1 = run_training(model_cfg, cfg1, source_dataset=_make_source())
|
| 60 |
+
|
| 61 |
+
_, cfg2 = _tiny_configs(
|
| 62 |
+
tmp_path, target_tokens=16_000, checkpoint_every_tokens=4_000, resume_from_checkpoint=True,
|
| 63 |
+
)
|
| 64 |
+
r2 = run_training(model_cfg, cfg2, source_dataset=_make_source())
|
| 65 |
+
|
| 66 |
+
assert r2["final_step"] > r1["final_step"]
|
| 67 |
+
assert r2["final_tokens"] > r1["final_tokens"]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def test_training_stops_at_target_tokens_not_before(tmp_path):
|
| 71 |
+
from bangla30m.trainer import run_training
|
| 72 |
+
model_cfg, train_cfg = _tiny_configs(
|
| 73 |
+
tmp_path, target_tokens=6_000, checkpoint_every_tokens=100_000,
|
| 74 |
+
resume_from_checkpoint=False,
|
| 75 |
+
)
|
| 76 |
+
# give it plenty of data so target_tokens (not data exhaustion) is the stopping condition
|
| 77 |
+
result = run_training(model_cfg, train_cfg, source_dataset=_make_source(n=20_000))
|
| 78 |
+
assert result["final_tokens"] >= train_cfg.target_tokens
|