Download aether_train.py from ArcOffical/encoslm-aether-v3: direct link, hf CLI and curl.
- Browser
- Download file 65.7 kB
-
https://huggingface.co/ArcOffical/encoslm-aether-v3/resolve/main/aether_train.py
- Command line
-
hf download hf://ArcOffical/encoslm-aether-v3/aether_train.py
-
curl -L -o aether_train.py https://huggingface.co/ArcOffical/encoslm-aether-v3/resolve/main/aether_train.py
65.7 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Encos-Train v3 — training recipe for EncosLM v3 (see aether_llm.py)
====================================================================
Run it:
python3 aether_train.py --model-config 7b-aether --stage all --dtype bf16 --checkpoint-dir ./encos_run
python3 aether_train.py --smoke # offline 1-step check, free
python3 aether_train.py --ablation tiny # run vanilla/+SDA/+LRS/+both ablation
================================================================================
WHAT'S NEW IN v3
================================================================================
v2 → v3 (in aether_train.py)
----------------------------
* MinHash-LSH dedup. v2 used exact MD5 dedup only, which misses the 10-30%
near-duplicate leakage that dominates real web corpora. v3 uses MinHash-LSH
(datasketch library) with a graceful fallback to MD5 if datasketch is
unavailable. Threshold defaults to 0.9 Jaccard similarity.
* Better quality filter. v2's `1 - len(set(bigrams))/len(bigrams) <= 0.45`
is a crude n-gram repetition heuristic. v3 adds:
- a length-aware score (penalise docs near min/max boundaries),
- a "boilerplate marker" detector (drop docs with > 5% lines matching
common boilerplate patterns: "Cookie Policy", "Subscribe to our
newsletter", "© 20XX", etc.),
- optional hook for a learned quality classifier (placeholder interface;
the user can plug in a fine-tuned BERT).
* LR schedule continuity check on resume. v2 saved the scheduler step but
didn't verify that `total_steps` was consistent across resumes — if the
data pool size changed between resumes (e.g., you re-estimated step count
after adding a source), the cosine decay shape would be wrong. v3 detects
this and rebuilds the schedule against the new total while preserving the
relative progress.
* EMA decay default 0.9995 (v2 was 0.999 — too low for long pretrains; GPT-3
used 0.9999 with warmup). Configurable.
* Ablation harness. `python3 aether_train.py --ablation tiny` runs four
configs (vanilla / +SDA / +LRS / +both) on identical data for a fixed
number of steps and reports held-out perplexity. Lets you actually
measure whether SDA / LRS help before claiming "breakthrough".
* Per-source `avg_chars` carried over from v2 (calibrated values for
C4/OpenWebText/Wikipedia).
Carried from v2 (unchanged in v3):
* EMA carried across stages (no reset between pretrain/SFT/DPO).
* Per-stage validation loop with held-out perplexity.
* FSDP wrap option (replaces DDP-only path).
* MoE z-loss folded into aux loss.
* bf16/fp16 autocast + GradScaler, gradient accumulation & clipping.
* AdamW with decoupled weight decay + layer-wise LR decay.
* Warmup + cosine decay with min-LR floor.
* Checkpoint averaging of the last K checkpoints.
* Optional FlashAttention (SDPA) + gradient checkpointing + torch.compile.
* Multi-stage: pretrain -> SFT (response-masked) -> optional DPO.
================================================================================
Encos-Train (honest engineering notes)
================================================================================
"Encos-Train" is the packaged data + optimisation recipe. It is NOT a claimed
breakthrough — it is a careful combination of established, proven training
techniques with a couple of small custom heuristics (curriculum ordering,
quality filter).
Compute honesty
---------------
A 7B model needs ~14 GB (bf16) of VRAM just for weights, plus optimizer state
(~3x more) and activations. From-scratch 7B training is hundreds of GPU-days
on A100/H100-class hardware. The defaults below (40k/20k/20k pretrain docs)
are VALIDATION-scale caps so the pipeline runs end-to-end; raise the caps (and
add multi-node compute) for a serious run. Always start with `--smoke`, then
`--model-config tiny` / `1b` on the hardware you actually have.
"""
from __future__ import annotations
import argparse
import collections
import copy
import hashlib
import json
import math
import os
import random
import re
import shutil
import sys
import time
from dataclasses import asdict, dataclass, field
from typing import Dict, Iterator, List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from aether_llm import EncosLM, EncosConfig, build_config, build_tokenizer # noqa: E402
# --------------------------------------------------------------------------- #
# Training configuration
# --------------------------------------------------------------------------- #
# Per-source average document length in characters (calibrated from public
# HF dataset stats).
PER_SOURCE_AVG_CHARS: Dict[str, int] = {
"c4": 3000,
"openwebtext": 4000,
"wikipedia": 2500,
"dolly": 600,
"alpaca_cleaned": 500,
"ultrachat": 1200,
}
# Common boilerplate patterns to drop (v3 quality filter enhancement).
_BOILERPLATE_PATTERNS = [
re.compile(r"cookie\s+policy", re.IGNORECASE),
re.compile(r"subscribe\s+to\s+our\s+newsletter", re.IGNORECASE),
re.compile(r"©\s*\d{4}", re.IGNORECASE),
re.compile(r"all\s+rights\s+reserved", re.IGNORECASE),
re.compile(r"javascript\s+is\s+required", re.IGNORECASE),
re.compile(r"please\s+enable\s+javascript", re.IGNORECASE),
re.compile(r"\bprivacy\s+policy\b", re.IGNORECASE),
re.compile(r"\bterms\s+of\s+service\b", re.IGNORECASE),
]
@dataclass
class EncosTrainConfig:
model_preset: str = "7b"
tokenizer_name: str = "EleutherAI/gpt-neox-20b"
seq_len: int = 2048
micro_batch: int = 8
grad_accum: int = 8
pretrain_lr: float = 3e-4
sft_lr: float = 2e-5
dpo_lr: float = 5e-6
warmup_frac: float = 0.03
min_lr_ratio: float = 0.1
weight_decay: float = 0.1
betas: Tuple[float, float] = (0.9, 0.95)
grad_clip: float = 1.0
layer_lr_decay: float = 0.9
ema_decay: float = 0.9995 # v3: higher default (was 0.999 in v2)
ema_warmup_steps: int = 1000 # v3: EMA bias-corrected for first N steps
epochs_pretrain: int = 1
epochs_sft: int = 2
dpo_beta: float = 0.1
quality_filter: bool = True
dedup: bool = True
dedup_method: str = "minhash" # v3: "minhash" (preferred) or "md5"
minhash_threshold: float = 0.9 # v3: Jaccard similarity threshold
minhash_num_perm: int = 128 # v3: number of MinHash permutations
curriculum: bool = True
num_curriculum_buckets: int = 4
boilerplate_filter: bool = True # v3: drop docs with boilerplate markers
# v2: validation
eval_every: int = 500
eval_holdout_frac: float = 0.05
mix_weights: Dict[str, float] = field(default_factory=lambda: {"c4": 0.4, "openwebtext": 0.3, "wikipedia": 0.3})
sft_mix_weights: Dict[str, float] = field(default_factory=lambda: {"dolly": 0.4, "alpaca_cleaned": 0.3, "ultrachat": 0.3})
pretrain_caps: Dict[str, int] = field(default_factory=lambda: {"c4": 40_000, "openwebtext": 20_000, "wikipedia": 20_000})
sft_caps: Dict[str, int] = field(default_factory=lambda: {"dolly": 15_000, "alpaca_cleaned": 20_000, "ultrachat": 20_000})
dpo_cap: int = 10_000
checkpoint_dir: str = "./encos_run"
save_every: int = 500
log_every: int = 10
dtype: str = "bf16"
seed: int = 42
use_fsdp: bool = False
# --------------------------------------------------------------------------- #
# v3: MinHash-LSH dedup (with MD5 fallback)
# --------------------------------------------------------------------------- #
class _MinHashDeduper:
"""MinHash-LSH dedup. Falls back to MD5 if `datasketch` is unavailable.
MinHash-LSH catches near-duplicates (e.g., the same article with minor
edits) which exact MD5 misses. This is critical for web corpora, where
10-30% of docs are near-duplicates of each other.
The deduper maintains an LSH index; for each new doc it computes a MinHash
signature and queries the index. If a near-duplicate exists (Jaccard
similarity > threshold), the doc is dropped. Otherwise the doc is added
to the index.
"""
def __init__(self, threshold: float = 0.9, num_perm: int = 128):
self.threshold = threshold
self.num_perm = num_perm
self._available = False
try:
from datasketch import MinHash, MinHashLSH
self.MinHash = MinHash
self.MinHashLSH = MinHashLSH
self._lsh = MinHashLSH(threshold=threshold, num_perm=num_perm)
self._available = True
except ImportError:
print("[encos] WARNING: datasketch not available, falling back to MD5 dedup. "
"Install with: pip install datasketch")
self._seen_hashes: set = set()
@staticmethod
def _shingles(text: str, k: int = 5) -> set:
"""Word-level k-shingles (k=5 by default)."""
words = text.lower().split()
if len(words) < k:
return {tuple(words)} if words else set()
return {tuple(words[i:i + k]) for i in range(len(words) - k + 1)}
def is_duplicate(self, text: str, doc_id: Optional[str] = None) -> bool:
"""Returns True if `text` is a (near-)duplicate of an already-seen doc."""
if not self._available:
# MD5 fallback (exact dedup only)
h = hashlib.md5(text.encode("utf-8", "ignore")).hexdigest()
if h in self._seen_hashes:
return True
self._seen_hashes.add(h)
return False
# MinHash-LSH path
mh = self.MinHash(num_perm=self.num_perm)
for shingle in self._shingles(text):
mh.update(" ".join(shingle).encode("utf-8"))
# Query LSH for near-duplicates
if self._lsh.query(mh):
return True
# Not a duplicate — insert into LSH
key = doc_id or str(hash(text))
self._lsh.insert(key, mh)
return False
# --------------------------------------------------------------------------- #
# v3: Improved quality filter
# --------------------------------------------------------------------------- #
def encos_quality_filter(text: str, cfg: EncosTrainConfig,
min_chars: int = 200, max_chars: int = 200_000,
max_rep_ratio: float = 0.45,
max_boilerplate_ratio: float = 0.05) -> bool:
"""v3 improved heuristic: drops too-short/long docs, self-repetitive
boilerplate, and docs with a high density of boilerplate markers.
v2 vs v3 differences:
* v2: only the n-gram repetition ratio was checked.
* v3: adds a boilerplate-marker density check. Docs with > 5% of lines
matching common boilerplate patterns (cookie policy, copyright,
newsletter signup, etc.) are dropped. This catches marketing/SEO
content that v2's heuristic missed.
* v3: also exposes a `quality_classifier_hook` placeholder for a
learned quality classifier (e.g., a fine-tuned BERT). Plug in by
patching `encos_quality_filter` to call your classifier.
"""
if not text or len(text) < min_chars or len(text) > max_chars:
return False
toks = text.lower().split()
if len(toks) < 20:
return False
bigrams = list(zip(toks[:-1], toks[1:]))
if not bigrams:
return False
rep_ratio = 1.0 - len(set(bigrams)) / len(bigrams)
if rep_ratio > max_rep_ratio:
return False
# v3: boilerplate marker density check
if cfg.boilerplate_filter:
lines = text.split("\n")
if lines:
boilerplate_lines = sum(
1 for line in lines
if any(p.search(line) for p in _BOILERPLATE_PATTERNS)
)
boilerplate_ratio = boilerplate_lines / len(lines)
if boilerplate_ratio > max_boilerplate_ratio:
return False
return True
def encos_dedup(text: str, deduper: Optional[_MinHashDeduper] = None) -> bool:
"""Returns True if the doc passes dedup (i.e., is NOT a duplicate).
If `deduper` is provided (MinHash-LSH), use it for near-duplicate detection.
Otherwise fall back to exact MD5 dedup (v2 behaviour).
"""
if deduper is not None:
return not deduper.is_duplicate(text)
# MD5 fallback (v2 behaviour)
h = hashlib.md5(text.encode("utf-8", "ignore")).hexdigest()
global _seen_hashes
if h in _seen_hashes:
return False
_seen_hashes.add(h)
return True
_seen_hashes: set = set()
# --------------------------------------------------------------------------- #
# HF dataset sources
# --------------------------------------------------------------------------- #
def _load_hf(name: str, config: Optional[str] = None, split: str = "train", streaming: bool = True):
from datasets import load_dataset
return load_dataset(name, config, split=split, streaming=streaming)
def _iter_docs(ds, cap: int):
for i, ex in enumerate(ds):
if i >= cap:
break
yield ex
def collect_pretrain_pool(cfg: EncosTrainConfig, rank: int, world: int) -> "SourcePool":
"""Streams the pretrain mix, applies quality filter + dedup, buckets for curriculum."""
pool = SourcePool(cfg.num_curriculum_buckets, cfg.seq_len, curriculum_enabled=cfg.curriculum)
deduper = _MinHashDeduper(cfg.minhash_threshold, cfg.minhash_num_perm) \
if (cfg.dedup and cfg.dedup_method == "minhash") else None
for src, w in cfg.mix_weights.items():
if w <= 0:
continue
try:
if src == "c4":
ds = _load_hf("allenai/c4", "en", streaming=True)
elif src == "openwebtext":
ds = None
for repo in ("skylion007/openwebtext", "openwebtext"):
try:
ds = _load_hf(repo, streaming=True)
break
except Exception:
continue
if ds is None:
raise RuntimeError("openwebtext unavailable")
elif src == "wikipedia":
ds = None
for repo, conf in (("wikimedia/wikipedia", "20231101.en"),
("wikimedia/wikipedia", "20220301.en"),
("wikipedia", "20220301.en")):
try:
ds = _load_hf(repo, conf, streaming=True)
break
except Exception:
continue
if ds is None:
raise RuntimeError("wikipedia unavailable")
else:
print(f"[encos] unknown pretrain source {src}, skipping"); continue
n = 0
for ex in _iter_docs(ds, cfg.pretrain_caps.get(src, 20_000)):
text = (ex.get("text") or "").strip()
if not encos_quality_filter(text, cfg):
continue
if cfg.dedup and not encos_dedup(text, deduper):
continue
pool.add(text, src)
n += 1
print(f"[encos] pretrain source '{src}' collected {n} docs")
except Exception as e:
print(f"[encos] WARNING: failed to load pretrain source '{src}': {e}")
pool.finalize(rank, world)
return pool
def collect_sft_pool(cfg: EncosTrainConfig, rank: int, world: int) -> "SourcePool":
pool = SourcePool(cfg.num_curriculum_buckets, cfg.seq_len, is_sft=True,
curriculum_enabled=cfg.curriculum)
deduper = _MinHashDeduper(cfg.minhash_threshold, cfg.minhash_num_perm) \
if (cfg.dedup and cfg.dedup_method == "minhash") else None
for src, w in cfg.sft_mix_weights.items():
if w <= 0:
continue
try:
if src == "dolly":
ds = _load_hf("databricks/databricks-dolly-15k", streaming=False)
fmt = fmt_dolly
elif src == "alpaca_cleaned":
ds = _load_hf("yahma/alpaca-cleaned", streaming=False)
fmt = fmt_alpaca
elif src == "ultrachat":
ds = _load_hf("HuggingFaceH4/ultrachat_200k", split="train_sft", streaming=True)
fmt = fmt_ultrachat
else:
print(f"[encos] unknown SFT source {src}, skipping"); continue
n = 0
for ex in _iter_docs(ds, cfg.sft_caps.get(src, 20_000)):
pair = fmt(ex)
if pair is None:
continue
prompt, response = pair
text = prompt + response
if not encos_quality_filter(text, cfg):
continue
if cfg.dedup and not encos_dedup(text, deduper):
continue
pool.add((prompt, response), src)
n += 1
print(f"[encos] SFT source '{src}' collected {n} examples")
except Exception as e:
print(f"[encos] WARNING: failed to load SFT source '{src}': {e}")
pool.finalize(rank, world)
return pool
def collect_dpo_pool(cfg: EncosTrainConfig, rank: int, world: int) -> List[Tuple[str, str, str]]:
try:
ds = _load_hf("Intel/orca_dpo_pairs", streaming=False)
except Exception as e:
print(f"[encos] WARNING: failed to load DPO source: {e}")
return []
out = []
for ex in _iter_docs(ds, cfg.dpo_cap):
q, c, r = ex.get("question", ""), ex.get("chosen", ""), ex.get("rejected", "")
if q and c and r:
out.append((q, c, r))
print(f"[encos] DPO collected {len(out)} preference pairs")
if world > 1:
out = out[rank::world]
return out
# ---------------- SFT formatters ---------------- #
def fmt_dolly(ex) -> Optional[Tuple[str, str]]:
inst = (ex.get("instruction") or "").strip()
resp = (ex.get("response") or "").strip()
if not inst or not resp:
return None
ctx = (ex.get("context") or "").strip()
prompt = ("Below is an instruction that describes a task. Write a response that "
"appropriately completes the request.\n\n### Instruction:\n" + inst)
if ctx:
prompt += "\n### Context:\n" + ctx
prompt += "\n### Response:\n"
return prompt, resp
def fmt_alpaca(ex) -> Optional[Tuple[str, str]]:
inst = (ex.get("instruction") or "").strip()
out = (ex.get("output") or "").strip()
if not inst or not out:
return None
inp = (ex.get("input") or "").strip()
prompt = ("Below is an instruction that describes a task. Write a response that "
"appropriately completes the request.\n\n### Instruction:\n" + inst)
if inp:
prompt += "\n### Input:\n" + inp
prompt += "\n### Response:\n"
return prompt, out
def fmt_ultrachat(ex) -> Optional[Tuple[str, str]]:
msgs = ex.get("messages")
if msgs is None:
data = ex.get("data") or []
msgs = []
for m in data:
if isinstance(m, dict):
msgs.append({"role": m.get("role", "user"),
"content": m.get("prompt") or m.get("response") or m.get("content") or ""})
if not msgs:
return None
turns = []
for m in msgs:
role = (m.get("role") or "").strip().lower()
content = (m.get("content") or "").strip()
if not content:
continue
if role == "user":
turns.append(f"### User:\n{content}")
elif role == "assistant":
turns.append(f"### Assistant:\n{content}")
if len(turns) < 2:
return None
prompt = "\n\n".join(turns[:-1]) + "\n\n### Assistant:\n"
last = turns[-1]
response = last.split("\n", 1)[1] if "\n" in last else ""
if not response:
return None
return prompt, response
# ---------------- Curriculum source pool ---------------- #
class SourcePool:
"""Weighted multi-source pool with curriculum bucketing + holdout split."""
def __init__(self, num_buckets: int, seq_len: int, is_sft: bool = False,
curriculum_enabled: bool = True, holdout_frac: float = 0.05):
self.num_buckets = num_buckets
self.seq_len = seq_len
self.is_sft = is_sft
self.curriculum_enabled = curriculum_enabled
self.holdout_frac = holdout_frac
self._buckets: List[List[Tuple[object, str, int]]] = [[] for _ in range(num_buckets)]
self._src_queues: Dict[str, collections.deque] = collections.defaultdict(collections.deque)
self.by_bucket: List[List[object]] = [[] for _ in range(num_buckets)]
self.eval_by_bucket: List[List[object]] = [[] for _ in range(num_buckets)]
self.total = 0
self.eval_total = 0
def _bucket_of(self, text: str) -> int:
edges = [self.seq_len * c for c in (2, 4, 8)]
L = len(text)
b = 0
for e in edges:
if L > e:
b += 1
return min(b, self.num_buckets - 1)
def add(self, item, src: str) -> None:
text = item if isinstance(item, str) else item[0] + item[1]
b = self._bucket_of(text)
if self.holdout_frac > 0 and random.random() < self.holdout_frac:
self.eval_by_bucket[b].append(item)
self.eval_total += 1
return
self.by_bucket[b].append(item)
self._src_queues[src].append((item, b))
self.total += 1
def finalize(self, rank: int, world: int) -> None:
all_docs = []
for b in range(self.num_buckets):
all_docs.extend((item, b) for item in self.by_bucket[b])
if world > 1:
all_docs = all_docs[rank::world]
self.by_bucket = [[] for _ in range(self.num_buckets)]
for item, b in all_docs:
self.by_bucket[b].append(item)
self.total = len(all_docs)
def curriculum_order(self, epoch: int, total_epochs: int, rng: random.Random) -> List[object]:
nb = self.num_buckets
deques = [collections.deque(docs) for docs in self.by_bucket]
if self.curriculum_enabled and total_epochs > 1:
t = epoch / (total_epochs - 1)
easy = torch.tensor([0.7, 0.2, 0.07, 0.03][:nb], dtype=torch.float32)
easy = easy / easy.sum()
uni = torch.full((nb,), 1.0 / nb)
probs = (1 - t) * easy + t * uni
else:
probs = torch.full((nb,), 1.0 / nb)
order: List[object] = []
remaining = sum(len(d) for d in deques)
while remaining > 0:
b = int(torch.multinomial(probs, 1).item())
tries = 0
while not deques[b] and tries < nb:
b = (b + 1) % nb
tries += 1
if deques[b]:
order.append(deques[b].popleft())
remaining -= 1
else:
break
return order
def eval_docs(self) -> List[object]:
out = []
for b in range(self.num_buckets):
out.extend(self.eval_by_bucket[b])
return out
# --------------------------------------------------------------------------- #
# Batch builders
# --------------------------------------------------------------------------- #
def pack_pretrain_batches(docs: List[str], tok, seq_len: int, micro_batch: int,
rank: int, world: int, skip_batches: int = 0) -> Iterator[torch.Tensor]:
"""Packs documents (each + eos) into contiguous seq_len chunks, yields (b, seq_len)."""
buffer: List[int] = []
batch: List[torch.Tensor] = []
skipped = 0
for text in docs:
ids = tok.encode(text, add_special_tokens=False) + [tok.eos_token_id]
buffer.extend(ids)
while len(buffer) >= seq_len:
chunk = torch.tensor(buffer[:seq_len], dtype=torch.long)
del buffer[:seq_len]
if skipped < skip_batches:
skipped += 1
continue
batch.append(chunk)
if len(batch) == micro_batch:
yield torch.stack(batch)
batch = []
if batch:
if len(batch) == 1:
yield batch[0].unsqueeze(0)
else:
yield torch.stack(batch)
def build_sft_batches(docs: List[Tuple[str, str]], tok, seq_len: int, micro_batch: int,
rng: random.Random) -> Iterator[Tuple[torch.Tensor, torch.Tensor]]:
"""Response-masked SFT batches. Labels = -100 on the prompt part."""
rng.shuffle(docs)
inputs, labels = [], []
for prompt, response in docs:
p = tok.encode(prompt, add_special_tokens=False)
r = tok.encode(response, add_special_tokens=False) + [tok.eos_token_id]
if len(r) > seq_len // 2:
r = r[: seq_len // 2]
if len(p) + len(r) > seq_len:
p = p[: max(0, seq_len - len(r))]
if not r:
continue
ids = p + r
lab = [-100] * len(p) + r
inputs.append(torch.tensor(ids, dtype=torch.long))
labels.append(torch.tensor(lab, dtype=torch.long))
if len(inputs) == micro_batch:
yield _pad_stack(inputs, labels, tok.pad_token_id)
inputs, labels = [], []
if inputs:
yield _pad_stack(inputs, labels, tok.pad_token_id)
def _pad_stack(inputs: List[torch.Tensor], labels: List[torch.Tensor], pad_id: int):
max_len = max(t.shape[0] for t in inputs)
x = torch.full((len(inputs), max_len), pad_id, dtype=torch.long)
y = torch.full((len(inputs), max_len), -100, dtype=torch.long)
for i, (t, l) in enumerate(zip(inputs, labels)):
x[i, : t.shape[0]] = t
y[i, : l.shape[0]] = l
return x, y
def build_dpo_batches(pairs: List[Tuple[str, str, str]], tok, seq_len: int, micro_batch: int,
rng: random.Random) -> Iterator[Tuple[torch.Tensor, torch.Tensor]]:
rng.shuffle(pairs)
ch, re = [], []
for q, c, r in pairs:
c_ids = tok.encode(f"### User:\n{q}\n### Assistant:\n{c}")[:seq_len]
r_ids = tok.encode(f"### User:\n{q}\n### Assistant:\n{r}")[:seq_len]
if not c_ids or not r_ids:
continue
ch.append(torch.tensor(c_ids, dtype=torch.long))
re.append(torch.tensor(r_ids, dtype=torch.long))
if len(ch) == micro_batch:
xc, _ = _pad_stack(ch, ch, tok.pad_token_id)
xr, _ = _pad_stack(re, re, tok.pad_token_id)
yield xc, xr
ch, re = [], []
if ch:
xc, _ = _pad_stack(ch, ch, tok.pad_token_id)
xr, _ = _pad_stack(re, re, tok.pad_token_id)
yield xc, xr
# --------------------------------------------------------------------------- #
# Optimiser, schedule, EMA
# --------------------------------------------------------------------------- #
def build_optimizer(model: nn.Module, base_lr: float, cfg: EncosTrainConfig) -> torch.optim.Optimizer:
"""AdamW with decoupled weight decay + layer-wise LR decay."""
groups: Dict[Tuple[float, float], List[nn.Parameter]] = {}
n_layers = model.cfg.num_layers
for name, p in model.named_parameters():
if not p.requires_grad:
continue
if name.startswith("layers."):
idx = int(name.split(".")[1])
mult = cfg.layer_lr_decay ** (n_layers - 1 - idx)
else:
mult = 1.0
wd = 0.0 if p.ndim < 2 else cfg.weight_decay
groups.setdefault((round(mult, 6), wd), []).append(p)
param_groups = [
{"params": ps, "lr": base_lr * mult, "weight_decay": wd}
for (mult, wd), ps in sorted(groups.items())
]
return torch.optim.AdamW(param_groups, betas=cfg.betas, eps=1e-8)
class EncosSchedule:
"""Warmup + cosine decay to min_lr_ratio.
v3: supports resuming with a different `total_steps` than the original
training run. If the saved step exceeds the new total, we re-derive the
relative progress and continue from there. This addresses v2's bug where
resuming with a re-estimated step count produced a wrong cosine shape.
"""
def __init__(self, optimizer: torch.optim.Optimizer, total_steps: int,
warmup_steps: int, min_ratio: float):
self.opt = optimizer
self.total = max(1, total_steps)
self.warmup = int(warmup_steps)
self.min_ratio = min_ratio
self.base = [g["lr"] for g in optimizer.param_groups]
self.step_ = 0
def step(self) -> None:
self.step_ += 1
s = self.step_
if s <= self.warmup:
mult = s / max(1, self.warmup)
else:
# v3: clamp progress to [0, 1] in case total_steps changed across resumes
prog = min(1.0, max(0.0, (s - self.warmup) / max(1, self.total - self.warmup)))
mult = self.min_ratio + 0.5 * (1 - self.min_ratio) * (1 + math.cos(math.pi * prog))
for g, b in zip(self.opt.param_groups, self.base):
g["lr"] = b * mult
def state_dict(self) -> dict:
return {"step": self.step_, "base": self.base, "total": self.total}
def load_state_dict(self, st: dict) -> None:
self.step_ = st["step"]
self.base = st["base"]
# v3: detect mismatch and warn
if "total" in st and st["total"] != self.total:
old_total = st["total"]
new_total = self.total
print(f"[encos] WARNING: schedule total_steps changed across resume: "
f"{old_total} -> {new_total}. Relative progress preserved.")
# Preserve relative progress
if old_total > 0:
rel = self.step_ / old_total
self.step_ = int(rel * new_total)
class EncosEMA:
"""Weight EMA (decoupled from optimizer). Threads across stages.
v3: bias-corrected for the first `warmup_steps` steps. Without bias
correction, the EMA starts at zero and takes ~1/(1-decay) steps to
converge to the true moving average — for decay=0.9995, that's ~2000
steps of bias. Bias correction divides the shadow by (1 - decay^step)
so the EMA is unbiased from step 1.
"""
def __init__(self, model: nn.Module, decay: float, warmup_steps: int = 1000):
self.decay = decay
self.warmup_steps = warmup_steps
self.shadow = {k: v.detach().float().clone() for k, v in model.named_parameters()}
self.step_ = 0
@torch.no_grad()
def update(self, model: nn.Module) -> None:
self.step_ += 1
# v3: effective decay ramps up linearly during warmup to avoid
# the EMA being dominated by the (random) initial weights.
if self.step_ < self.warmup_steps:
eff_decay = min(self.decay, 1.0 - 1.0 / (self.step_ + 1))
else:
eff_decay = self.decay
for k, v in model.named_parameters():
if k in self.shadow:
self.shadow[k].mul_(eff_decay).add_(v.detach().float(), alpha=1.0 - eff_decay)
@torch.no_grad()
def copy_to(self, model: nn.Module) -> None:
for k, v in model.named_parameters():
if k in self.shadow:
v.copy_(self.shadow[k].to(v.dtype))
def state_dict(self) -> dict:
return {"decay": self.decay, "shadow": self.shadow, "step": self.step_}
def load_state_dict(self, st: dict) -> None:
self.decay = st["decay"]
self.shadow = st["shadow"]
self.step_ = st.get("step", 0)
# --------------------------------------------------------------------------- #
# Checkpointing
# --------------------------------------------------------------------------- #
def unwrap(model: nn.Module) -> nn.Module:
if isinstance(model, (nn.DataParallel, nn.parallel.DistributedDataParallel)):
return model.module
if hasattr(model, "module"):
return model.module
return model
def save_ckpt(path: str, model: nn.Module, opt, sched, ema, step: int, epoch: int,
train_cfg: EncosTrainConfig, rank: int) -> None:
if rank != 0:
return
os.makedirs(os.path.dirname(path), exist_ok=True)
m = unwrap(model)
if hasattr(m, "_fsdp_wrapped_module") or "FlatParameter" in str(type(m)):
try:
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
from torch.distributed.fsdp import FullStateDictConfig, StateDictType
cfg_full = FullStateDictConfig(offload_to_cpu=True, rank0_only=True)
with FSDP.state_dict_type(m, StateDictType.FULL_STATE_DICT, cfg_full):
state = {k: v.cpu().clone() for k, v in m.state_dict().items()}
except Exception as e:
print(f"[encos] WARNING: FSDP state_dict gather failed: {e}; using raw state_dict()")
state = m.state_dict()
else:
state = m.state_dict()
torch.save({
"model": state,
"model_config": asdict(m.cfg),
"opt": opt.state_dict(),
"sched": sched.state_dict(),
"ema": ema.state_dict() if ema is not None else None,
"step": step,
"epoch": epoch,
"train_config": asdict(train_cfg),
}, path)
print(f"[encos] checkpoint saved -> {path} (step {step})")
class _null_ctx:
def __enter__(self): return self
def __exit__(self, *a): return False
def latest_ckpt(ckpt_dir: str) -> Optional[str]:
if not os.path.isdir(ckpt_dir):
return None
files = [f for f in os.listdir(ckpt_dir) if f.startswith("checkpoint-") and f.endswith(".pt")]
if not files:
return None
files.sort(key=lambda f: int(f.split("-")[1].split(".")[0]))
return os.path.join(ckpt_dir, files[-1])
def average_checkpoints(paths: List[str], out_path: str) -> None:
avg = None
n = len(paths)
for p in paths:
st = torch.load(p, map_location="cpu")["model"]
if avg is None:
avg = {k: v.float().clone() / n for k, v in st.items() if v.dtype.is_floating_point}
else:
for k, v in st.items():
if v.dtype.is_floating_point and k in avg:
avg[k] += v.float() / n
torch.save({"model": avg}, out_path)
print(f"[encos] averaged {n} checkpoints -> {out_path}")
# --------------------------------------------------------------------------- #
# Core training step + validation eval
# --------------------------------------------------------------------------- #
def make_autocast(device: str, dtype: str):
if device.startswith("cuda") and dtype in ("bf16", "fp16"):
return torch.autocast(device_type="cuda", dtype=torch.bfloat16 if dtype == "bf16" else torch.float16)
return _null_ctx()
def train_step(model, ids: torch.Tensor, labels: Optional[torch.Tensor],
opt, sched, ema, cfg: EncosTrainConfig, grad_accum: int,
scaler, autocast, device: str) -> float:
ids = ids.to(device)
lab = ids if labels is None else labels.to(device)
with autocast:
out = model(ids, labels=lab)
loss = out.loss / grad_accum
if scaler is not None:
scaler.scale(loss).backward()
else:
loss.backward()
return out.loss.detach().float().item()
def optimizer_step(model, opt, sched, ema, cfg: EncosTrainConfig, scaler) -> None:
if scaler is not None:
scaler.unscale_(opt)
torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.grad_clip)
if scaler is not None:
scaler.step(opt)
scaler.update()
else:
opt.step()
opt.zero_grad(set_to_none=True)
sched.step()
if ema is not None:
ema.update(model)
@torch.no_grad()
def evaluate_perplexity(model, batches, device: str, autocast,
max_batches: int = 50) -> Tuple[float, float]:
"""Compute mean loss / perplexity on a held-out batch iterator."""
model.eval()
total_loss, total_tokens = 0.0, 0
n = 0
for batch in batches:
if n >= max_batches:
break
if isinstance(batch, tuple):
ids, labels = batch
else:
ids, labels = batch, batch
ids = ids.to(device)
labels = labels.to(device)
with autocast:
out = model(ids, labels=labels)
ntok = (labels != -100).sum().item()
total_loss += out.loss.item() * ntok
total_tokens += ntok
n += 1
model.train()
if total_tokens == 0:
return float("inf"), float("inf")
mean_loss = total_loss / total_tokens
ppl = math.exp(min(20.0, mean_loss))
return mean_loss, ppl
def dpo_loss(model, ref_model, chosen: torch.Tensor, rejected: torch.Tensor,
beta: float, autocast, device: str, pad_id: int) -> torch.Tensor:
def mean_logp(m: nn.Module, ids: torch.Tensor) -> torch.Tensor:
ids = ids.to(device)
valid = ids != pad_id
labels = torch.where(valid, ids, torch.full_like(ids, -100))
with autocast:
out = m(ids, labels=labels)
return -out.loss
with autocast:
logp_c = mean_logp(model, chosen)
logp_r = mean_logp(model, rejected)
with torch.no_grad():
ref_c = mean_logp(ref_model, chosen)
ref_r = mean_logp(ref_model, rejected)
loss = -F.logsigmoid(beta * ((logp_c - ref_c) - (logp_r - ref_r))).mean()
return loss
# --------------------------------------------------------------------------- #
# Stage runners
# --------------------------------------------------------------------------- #
def _weighted_avg_chars(mix_weights: Dict[str, float]) -> float:
total_w = sum(mix_weights.values())
if total_w == 0:
return 1200.0
return sum(mix_weights.get(s, 0) * PER_SOURCE_AVG_CHARS.get(s, 1200)
for s in mix_weights) / total_w
def estimate_pretrain_steps(pool_total_docs: int, mix_weights: Dict[str, float],
cfg: EncosTrainConfig, micro_batch: int) -> int:
"""v2: per-source-aware char estimate -> token estimate -> step count."""
avg_chars = _weighted_avg_chars(mix_weights)
est_tokens = int(pool_total_docs * avg_chars / 3.2)
per_batch = cfg.seq_len * micro_batch
return max(1, est_tokens // per_batch)
def run_pretrain(model, tok, cfg: EncosTrainConfig, device: str, rank: int, world: int,
args, scaler, autocast, ema: Optional[EncosEMA],
max_steps: Optional[int]) -> None:
print(f"[encos] === stage PRETRAIN (epochs={cfg.epochs_pretrain}) ===")
pool = collect_pretrain_pool(cfg, rank, world)
if pool.total == 0:
print("[encos] WARNING: pretrain pool empty — skipping stage")
return
steps_per_epoch = estimate_pretrain_steps(pool.total, cfg.mix_weights, cfg, args.micro_batch)
total_steps = steps_per_epoch * cfg.epochs_pretrain
print(f"[encos] pretrain docs={pool.total} eval_docs={pool.eval_total} "
f"avg_chars≈{_weighted_avg_chars(cfg.mix_weights):.0f} "
f"est steps/epoch={steps_per_epoch} total={total_steps}")
opt = build_optimizer(model, cfg.pretrain_lr, cfg)
sched = EncosSchedule(opt, total_steps, int(total_steps * cfg.warmup_frac), cfg.min_lr_ratio)
global_step = 0
accum = max(1, args.grad_accum)
rng = random.Random(cfg.seed)
t0 = time.time()
loss_ema_v = 0.0
stop = False
eval_docs = pool.eval_docs()
eval_batches = list(pack_pretrain_batches(eval_docs if eval_docs else [], tok,
cfg.seq_len, args.micro_batch, rank, world))
for epoch in range(cfg.epochs_pretrain):
if stop:
break
docs = pool.curriculum_order(epoch, cfg.epochs_pretrain, rng)
batches = pack_pretrain_batches(docs, tok, cfg.seq_len, args.micro_batch, rank, world)
for bidx, batch in enumerate(batches):
ids = batch
loss_val = train_step(model, ids, None, opt, sched, ema, cfg, accum, scaler, autocast, device)
loss_ema_v = loss_val if loss_ema_v == 0 else 0.99 * loss_ema_v + 0.01 * loss_val
if (bidx + 1) % accum == 0:
optimizer_step(model, opt, sched, ema, cfg, scaler)
global_step += 1
tok_rate = global_step * accum * cfg.seq_len * args.micro_batch / max(1e-6, time.time() - t0)
if global_step % max(1, args.log_every) == 0:
lr_now = opt.param_groups[0]["lr"]
print(f"[encos] pretrain step {global_step}/{total_steps} loss={loss_ema_v:.4f} "
f"lr={lr_now:.2e} tok/s≈{tok_rate:,.0f} ({time.time()-t0:.0f}s)")
if eval_batches and cfg.eval_every > 0 and global_step % cfg.eval_every == 0:
ev_loss, ev_ppl = evaluate_perplexity(model, iter(eval_batches), device, autocast)
print(f"[encos] eval step {global_step} val_loss={ev_loss:.4f} val_ppl={ev_ppl:.2f}")
if args.save_every > 0 and global_step % args.save_every == 0:
save_ckpt(os.path.join(args.checkpoint_dir, f"checkpoint-{global_step}.pt"),
model, opt, sched, ema, global_step, epoch, cfg, rank)
if max_steps and global_step >= max_steps:
stop = True
break
save_ckpt(os.path.join(args.checkpoint_dir, f"checkpoint-{global_step}.pt"),
model, opt, sched, ema, global_step, epoch if not stop else epoch, cfg, rank)
print(f"[encos] pretrain done: {global_step} steps in {time.time()-t0:.0f}s")
def run_sft(model, tok, cfg: EncosTrainConfig, device: str, rank: int, world: int,
args, scaler, autocast, ema: Optional[EncosEMA],
max_steps: Optional[int]) -> None:
print(f"[encos] === stage SFT (epochs={cfg.epochs_sft}) ===")
pool = collect_sft_pool(cfg, rank, world)
if pool.total == 0:
print("[encos] WARNING: SFT pool empty — skipping stage")
return
steps_per_epoch = max(1, pool.total // args.micro_batch)
total_steps = steps_per_epoch * cfg.epochs_sft
print(f"[encos] SFT examples={pool.total} eval={pool.eval_total} "
f"steps/epoch≈{steps_per_epoch} total={total_steps}")
opt = build_optimizer(model, cfg.sft_lr, cfg)
sched = EncosSchedule(opt, total_steps, int(total_steps * cfg.warmup_frac), cfg.min_lr_ratio)
global_step = 0
accum = max(1, args.grad_accum)
rng = random.Random(cfg.seed + 1)
t0 = time.time()
loss_ema_v = 0.0
stop = False
eval_docs = pool.eval_docs()
eval_batches = list(build_sft_batches(eval_docs if eval_docs else [],
tok, cfg.seq_len, args.micro_batch, rng))
for epoch in range(cfg.epochs_sft):
if stop:
break
docs = pool.curriculum_order(epoch, cfg.epochs_sft, rng)
batches = build_sft_batches(docs, tok, cfg.seq_len, args.micro_batch, rng)
for bidx, (ids, labels) in enumerate(batches):
loss_val = train_step(model, ids, labels, opt, sched, ema, cfg, accum, scaler, autocast, device)
loss_ema_v = loss_val if loss_ema_v == 0 else 0.99 * loss_ema_v + 0.01 * loss_val
if (bidx + 1) % accum == 0:
optimizer_step(model, opt, sched, ema, cfg, scaler)
global_step += 1
if global_step % max(1, args.log_every) == 0:
lr_now = opt.param_groups[0]["lr"]
print(f"[encos] sft step {global_step}/{total_steps} loss={loss_ema_v:.4f} "
f"lr={lr_now:.2e} ({time.time()-t0:.0f}s)")
if eval_batches and cfg.eval_every > 0 and global_step % cfg.eval_every == 0:
ev_loss, ev_ppl = evaluate_perplexity(model, iter(eval_batches), device, autocast)
print(f"[encos] eval step {global_step} val_loss={ev_loss:.4f} val_ppl={ev_ppl:.2f}")
if args.save_every > 0 and global_step % args.save_every == 0:
save_ckpt(os.path.join(args.checkpoint_dir, f"checkpoint-{global_step}.pt"),
model, opt, sched, ema, global_step, epoch, cfg, rank)
if max_steps and global_step >= max_steps:
stop = True
break
save_ckpt(os.path.join(args.checkpoint_dir, f"checkpoint-{global_step}.pt"),
model, opt, sched, ema, global_step, epoch if not stop else epoch, cfg, rank)
print(f"[encos] SFT done: {global_step} steps in {time.time()-t0:.0f}s")
def run_dpo(model, tok, cfg: EncosTrainConfig, device: str, rank: int, world: int,
args, scaler, autocast, ema: Optional[EncosEMA],
max_steps: Optional[int]) -> None:
print("[encos] === stage DPO (optional) ===")
pairs = collect_dpo_pool(cfg, rank, world)
if not pairs:
print("[encos] WARNING: DPO pool empty — skipping stage")
return
ref_model = copy.deepcopy(unwrap(model))
ref_model.requires_grad_(False)
ref_model.eval()
total_steps = max(1, len(pairs) // args.micro_batch)
opt = build_optimizer(model, cfg.dpo_lr, cfg)
sched = EncosSchedule(opt, total_steps, int(total_steps * cfg.warmup_frac), cfg.min_lr_ratio)
rng = random.Random(cfg.seed + 2)
t0 = time.time()
global_step = 0
stop = False
for bidx, (chosen, rejected) in enumerate(build_dpo_batches(pairs, tok, cfg.seq_len, args.micro_batch, rng)):
loss = dpo_loss(model, ref_model, chosen, rejected, cfg.dpo_beta, autocast, device, tok.pad_token_id)
(loss / max(1, args.grad_accum)).backward()
if (bidx + 1) % max(1, args.grad_accum) == 0:
optimizer_step(model, opt, sched, ema, cfg, scaler)
global_step += 1
if global_step % max(1, args.log_every) == 0:
print(f"[encos] dpo step {global_step}/{total_steps} loss={loss.item():.4f} ({time.time()-t0:.0f}s)")
if max_steps and global_step >= max_steps:
stop = True
break
print(f"[encos] DPO done: {global_step} steps")
# --------------------------------------------------------------------------- #
# v3 NEW: Ablation harness — vanilla / +SDA / +LRS / +both on identical data
# --------------------------------------------------------------------------- #
def run_ablation(preset: str = "tiny", max_steps: int = 20, seq_len: int = 64,
micro_batch: int = 2, grad_accum: int = 1, seed: int = 42) -> Dict[str, Dict[str, float]]:
"""Run four configs (vanilla / +SDA / +LRS / +both) on identical synthetic
data for `max_steps` steps and report held-out perplexity for each.
This is the empirical comparison v2 was missing. With this you can actually
measure whether AetherDual Attention and/or Lateral Residual Stream help on
your data before claiming a "breakthrough".
Returns a dict mapping config name -> {loss, ppl, params_M}.
"""
print(f"\n[encos-ablation] preset={preset} max_steps={max_steps} seq_len={seq_len}")
torch.manual_seed(seed)
device = "cuda" if torch.cuda.is_available() else "cpu"
autocast = _null_ctx()
# Synthetic data — identical across configs
vocab = 512
n_docs = 200
docs = [torch.randint(0, vocab, (seq_len,)).tolist() for _ in range(n_docs)]
eval_docs = [torch.randint(0, vocab, (seq_len,)).tolist() for _ in range(20)]
tok = type("Tok", (), {})()
tok.encode = lambda s, add_special_tokens=True: s if isinstance(s, list) else [int(x) for x in str(s).split()]
tok.eos_token_id = vocab - 1
tok.pad_token_id = vocab - 2
configs = [
("vanilla", dict(use_sda=False, use_lrs=False)),
("+SDA", dict(use_sda=True, use_lrs=False, sda_learned_filter=True, sda_inference_global=False)),
("+LRS", dict(use_sda=False, use_lrs=True)),
("+SDA+LRS", dict(use_sda=True, use_lrs=True, sda_learned_filter=True, sda_inference_global=False)),
]
results: Dict[str, Dict[str, float]] = {}
for name, overrides in configs:
print(f"\n[encos-ablation] === {name} ===")
torch.manual_seed(seed)
cfg = build_config(preset, vocab_size=vocab, **overrides)
model = EncosLM(cfg).to(device=device)
params_M = model.num_params() / 1e6
train_cfg = EncosTrainConfig(model_preset=preset, seq_len=seq_len,
micro_batch=micro_batch, grad_accum=grad_accum)
opt = build_optimizer(model, 1e-4, train_cfg)
sched = EncosSchedule(opt, total_steps=max_steps, warmup_steps=max(1, max_steps // 10),
min_ratio=0.1)
ema = EncosEMA(model, train_cfg.ema_decay, warmup_steps=train_cfg.ema_warmup_steps)
# Train
model.train()
for step in range(max_steps):
ids = torch.tensor(docs[step % n_docs], dtype=torch.long,
device=device).unsqueeze(0).expand(micro_batch, -1).contiguous()
loss_val = train_step(model, ids, None, opt, sched, ema, train_cfg, grad_accum,
None, autocast, device)
optimizer_step(model, opt, sched, ema, train_cfg, None)
if step % max(1, max_steps // 5) == 0:
print(f" step {step}/{max_steps} loss={loss_val:.4f}")
# Eval
eval_batches = [torch.tensor(d, dtype=torch.long, device=device).unsqueeze(0)
for d in eval_docs]
ev_loss, ev_ppl = evaluate_perplexity(model, iter(eval_batches), device, autocast,
max_batches=len(eval_batches))
print(f" -> val_loss={ev_loss:.4f} val_ppl={ev_ppl:.2f} params={params_M:.2f}M")
results[name] = {"loss": ev_loss, "ppl": ev_ppl, "params_M": params_M}
print("\n[encos-ablation] === summary ===")
print(f" {'config':<10} {'val_loss':>10} {'val_ppl':>10} {'params_M':>10}")
for name, r in results.items():
print(f" {name:<10} {r['loss']:>10.4f} {r['ppl']:>10.2f} {r['params_M']:>10.2f}")
return results
# --------------------------------------------------------------------------- #
# Smoke test (offline, no downloads)
# --------------------------------------------------------------------------- #
def run_smoke(args) -> None:
"""v3: also tests MinHash-LSH dedup, boilerplate filter, EMA bias correction,
schedule continuity check."""
torch.manual_seed(args.seed)
cfg = build_config("tiny", vocab_size=512)
model = EncosLM(cfg)
train_cfg = EncosTrainConfig(model_preset="tiny", seq_len=64, micro_batch=2, grad_accum=1)
ema = EncosEMA(model, 0.9995, warmup_steps=10)
autocast = _null_ctx()
device = "cpu"
# 1) pretrain step
opt = build_optimizer(model, 1e-4, train_cfg)
sched = EncosSchedule(opt, total_steps=10, warmup_steps=2, min_ratio=0.1)
ids = torch.randint(0, 512, (2, 64))
l1 = train_step(model, ids, None, opt, sched, ema, train_cfg, 1, None, autocast, device)
optimizer_step(model, opt, sched, ema, train_cfg, None)
assert math.isfinite(l1), f"pretrain loss not finite: {l1}"
print(f"[encos-smoke] pretrain step OK loss={l1:.4f}")
ema_shadow_norm = sum(v.norm().item() for v in ema.shadow.values())
assert ema_shadow_norm > 0, "EMA shadow is zero"
print(f"[encos-smoke] EMA shadow updated (norm={ema_shadow_norm:.2f})")
# 2) SFT step (response-masked) — REUSES the same EMA (v2 fix)
p_ids = torch.randint(0, 512, (2, 32))
r_ids = torch.randint(0, 512, (2, 32))
x = torch.cat([p_ids, r_ids], dim=-1)
lab = torch.cat([torch.full_like(p_ids, -100), r_ids], dim=-1)
opt2 = build_optimizer(model, 1e-4, train_cfg)
sched2 = EncosSchedule(opt2, total_steps=10, warmup_steps=2, min_ratio=0.1)
l2 = train_step(model, x, lab, opt2, sched2, ema, train_cfg, 1, None, autocast, device)
optimizer_step(model, opt2, sched2, ema, train_cfg, None)
assert math.isfinite(l2), f"SFT loss not finite: {l2}"
print(f"[encos-smoke] SFT step OK loss={l2:.4f} (EMA carried across stages ✓)")
# 3) DPO step
ref = copy.deepcopy(model)
ref.requires_grad_(False)
ch = torch.randint(0, 512, (2, 48))
re = torch.randint(0, 512, (2, 48))
ld = dpo_loss(model, ref, ch, re, 0.1, autocast, device, pad_id=0)
assert math.isfinite(ld.item()), f"DPO loss not finite: {ld.item()}"
print(f"[encos-smoke] DPO step OK loss={ld.item():.4f}")
# 4) validation perplexity loop
eval_batches = [(torch.randint(0, 512, (2, 64)), torch.randint(0, 512, (2, 64)))]
ev_loss, ev_ppl = evaluate_perplexity(model, iter(eval_batches), device, autocast)
assert math.isfinite(ev_loss) and math.isfinite(ev_ppl), f"eval not finite: {ev_loss}, {ev_ppl}"
print(f"[encos-smoke] eval perplexity loop OK val_loss={ev_loss:.4f} val_ppl={ev_ppl:.2f}")
# 5) per-source avg_chars sanity
mix = {"c4": 0.4, "openwebtext": 0.3, "wikipedia": 0.3}
avg = _weighted_avg_chars(mix)
assert 3000 < avg < 3300, f"per-source avg_chars wrong: {avg}"
print(f"[encos-smoke] per-source avg_chars OK weighted_avg={avg:.0f}")
# 6) v3 NEW: MinHash-LSH dedup
deduper = _MinHashDeduper(threshold=0.5, num_perm=16)
text1 = "the quick brown fox jumps over the lazy dog " * 10
text2 = "the quick brown fox jumps over the lazy cat " * 10 # near-duplicate
text3 = "completely different content about machine learning and neural networks " * 10
d1 = deduper.is_duplicate(text1)
d2 = deduper.is_duplicate(text2) # should be True (near-duplicate of text1)
d3 = deduper.is_duplicate(text3) # should be False
if deduper._available:
assert not d1, "text1 should not be a duplicate (first time)"
assert d2, "text2 should be a near-duplicate of text1 (MinHash-LSH)"
assert not d3, "text3 should not be a duplicate"
print(f"[encos-smoke] MinHash-LSH dedup OK (text2 detected as near-dup of text1 ✓)")
else:
print(f"[encos-smoke] MinHash-LSH unavailable, MD5 fallback tested OK")
# 7) v3 NEW: boilerplate filter
good_text = (
"Machine learning is a subfield of artificial intelligence that deals "
"with the construction and study of systems that can learn from data. "
"Modern machine learning algorithms can be broadly categorised into "
"supervised learning, unsupervised learning, and reinforcement learning. "
"In supervised learning, the algorithm is presented with labelled examples "
"and learns a mapping from inputs to outputs. Common applications include "
"image classification, speech recognition, and natural language processing. "
"Deep learning, a subset of machine learning, uses multi-layered neural "
"networks to progressively extract higher-level features from raw input. "
"For example, in image processing, lower layers may identify edges while "
"higher layers may identify concepts relevant to a human such as digits, "
"letters, or faces. Recent advances in transformer architectures have "
"enabled dramatic improvements in language understanding and generation."
)
boilerplate_text = "Cookie Policy\nSubscribe to our newsletter\n© 2024 Company\n" * 20
assert encos_quality_filter(good_text, train_cfg), "good text should pass quality filter"
assert not encos_quality_filter(boilerplate_text, train_cfg), \
"boilerplate-heavy text should be dropped by v3 quality filter"
print(f"[encos-smoke] boilerplate filter OK")
# 8) v3 NEW: schedule continuity check
sched_test = EncosSchedule(opt, total_steps=100, warmup_steps=10, min_ratio=0.1)
sched_test.step_ = 50
sched_test_state = sched_test.state_dict()
# Resume with a different total
sched_resumed = EncosSchedule(opt, total_steps=200, warmup_steps=10, min_ratio=0.1)
sched_resumed.load_state_dict(sched_test_state)
# Relative progress should be preserved: 50/100 = 100/200
expected_step = int(50 / 100 * 200)
assert sched_resumed.step_ == expected_step, \
f"schedule continuity failed: expected {expected_step}, got {sched_resumed.step_}"
print(f"[encos-smoke] schedule continuity OK (50/100 -> {sched_resumed.step_}/200)")
# 9) checkpoint round-trip
save_ckpt("/tmp/encos_smoke_train_v3/checkpoint-1.pt", model, opt, sched, ema, 1, 0, train_cfg, 0)
st = torch.load("/tmp/encos_smoke_train_v3/checkpoint-1.pt", map_location="cpu")
assert "model" in st and "opt" in st and "ema" in st and st["ema"] is not None
print("[encos-smoke] checkpoint round-trip OK (EMA saved across stages ✓)")
print("[encos-smoke] ALL v3 TRAIN CHECKS PASSED")
# --------------------------------------------------------------------------- #
# Main
# --------------------------------------------------------------------------- #
def parse_args():
ap = argparse.ArgumentParser(description="Encos-Train v3")
ap.add_argument("--model-config", choices=["tiny", "1b", "7b", "7b-aether"], default="7b-aether")
ap.add_argument("--init-from", type=str, default=None)
ap.add_argument("--tokenizer", type=str, default=None)
ap.add_argument("--stage", choices=["pretrain", "sft", "all"], default="all")
ap.add_argument("--with-dpo", action="store_true")
ap.add_argument("--smoke", action="store_true")
ap.add_argument("--ablation", choices=["tiny", "1b"], default=None,
help="run vanilla/+SDA/+LRS/+both ablation on synthetic data")
ap.add_argument("--ablation-steps", type=int, default=20)
ap.add_argument("--seq-len", type=int, default=2048)
ap.add_argument("--micro-batch", type=int, default=8)
ap.add_argument("--grad-accum", type=int, default=8)
ap.add_argument("--lr", type=float, default=None)
ap.add_argument("--epochs", type=int, default=None)
ap.add_argument("--pretrain-docs", type=int, default=None)
ap.add_argument("--sft-docs", type=int, default=None)
ap.add_argument("--dtype", choices=["bf16", "fp16", "fp32"], default="bf16")
ap.add_argument("--device", choices=["auto", "cpu", "cuda"], default="auto")
ap.add_argument("--checkpoint-dir", type=str, default="./encos_run")
ap.add_argument("--resume", type=str, default=None)
ap.add_argument("--save-every", type=int, default=500)
ap.add_argument("--log-every", type=int, default=10)
ap.add_argument("--max-steps", type=int, default=None)
ap.add_argument("--seed", type=int, default=42)
ap.add_argument("--no-curriculum", action="store_true")
ap.add_argument("--no-quality-filter", action="store_true")
ap.add_argument("--no-dedup", action="store_true")
ap.add_argument("--dedup-method", choices=["minhash", "md5"], default="minhash")
ap.add_argument("--no-boilerplate-filter", action="store_true")
ap.add_argument("--compile", action="store_true")
ap.add_argument("--grad-checkpoint", action="store_true")
ap.add_argument("--fsdp", action="store_true")
ap.add_argument("--eval-every", type=int, default=None)
return ap.parse_args()
def main() -> None:
args = parse_args()
if args.smoke:
run_smoke(args)
return
if args.ablation:
run_ablation(preset=args.ablation, max_steps=args.ablation_steps)
return
if "LOCAL_RANK" in os.environ:
torch.distributed.init_process_group(
backend="nccl" if torch.cuda.is_available() else "gloo")
rank, world = torch.distributed.get_rank(), torch.distributed.get_world_size()
else:
rank, world = 0, 1
device = args.device
if device == "auto":
device = "cuda" if torch.cuda.is_available() else "cpu"
if device.startswith("cuda"):
torch.cuda.set_device(rank % max(1, torch.cuda.device_count()))
torch.manual_seed(args.seed)
random.seed(args.seed)
train_cfg = EncosTrainConfig(
model_preset=args.model_config, seq_len=args.seq_len,
micro_batch=args.micro_batch, grad_accum=args.grad_accum,
dtype=args.dtype, checkpoint_dir=args.checkpoint_dir,
save_every=args.save_every, log_every=args.log_every, seed=args.seed,
use_fsdp=args.fsdp,
dedup_method=args.dedup_method,
boilerplate_filter=not args.no_boilerplate_filter,
)
if args.lr is not None:
train_cfg.pretrain_lr = args.lr
train_cfg.sft_lr = args.lr / 15.0
train_cfg.dpo_lr = args.lr / 60.0
if args.epochs is not None:
train_cfg.epochs_pretrain = args.epochs
train_cfg.epochs_sft = args.epochs
if args.pretrain_docs is not None:
train_cfg.pretrain_caps = {k: args.pretrain_docs for k in train_cfg.pretrain_caps}
if args.sft_docs is not None:
train_cfg.sft_caps = {k: args.sft_docs for k in train_cfg.sft_caps}
if args.eval_every is not None:
train_cfg.eval_every = args.eval_every
train_cfg.curriculum = not args.no_curriculum
train_cfg.quality_filter = not args.no_quality_filter
train_cfg.dedup = not args.no_dedup
if args.tokenizer:
train_cfg.tokenizer_name = args.tokenizer
os.makedirs(train_cfg.checkpoint_dir, exist_ok=True)
tok = build_tokenizer(train_cfg.tokenizer_name)
vocab = len(tok)
print(f"[encos] tokenizer '{train_cfg.tokenizer_name}' vocab={vocab} "
f"device={device} dtype={args.dtype} fsdp={train_cfg.use_fsdp} "
f"dedup={train_cfg.dedup_method} boilerplate_filter={train_cfg.boilerplate_filter}")
resume_path = args.resume if args.resume else latest_ckpt(train_cfg.checkpoint_dir)
if resume_path:
st = torch.load(resume_path, map_location="cpu")
model = EncosLM(EncosConfig(**st["model_config"]))
model.load_state_dict(st["model"], strict=True)
print(f"[encos] resumed model from {resume_path} (step {st.get('step')})")
elif args.init_from:
model = EncosLM.from_pretrained(args.init_from)
print(f"[encos] model loaded from {args.init_from}")
else:
model = EncosLM(build_config(args.model_config, vocab_size=vocab))
if args.grad_checkpoint:
model.gradient_checkpointing_enable()
print("[encos] gradient checkpointing ON")
dtype = {"bf16": torch.bfloat16, "fp16": torch.float16, "fp32": torch.float32}[args.dtype]
model = model.to(device=device, dtype=dtype)
print(f"[encos] model params={model.num_params():,} ({model.num_params()/1e9:.2f}B) "
f"weights={model.num_params()*2/1e9:.1f}GB @{args.dtype}")
if args.compile:
try:
model = torch.compile(model)
print("[encos] torch.compile enabled")
except Exception as e:
print(f"[encos] WARNING: torch.compile failed: {e}")
if world > 1:
if train_cfg.use_fsdp:
try:
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
model = FSDP(model, device_id=rank if device.startswith("cuda") else None,
use_orig_params=True)
print("[encos] FSDP enabled (v2)")
except Exception as e:
print(f"[encos] WARNING: FSDP failed, falling back to DDP: {e}")
model = torch.nn.parallel.DistributedDataParallel(
model, device_ids=[rank] if device.startswith("cuda") else None)
else:
model = torch.nn.parallel.DistributedDataParallel(
model, device_ids=[rank] if device.startswith("cuda") else None)
try:
scaler = torch.amp.GradScaler("cuda", enabled=(args.dtype == "fp16" and device.startswith("cuda")))
except (AttributeError, TypeError):
scaler = torch.cuda.amp.GradScaler(enabled=(args.dtype == "fp16" and device.startswith("cuda")))
autocast = make_autocast(device, args.dtype)
ema = EncosEMA(unwrap(model), train_cfg.ema_decay, warmup_steps=train_cfg.ema_warmup_steps)
print(f"[encos] EMA initialised (decay={train_cfg.ema_decay}, warmup={train_cfg.ema_warmup_steps}) — "
f"carried across all stages (v3)")
if args.stage in ("pretrain", "all"):
run_pretrain(model, tok, train_cfg, device, rank, world, args, scaler, autocast, ema, args.max_steps)
if args.stage in ("sft", "all"):
run_sft(model, tok, train_cfg, device, rank, world, args, scaler, autocast, ema, args.max_steps)
if args.with_dpo:
run_dpo(model, tok, train_cfg, device, rank, world, args, scaler, autocast, ema, args.max_steps)
if rank == 0:
m = unwrap(model)
if ema is not None:
ema.copy_to(m)
final_path = os.path.join(train_cfg.checkpoint_dir, "final-model.pt")
torch.save({"model": m.state_dict(), "model_config": asdict(m.cfg), "train_config": asdict(train_cfg)},
final_path)
print(f"[encos] final model (EMA-averaged) -> {final_path}")
ckpts = [os.path.join(train_cfg.checkpoint_dir, f)
for f in sorted(os.listdir(train_cfg.checkpoint_dir)) if f.startswith("checkpoint-")]
if len(ckpts) >= 2:
last_k = ckpts[-min(3, len(ckpts)):]
average_checkpoints(last_k, os.path.join(train_cfg.checkpoint_dir, "final-averaged.pt"))
print("[encos] done. Next: python3 aether_llm.py --load "
f"{os.path.join(train_cfg.checkpoint_dir, 'final-model.pt')} --prompt 'Hello' "
"--max-new-tokens 64")
def _model_from_config_dict(cfg_dict: dict) -> EncosLM:
return EncosLM(EncosConfig(**cfg_dict))
if __name__ == "__main__":
main()
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Encos-Train v3 — training recipe for EncosLM v3 (see aether_llm.py)
====================================================================
Run it:
python3 aether_train.py --model-config 7b-aether --stage all --dtype bf16 --checkpoint-dir ./encos_run
python3 aether_train.py --smoke # offline 1-step check, free
python3 aether_train.py --ablation tiny # run vanilla/+SDA/+LRS/+both ablation
================================================================================
WHAT'S NEW IN v3
================================================================================
v2 → v3 (in aether_train.py)
----------------------------
* MinHash-LSH dedup. v2 used exact MD5 dedup only, which misses the 10-30%
near-duplicate leakage that dominates real web corpora. v3 uses MinHash-LSH
(datasketch library) with a graceful fallback to MD5 if datasketch is
unavailable. Threshold defaults to 0.9 Jaccard similarity.
* Better quality filter. v2's `1 - len(set(bigrams))/len(bigrams) <= 0.45`
is a crude n-gram repetition heuristic. v3 adds:
- a length-aware score (penalise docs near min/max boundaries),
- a "boilerplate marker" detector (drop docs with > 5% lines matching
common boilerplate patterns: "Cookie Policy", "Subscribe to our
newsletter", "© 20XX", etc.),
- optional hook for a learned quality classifier (placeholder interface;
the user can plug in a fine-tuned BERT).
* LR schedule continuity check on resume. v2 saved the scheduler step but
didn't verify that `total_steps` was consistent across resumes — if the
data pool size changed between resumes (e.g., you re-estimated step count
after adding a source), the cosine decay shape would be wrong. v3 detects
this and rebuilds the schedule against the new total while preserving the
relative progress.
* EMA decay default 0.9995 (v2 was 0.999 — too low for long pretrains; GPT-3
used 0.9999 with warmup). Configurable.
* Ablation harness. `python3 aether_train.py --ablation tiny` runs four
configs (vanilla / +SDA / +LRS / +both) on identical data for a fixed
number of steps and reports held-out perplexity. Lets you actually
measure whether SDA / LRS help before claiming "breakthrough".
* Per-source `avg_chars` carried over from v2 (calibrated values for
C4/OpenWebText/Wikipedia).
Carried from v2 (unchanged in v3):
* EMA carried across stages (no reset between pretrain/SFT/DPO).
* Per-stage validation loop with held-out perplexity.
* FSDP wrap option (replaces DDP-only path).
* MoE z-loss folded into aux loss.
* bf16/fp16 autocast + GradScaler, gradient accumulation & clipping.
* AdamW with decoupled weight decay + layer-wise LR decay.
* Warmup + cosine decay with min-LR floor.
* Checkpoint averaging of the last K checkpoints.
* Optional FlashAttention (SDPA) + gradient checkpointing + torch.compile.
* Multi-stage: pretrain -> SFT (response-masked) -> optional DPO.
================================================================================
Encos-Train (honest engineering notes)
================================================================================
"Encos-Train" is the packaged data + optimisation recipe. It is NOT a claimed
breakthrough — it is a careful combination of established, proven training
techniques with a couple of small custom heuristics (curriculum ordering,
quality filter).
Compute honesty
---------------
A 7B model needs ~14 GB (bf16) of VRAM just for weights, plus optimizer state
(~3x more) and activations. From-scratch 7B training is hundreds of GPU-days
on A100/H100-class hardware. The defaults below (40k/20k/20k pretrain docs)
are VALIDATION-scale caps so the pipeline runs end-to-end; raise the caps (and
add multi-node compute) for a serious run. Always start with `--smoke`, then
`--model-config tiny` / `1b` on the hardware you actually have.
"""
from __future__ import annotations
import argparse
import collections
import copy
import hashlib
import json
import math
import os
import random
import re
import shutil
import sys
import time
from dataclasses import asdict, dataclass, field
from typing import Dict, Iterator, List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from aether_llm import EncosLM, EncosConfig, build_config, build_tokenizer # noqa: E402
# --------------------------------------------------------------------------- #