Download trainer_source/train.py from GRIMIAI-VNAnhdev/GROMAIVN: direct link, hf CLI and curl.
- Browser
- Download file 65.1 kB
-
https://huggingface.co/datasets/GRIMIAI-VNAnhdev/GROMAIVN/resolve/main/trainer_source/train.py
- Command line
-
hf download hf://datasets/GRIMIAI-VNAnhdev/GROMAIVN/trainer_source/train.py
-
curl -L -o train.py https://huggingface.co/datasets/GRIMIAI-VNAnhdev/GROMAIVN/resolve/main/trainer_source/train.py
65.1 kB
"""
GromGPT — train.py
Chế độ train bình thường (data/train.txt):
py train.py
Chế độ incremental parquet (tải từng file → train → xóa → tiếp):
- Thêm "parquet_urls" vào config.json (danh sách URL parquet HuggingFace)
- Mỗi file được tải về (~250MB), tokenize, train STEPS step, rồi XÓA NGAY
- Disk dùng tối đa = 1 file parquet (~250MB) + model/checkpoint
- Tiến độ (file nào đã train xong) lưu vào parquet_progress.json
- Nếu bị ngắt giữa chừng, chạy lại sẽ bỏ qua các file đã xong và tiếp tục
file đang dang dở từ step checkpoint cuối
Checkpoint/resume hoạt động bình thường xuyên suốt toàn bộ quá trình.
"""
import json
import math
import random
import os
import shutil
import subprocess
import sys
import time
from pathlib import Path
from grom_runtime import (
ROOT, CFG as BASE_CFG, load_config, training_config, print_runtime_status,
verify_manifest, dataset_fingerprint, h100_profile, dataset_roots, low_resource_profile,
AI_NAME, DEVELOPER_NAME, RESPONSE_MARKER,
DATA_ROOT, TRAIN_TXT, TRAIN_SHARDS_DIR, VAL_SHARDS_DIR, DATASET_MANIFEST, PICTURE_DIR,
MODEL_PATH, TOKENIZER_PATH, TOKENIZER_META_PATH, CHECKPOINT_PATH, PROGRESS_PATH,
)
CFG_PATH = ROOT / "config.json"
cfg = training_config(load_config())
HF_STREAMING = bool(cfg.get("hf_streaming", True))
HF_REPO_ID = str(cfg.get("hf_repo_id", "GRIMIAI-VNAnhdev/GROMAIVN"))
HF_REVISION = str(cfg.get("hf_revision", "main"))
HF_STREAM_CHUNK_CHARS = max(64_000, int(cfg.get("hf_stream_chunk_chars", 262_144)))
if cfg.get("force_cpu"):
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
import torch
IS_H100 = h100_profile()
IS_CPU = not torch.cuda.is_available()
from model import GromGPT
from vision import PictureDataset, make_image_turn, QUESTIONS, pretty, load_image
from tokenizer import DEFAULT_VOCAB_SIZE, Tokenizer
from curate_append_quality_v2 import HFShardDataset
DATA = TRAIN_TXT
SHARD_DIR = TRAIN_SHARDS_DIR
SHARD_MANIFEST = DATASET_MANIFEST
BUILD = ROOT / "data" / "build.py"
OUT = MODEL_PATH
CKPT = CHECKPOINT_PATH
CKPT_TMP = ROOT / "checkpoint.pt.tmp"
PARQUET_TMP = DATA_ROOT / "_parquet_tmp.parquet"
PROGRESS = PROGRESS_PATH
HF_STREAM_CURSOR = None
HF_SOURCE = HFShardDataset(repo_id=HF_REPO_ID, revision=HF_REVISION) if HF_STREAMING else None
print_runtime_status(cfg)
if HF_SOURCE is not None:
print("[HF STREAM] " + json.dumps(HF_SOURCE.summary(), ensure_ascii=False), flush=True)
VOCAB_SIZE = int(cfg.get("vocab_size", DEFAULT_VOCAB_SIZE))
LR = float(cfg.get("learning_rate", 3e-4))
DROPOUT = float(cfg.get("dropout", 0.05))
CKPT_EVERY_STEPS = int(cfg.get("checkpoint_every", 50))
CKPT_EVERY_SECS = float(cfg.get("checkpoint_every_seconds", 180))
STEPS_BASE = int(cfg.get("training_steps", 14000))
STEPS_MIN = int(cfg.get("training_steps_min", STEPS_BASE))
STEPS_UPGRADE = int(cfg.get("training_steps_upgrade", 8000))
AUTO_SCALE = bool(cfg.get("training_auto_scale", True))
TRAIN_EPOCHS = float(cfg.get("training_epochs", 1.0))
CHARS_PER_TOKEN = float(cfg.get("training_chars_per_token", 3.8))
TRAIN_HARD_MAX = int(cfg.get("training_steps_hard_max", 0) or 0)
if IS_H100 and bool(cfg.get("full_corpus_no_caps", True)):
TRAIN_HARD_MAX = 0
elif IS_CPU and cfg.get("low_resource_auto", True):
TRAIN_HARD_MAX = min(TRAIN_HARD_MAX or 8000, 8000)
def estimate_training_steps():
"""Ước lượng budget toàn cục theo quy mô dữ liệu, không tính lại theo từng shard."""
chars = int(HF_SOURCE.train_bytes) if HF_SOURCE is not None else 0
if chars <= 0 and SHARD_MANIFEST.exists():
try:
manifest = json.loads(SHARD_MANIFEST.read_text(encoding="utf-8"))
chars = int(manifest.get("actual_chars", 0) or 0)
if chars <= 0:
chars = int(manifest.get("actual_bytes", 0) or 0)
except Exception as exc:
print(f"[steps] Không đọc được shard manifest ({exc}), dùng fallback.")
if chars <= 0 and DATA.exists():
chars += DATA.stat().st_size
dialogue = ROOT / "data" / "data" / "dialogue_dedup.jsonl"
if chars <= 0 and dialogue.exists():
chars += dialogue.stat().st_size
if chars <= 0:
for item in cfg.get("external_datasets", []):
try:
chars += int(item.get("limit_chars", 0) or 0)
except (TypeError, ValueError):
pass
tokens = max(1, int(chars / max(1.0, CHARS_PER_TOKEN)))
denom = max(1, BATCH * BLOCK)
auto_steps = math.ceil(tokens * max(0.1, TRAIN_EPOCHS) / denom)
target = max(STEPS_MIN, auto_steps) if AUTO_SCALE else STEPS_BASE
if TRAIN_HARD_MAX > 0:
target = min(target, TRAIN_HARD_MAX)
print(f"[steps] chars≈{chars:,} tokens≈{tokens:,} -> target={target:,} (base={STEPS_BASE:,}, upgrade={STEPS_UPGRADE:,}, hard_max={TRAIN_HARD_MAX or 'none'})")
return target
STEPS_TARGET = 0
# --- Nhánh ảnh (đọc data/picture/). Tắt bằng "vision": false trong config.json ---
VISION_ON = bool(cfg.get("vision", True)) and HF_SOURCE is None
if IS_H100 and HF_SOURCE is None:
VISION_ON = True
if HF_SOURCE is not None:
print("[HF STREAM] Remote images are listed but this train.py pass is text-only; no local image folders are scanned.")
IMG_SIZE = int(cfg.get("img_size", 224))
IMG_PATCH = int(cfg.get("img_patch", 16))
IMG_VIT_DIM = int(cfg.get("img_vit_dim", 384))
IMG_VIT_LAYERS = int(cfg.get("img_vit_layers", 6))
IMG_VIT_HEADS = int(cfg.get("img_vit_heads", 6))
IMG_TOKENS = int(cfg.get("img_tokens", 16))
IMG_BATCH = int(cfg.get("img_batch_size", 32))
IMG_EVERY = int(cfg.get("img_every", 2)) # cứ N step văn bản thì có 1 step ảnh
PARQUET_URLS: list[str] = [] if IS_H100 else list(cfg.get("parquet_urls", []))
if not PARQUET_URLS and not IS_H100:
# Chỉ các nguồn được khai báo rõ là format=parquet mới đi vào
# incremental pipeline. Nguồn raw_text phải qua data/build.py và
# trở thành corpus chính, không được khiến data/train.txt bị bỏ qua.
PARQUET_URLS = [
str(item.get("url")) for item in cfg.get("external_datasets", [])
if item.get("url")
and str(item.get("format", "")).lower() == "parquet"
and str(item.get("url")).lower().split("?")[0].endswith(".parquet")
]
if (ROOT / "data" / "data" / "dialogue_dedup.jsonl").exists() and cfg.get("train_dialogue_incremental", False):
# Chỉ đưa dialogue_dedup vào incremental khi người dùng bật rõ ràng.
PARQUET_URLS = ["local://dialogue_dedup.jsonl"] + PARQUET_URLS
# ---------------------------------------------------------------------------
# Colab: mount Google Drive
# ---------------------------------------------------------------------------
def setup_drive_ckpt_dir():
try:
import google.colab # noqa: F401
except ImportError:
return None
try:
from google.colab import drive as _drive
mount_point = Path("/content/drive")
if not (mount_point / "MyDrive").exists():
print("[colab] Đang mount Google Drive...")
_drive.mount(str(mount_point))
drive_dir = mount_point / "MyDrive" / "GROM_Mini_ckpt"
drive_dir.mkdir(parents=True, exist_ok=True)
print(f"[colab] Checkpoint sao lưu vào: {drive_dir}")
return drive_dir
except Exception as e:
print(f"[colab] Không mount được Drive ({e}), chỉ lưu local.")
return None
DRIVE_DIR = setup_drive_ckpt_dir()
DRIVE_CKPT = (DRIVE_DIR / "checkpoint.pt") if DRIVE_DIR else None
DRIVE_TOKENIZER = (DRIVE_DIR / "tokenizer.json") if DRIVE_DIR else None
DRIVE_OUT = (DRIVE_DIR / "grom_mini.pt") if DRIVE_DIR else None
DRIVE_PROGRESS = (DRIVE_DIR / "parquet_progress.json") if DRIVE_DIR else None
# ---------------------------------------------------------------------------
# Corpus thường (khi không dùng parquet_urls)
# ---------------------------------------------------------------------------
def ensure_corpus():
"""Build local corpus only when HF streaming has explicitly been disabled."""
if HF_SOURCE is not None:
print("[dataset] HF canonical corpus is already built remotely; local build skipped.")
return
if IS_H100:
full_builder = ROOT / "build_full_dataset_h100.py"
if not full_builder.exists():
raise RuntimeError("Thiếu build_full_dataset_h100.py cho H100 full-corpus mode.")
needs_full = True
if SHARD_MANIFEST.exists():
try:
manifest = json.loads(SHARD_MANIFEST.read_text(encoding="utf-8"))
needs_full = manifest.get("training_mode") != "full_corpus_h100_v1"
except Exception:
needs_full = True
if needs_full:
print("[dataset] H100 full-corpus mode -> quét TOÀN BỘ dữ liệu trainable, không giới hạn dung lượng.")
subprocess.run([sys.executable, str(full_builder)], cwd=str(ROOT), check=True)
verify_manifest(require_dedup=True, require_validation=True)
return
if SHARD_MANIFEST.exists():
try:
current = json.loads(SHARD_MANIFEST.read_text(encoding="utf-8"))
if current.get("training_mode") == "clean_unique_corpus":
verify_manifest(require_dedup=True, require_validation=True)
print("[dataset] Clean 13 GiB manifest verified.")
return
except Exception:
pass
canonical_builder = ROOT / "build_dataset_dedup_v5.js"
node = shutil.which("node") or (r"D:\node.exe" if Path(r"D:\node.exe").exists() else None)
if canonical_builder.exists() and node:
print("[dataset] Chạy canonical builder record-level dedup...")
subprocess.run([node, str(canonical_builder)], cwd=str(ROOT), check=True)
verify_manifest(require_dedup=True, require_validation=True)
return
clean_builder = ROOT / "build_clean_13gb.py"
if clean_builder.exists():
if low_resource_profile() and cfg.get("low_resource_auto", True) and not cfg.get("allow_heavy_dataset_build_cpu", False):
raise RuntimeError(
"Máy thuộc cấu hình tài nguyên thấp; train.py sẽ KHÔNG tự chạy build_clean_13gb.py "
"vì pipeline 13 GiB có thể gây thrashing/đứng máy. Hãy tạo manifest trước trên máy mạnh "
"hoặc đặt allow_heavy_dataset_build_cpu=true một cách có chủ đích."
)
print("[dataset] Building clean 13 GiB corpus...")
subprocess.run([sys.executable, str(clean_builder)], cwd=str(ROOT), check=True)
return
builder = ROOT / "build_dataset_dedup_v5.js"
node = shutil.which("node") or (r"D:\node.exe" if Path(r"D:\node.exe").exists() else None)
if builder.exists() and node:
print("[dataset] Chạy canonical builder record-level dedup...")
subprocess.run([node, str(builder)], cwd=str(ROOT), check=True)
return
raise RuntimeError(
"Canonical dataset builder unavailable. Node.js + build_dataset_dedup_v5.js are required; "
"khong fallback sang legacy data/build.py de tranh train nham dataset khac."
)
# ---------------------------------------------------------------------------
# Device
# ---------------------------------------------------------------------------
def pick_device():
if torch.cuda.is_available():
name = torch.cuda.get_device_name(0)
vram_gb = torch.cuda.get_device_properties(0).total_memory / (1024**3)
print(f"[device] GPU CUDA: {name} ({vram_gb:.1f} GB VRAM)")
return "cuda"
print("[device] Không có GPU -> dùng CPU")
return "cpu"
device = pick_device()
IS_CPU = device == "cpu"
BLOCK = int(cfg.get("block_size", 192))
BATCH = int(cfg.get("batch_size", 8))
N_EMBD = int(cfg.get("n_embd", 192))
N_HEAD = int(cfg.get("n_head", 6))
N_LAYER= int(cfg.get("n_layer", 5))
ROPE_THETA = float(cfg.get("rope_theta", 10000.0)) # theta lon (500000) -> ngu canh dai on dinh hon
GRAD_CKPT = bool(cfg.get("gradient_checkpointing", False))
from model import ARCH as MODEL_ARCH
from longctx import assistant_loss_mask, window_turn_counts, boost_starts
LONG_MIN_TURNS = int(cfg.get("long_dialogue_min_turns", 6)) # cua so co >= so luot G/AI nay = hoi thoai dai
LONG_BOOST = int(cfg.get("long_dialogue_boost", 3)) # lap hoi thoai dai them (boost-1) lan moi epoch
if IS_CPU:
if "block_size" not in cfg: BLOCK = min(BLOCK, 160)
if "batch_size" not in cfg: BATCH = min(BATCH, 6)
threads = 2 if cfg.get("low_resource_auto", True) and __import__("grom_runtime").low_resource_profile() else max(1, os.cpu_count() or 1)
torch.set_num_threads(threads)
try:
torch.set_num_interop_threads(1)
except RuntimeError:
pass
print(f"[device] CPU mode: block={BLOCK} batch={BATCH} threads={threads} interop=1")
# ---------------------------------------------------------------------------
# Tokenizer
# ---------------------------------------------------------------------------
def _tokenizer_meta_matches(fp: str) -> bool:
if not TOKENIZER_PATH.exists():
return False
if not fp:
return True
try:
meta = json.loads(TOKENIZER_META_PATH.read_text(encoding="utf-8"))
return meta.get("dataset_fingerprint") == fp and int(meta.get("vocab_size", 0)) == VOCAB_SIZE
except Exception:
return False
def _canonical_text_iterator(max_chars: int):
total = 0
manifest = json.loads(DATASET_MANIFEST.read_text(encoding="utf-8"))
for name in manifest.get("train_shards", manifest.get("shards", [])):
p = TRAIN_SHARDS_DIR / name
if not p.exists():
continue
with p.open("r", encoding="utf-8", errors="replace") as fh:
for line in fh:
if not line.strip():
continue
if max_chars > 0 and total >= max_chars:
return
remain = max_chars - total if max_chars > 0 else len(line)
chunk = line[:remain] if max_chars > 0 else line
if chunk:
total += len(chunk)
yield chunk
if max_chars > 0 and total >= max_chars:
return
def _legacy_text_iterator():
if not DATA.exists():
return
with DATA.open("r", encoding="utf-8", errors="replace") as fh:
for line in fh:
if line.strip():
yield line
def ensure_tokenizer_from_dataset() -> Tokenizer:
if HF_SOURCE is not None:
HF_SOURCE.cache_tokenizer(TOKENIZER_PATH)
tok = Tokenizer.load(TOKENIZER_PATH)
meta = {
"dataset_fingerprint": HF_SOURCE.fingerprint,
"vocab_size": len(tok),
"source": "huggingface_remote_tokenizer",
"repo_id": HF_REPO_ID,
"revision": HF_SOURCE.revision,
}
TOKENIZER_META_PATH.write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8")
print(f"[tokenizer] Loaded remote tokenizer: vocab={len(tok):,}; only tokenizer.json cached locally.")
return tok
fp = ""
if SHARD_MANIFEST.exists():
try:
manifest = verify_manifest(require_dedup=True, require_validation=True)
fp = dataset_fingerprint(manifest)
except Exception:
fp = ""
if _tokenizer_meta_matches(fp):
print(f"[tokenizer] Nạp tokenizer: {TOKENIZER_PATH}")
return Tokenizer.load(TOKENIZER_PATH)
print(f"[tokenizer] Dataset fingerprint mới -> train BPE tokenizer (vocab_size={VOCAB_SIZE})...")
cap = int(cfg.get("tokenizer_max_chars", 600_000_000))
iterator = _canonical_text_iterator(cap) if SHARD_MANIFEST.exists() else _legacy_text_iterator()
tok = Tokenizer().build_from_iterator(iterator, vocab_size=VOCAB_SIZE)
tok.save(TOKENIZER_PATH)
meta = {"dataset_fingerprint": fp, "vocab_size": len(tok), "source": "canonical_train_shards" if SHARD_MANIFEST.exists() else "legacy_train_txt"}
TOKENIZER_META_PATH.write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8")
if DRIVE_TOKENIZER:
shutil.copy2(TOKENIZER_PATH, DRIVE_TOKENIZER)
print(f"[tokenizer] Đã lưu (vocab thực tế = {len(tok)})")
return tok
# ---------------------------------------------------------------------------
# Progress (theo dõi file parquet nào đã train xong)
# ---------------------------------------------------------------------------
def load_progress() -> set[str]:
for p in ([PROGRESS] + ([DRIVE_PROGRESS] if DRIVE_PROGRESS else [])):
if p and Path(p).exists():
try:
return set(json.loads(Path(p).read_text(encoding="utf-8")))
except Exception:
pass
return set()
def save_progress(done: set[str]):
data_out = json.dumps(sorted(done), ensure_ascii=False, indent=2)
PROGRESS.write_text(data_out, encoding="utf-8")
if DRIVE_PROGRESS:
try:
shutil.copy2(PROGRESS, DRIVE_PROGRESS)
except Exception:
pass
# ---------------------------------------------------------------------------
# Tải 1 file parquet → tensor token (rồi XÓA file parquet)
# ---------------------------------------------------------------------------
def download_and_tokenize_parquet(url: str, tok: Tokenizer) -> torch.Tensor | None:
import requests
PARQUET_TMP.parent.mkdir(parents=True, exist_ok=True)
print(f" [download] {url}")
try:
with requests.get(url, stream=True, timeout=300) as r:
r.raise_for_status()
total_size = int(r.headers.get("content-length", 0))
written = 0
with open(PARQUET_TMP, "wb") as f:
for chunk in r.iter_content(chunk_size=4 * 1024 * 1024):
f.write(chunk)
written += len(chunk)
if total_size and written < total_size * 0.99:
print(f" [download] LỖI: tải thiếu {written/1024/1024:.1f}/{total_size/1024/1024:.1f} MB -> bỏ qua")
return None
print(f" [download] Xong: {written/1024/1024:.1f} MB")
import pyarrow.parquet as pq
pf = pq.ParquetFile(PARQUET_TMP)
text_parts = []
char_cap = int(cfg.get("parquet_max_chars", 20_000_000))
chars = 0
columns = pf.schema_arrow.names
print(f" [parquet] Columns: {columns} | char_cap={char_cap:,}")
PRIORITY = ["text", "content", "output", "response", "answer",
"instruction", "input", "question", "body", "passage"]
text_cols = [c for c in PRIORITY if c in columns] or list(columns)
print(f" [parquet] Dùng cột: {text_cols}")
for batch in pf.iter_batches(batch_size=1024, columns=text_cols):
rows = batch.to_pylist()
for row in rows:
vals = []
for col in text_cols:
val = row.get(col)
if val is None:
continue
s = str(val).strip()
if len(s) > 10:
vals.append(s)
if vals:
chunk = "\n".join(vals)
if chars + len(chunk) > char_cap:
remain = max(0, char_cap - chars)
if remain:
text_parts.append(chunk[:remain])
chars = char_cap
break
text_parts.append(chunk)
chars += len(chunk)
if chars >= char_cap:
break
text = "\n".join(text_parts)
if len(text) < 32:
return None
print(f" [tokenize] {len(text):,} ký tự -> tokenizing...")
tokens = torch.tensor(tok.encode(text), dtype=torch.long)
print(f" [tokenize] {len(tokens):,} tokens")
return tokens
except Exception as e:
import traceback
print(f" [parquet] Lỗi: {e}")
traceback.print_exc()
return None
finally:
if PARQUET_TMP.exists():
PARQUET_TMP.unlink()
print(f" [cleanup] Đã xóa file tạm.")
def load_local_dialogue(tok: Tokenizer) -> torch.Tensor | None:
"""Nạp hội thoại dedup theo từng dòng, chỉ giữ tensor token của lượt hiện tại."""
path = ROOT / "data" / "data" / "dialogue_dedup.jsonl"
if not path.exists():
return None
parts = []
try:
with path.open("r", encoding="utf-8", errors="replace") as f:
for line in f:
if not line.strip():
continue
try:
obj = json.loads(line)
msgs = obj.get("messages", [])
text = "\n".join(
f"{m.get('role', 'user')}: {m.get('content', '')}"
for m in msgs if isinstance(m, dict) and m.get("content")
)
if text:
parts.append(text)
except Exception:
continue
text = "\n".join(parts)
if len(text) < 32:
return None
tokens = torch.tensor(tok.encode(text), dtype=torch.long)
print(f" [dialogue] {len(parts):,} hội thoại -> {len(tokens):,} tokens")
return tokens
except Exception as e:
print(f" [dialogue] Lỗi: {e}")
return None
# ---------------------------------------------------------------------------
# Batch
# ---------------------------------------------------------------------------
_RESPONSE_MARKER_IDS: list[int] | None = None
def _find_subsequence(row: torch.Tensor, pattern: list[int]) -> int:
n = len(pattern)
if not n or n > row.numel():
return -1
r = row.tolist() # một lần chuyển sang list, thay cho hàng nghìn torch.equal
first = pattern[0]
for i in range(len(r) - n + 1):
if r[i] == first and r[i:i + n] == pattern:
return i
return -1
_ROLE_IDS = None
def _role_ids():
global _ROLE_IDS
if _ROLE_IDS is None:
_ROLE_IDS = (tok.token_to_id(RESPONSE_MARKER), tok.token_to_id("Người dùng:"))
return _ROLE_IDS
def _apply_loss_mask(x: torch.Tensor, y: torch.Tensor):
"""Che noi dung nguoi dung o MOI luot, hoc moi luot G/AI. Tra None neu tokenizer
khong co special token tuong ung (khi do dung cach cu theo marker dau tien)."""
ai, user = _role_ids()
if ai is None or user is None:
return None
return y.masked_fill(~assistant_loss_mask(x, ai, user), -100)
def get_batch(data_tensor: torch.Tensor):
hi = max(1, len(data_tensor) - BLOCK - 1)
global _RESPONSE_MARKER_IDS
if bool(cfg.get("response_only_loss", True)):
if _RESPONSE_MARKER_IDS is None:
_RESPONSE_MARKER_IDS = tok.encode(RESPONSE_MARKER)
ix_list = []
attempts = 0
while len(ix_list) < BATCH and attempts < BATCH * 5:
attempts += 1
start = int(torch.randint(0, hi, (1,)).item())
candidate = data_tensor[start:start + BLOCK]
if _RESPONSE_MARKER_IDS and _find_subsequence(candidate, _RESPONSE_MARKER_IDS) >= 0:
ix_list.append(start)
elif attempts >= BATCH * 3:
ix_list.append(start)
while len(ix_list) < BATCH:
ix_list.append(int(torch.randint(0, hi, (1,)).item()))
ix = ix_list
else:
ix = [int(v) for v in torch.randint(0, hi, (BATCH,)).tolist()]
x = torch.stack([data_tensor[i:i + BLOCK] for i in ix])
y = torch.stack([data_tensor[i + 1:i + BLOCK + 1] for i in ix])
# Keep the user prompt as context, but put most supervised weight on the
# assistant response. Pure code/text records without a response marker
# remain fully supervised.
if bool(cfg.get("response_only_loss", True)):
_turn_y = _apply_loss_mask(x, y)
if _turn_y is not None:
y = _turn_y
elif _RESPONSE_MARKER_IDS:
masked = y.clone()
for b in range(masked.size(0)):
pos = _find_subsequence(x[b], _RESPONSE_MARKER_IDS)
if pos >= 0:
# y[j] là target của x[j+1]: KHÔNG che token trả lời đầu tiên.
masked[b, :max(0, min(masked.size(1), pos + len(_RESPONSE_MARKER_IDS) - 1))] = -100
y = masked
return x.to(device), y.to(device)
class AllImagesDataset:
"""H100-only image inventory: every discovered image becomes a train sample."""
EXT = {".jpg", ".jpeg", ".png", ".bmp", ".webp", ".gif", ".tif", ".tiff"}
def __init__(self, roots, img_size: int):
self.root = Path(next(iter(roots))) if roots else PICTURE_DIR
files = []
seen = set()
excluded = {".git", "__pycache__", "train_shards", "val_shards", "checkpoints", "models"}
for root in roots:
root = Path(root)
if not root.exists():
continue
for p in root.rglob("*"):
if not p.is_file() or p.suffix.lower() not in self.EXT:
continue
if any(part.startswith(".") or part.startswith("_") or part in excluded for part in p.parts):
continue
key = str(p.resolve()).lower()
if key not in seen:
seen.add(key); files.append(p)
self.items = sorted(files)
self.img_size = img_size
self.labels = []
label_to_idx = {}
train = []
for p in self.items:
label = p.parent.name or "image"
if label not in label_to_idx:
label_to_idx[label] = len(self.labels)
self.labels.append(label)
train.append((p, label_to_idx[label]))
self.train = train
self.val = []
self.names = {}
def __len__(self):
return len(self.train)
@property
def num_labels(self):
return len(self.labels)
def display(self, idx):
return self.labels[idx].replace("_", " ")
_IMG_TEXT_CACHE: dict = {}
def _image_text_ids(tok: Tokenizer, label_idx: int, q_idx: int) -> list[int]:
"""Token của 1 mẫu hội thoại ảnh (có cache: chỉ tokenize mỗi cặp nhãn/câu hỏi 1 lần)."""
key = (label_idx, q_idx)
if key not in _IMG_TEXT_CACHE:
text = make_image_turn(QUESTIONS[q_idx], pretty(pic_ds.labels[label_idx], pic_ds.names))
_IMG_TEXT_CACHE[key] = tok.encode(text)
return _IMG_TEXT_CACHE[key]
def get_image_batch(tok: Tokenizer, split: str = "train"):
"""Trả (ảnh, x, y) cho 1 step ảnh. y = -100 ở phần câu hỏi -> loss chỉ trên câu TRẢ LỜI."""
imgs, ids = pic_ds.batch(IMG_BATCH, split=split)
max_text = BLOCK - IMG_TOKENS
seqs, ans_starts = [], []
for lab in ids.tolist():
q = random.randrange(len(QUESTIONS))
t = _image_text_ids(tok, lab, q)[: max_text + 1]
# Tokenizer BPE có thể tách "GromGPT:" thành nhiều token; tìm cả
# chuỗi token thay vì giả định đây là một token đặc biệt duy nhất.
marker = tok.encode(RESPONSE_MARKER)
start = 0
if marker:
for pos in range(0, len(t) - len(marker) + 1):
if t[pos:pos + len(marker)] == marker:
start = pos + len(marker)
break
seqs.append(t)
ans_starts.append(start)
L = max(len(t) for t in seqs) - 1
pad = tok.token_to_id("<pad>") or 0
x = torch.full((len(seqs), L), pad, dtype=torch.long)
y = torch.full((len(seqs), L), -100, dtype=torch.long)
for i, (t, st) in enumerate(zip(seqs, ans_starts)):
n = len(t) - 1
x[i, :n] = torch.tensor(t[:-1])
tgt = torch.tensor(t[1:])
tgt[: max(0, st - 1)] = -100 # che phần câu hỏi
y[i, :n] = tgt
return imgs.to(device), x.to(device), y.to(device)
def lr_at(step, total_steps):
warmup = max(50, total_steps // 20)
if step < warmup:
return LR * (step + 1) / warmup
t = min(1.0, (step - warmup) / max(1, total_steps - warmup))
return 0.1 * LR + 0.9 * LR * 0.5 * (1 + math.cos(math.pi * t))
# ---------------------------------------------------------------------------
# Checkpoint
# ---------------------------------------------------------------------------
def find_best_checkpoint():
candidates = [p for p in [CKPT, DRIVE_CKPT] if p and Path(p).exists()]
if not candidates:
return None
return max(candidates, key=lambda p: Path(p).stat().st_mtime)
def save_checkpoint(model, opt, scaler, step, tok, extra=None):
payload = {
"model": model.state_dict(),
"optimizer": opt.state_dict(),
"scaler": scaler.state_dict() if use_amp else None,
"step": step,
"arch": MODEL_ARCH,
"rope_theta": ROPE_THETA,
"vocab_size": len(tok),
"block_size": BLOCK,
"n_embd": N_EMBD,
"n_head": N_HEAD,
"n_layer": N_LAYER,
"vision": VISION_CFG,
"picture_labels": pic_ds.labels if pic_ds else None,
"picture_names": pic_ds.names if pic_ds else None,
"config": cfg,
"dataset_fingerprint": HF_SOURCE.fingerprint if HF_SOURCE is not None else (dataset_fingerprint() if SHARD_MANIFEST.exists() else ""),
}
if HF_SOURCE is not None and HF_STREAM_CURSOR is not None:
payload["hf_stream_cursor"] = dict(HF_STREAM_CURSOR)
if extra:
payload.update(extra)
torch.save(payload, CKPT_TMP)
os.replace(CKPT_TMP, CKPT)
if DRIVE_CKPT:
try:
shutil.copy2(CKPT, DRIVE_CKPT)
except Exception as e:
print(f"[ckpt] Cảnh báo Drive: {e}")
def save_final(model, tok):
payload = {
"model": model.state_dict(),
"tokenizer_file": TOKENIZER_PATH.name,
"arch": MODEL_ARCH,
"rope_theta": ROPE_THETA,
"vocab_size": len(tok),
"block_size": BLOCK,
"n_embd": N_EMBD,
"n_head": N_HEAD,
"n_layer": N_LAYER,
"vision": VISION_CFG,
"picture_labels": pic_ds.labels if pic_ds else None,
"picture_names": pic_ds.names if pic_ds else None,
"config": cfg,
"dataset_fingerprint": HF_SOURCE.fingerprint if HF_SOURCE is not None else (dataset_fingerprint() if SHARD_MANIFEST.exists() else ""),
}
torch.save(payload, OUT)
print(f"[done] Model lưu: {OUT}")
if DRIVE_OUT:
try:
shutil.copy2(OUT, DRIVE_OUT)
print(f"[done] Sao lưu Drive: {DRIVE_OUT}")
except Exception as e:
print(f"[done] Cảnh báo Drive: {e}")
# ---------------------------------------------------------------------------
# Train loop trên 1 tensor data (dùng chung cho cả 2 chế độ)
# ---------------------------------------------------------------------------
def train_on_data(model, opt, scaler, tok, data_tensor: torch.Tensor,
start_step: int, total_steps: int, file_label: str = "",
schedule_total: int | None = None):
# LR phải bám theo tổng step TOÀN CỤC; nếu chỉ dùng total_steps của từng
# shard thì từ shard thứ 2 LR gần như luôn ở mức tối thiểu.
sched_total = max(int(schedule_total or 0), total_steps)
last_ckpt_time = time.time()
last_step = start_step - 1
try:
for step in range(start_step, total_steps):
last_step = step
for g in opt.param_groups:
g["lr"] = lr_at(step, sched_total)
x, y = get_batch(data_tensor)
opt.zero_grad(set_to_none=True)
if use_amp:
with torch.amp.autocast("cuda"):
_, loss = model(x, y)
scaler.scale(loss).backward()
scaler.unscale_(opt)
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
scaler.step(opt)
scaler.update()
else:
_, loss = model(x, y)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
img_loss = None
if pic_ds is not None and IMG_EVERY > 0 and step % IMG_EVERY == 0:
imgs, xi, yi = get_image_batch(tok)
opt.zero_grad(set_to_none=True)
if use_amp:
with torch.amp.autocast("cuda"):
_, img_loss = model(xi, yi, images=imgs)
scaler.scale(img_loss).backward()
scaler.unscale_(opt)
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
scaler.step(opt)
scaler.update()
else:
_, img_loss = model(xi, yi, images=imgs)
img_loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
if step % 100 == 0 or step == total_steps - 1:
label = f" [{file_label}]" if file_label else ""
extra_txt = f" img_loss={img_loss.item():.4f}" if img_loss is not None else ""
print(f"step {step}/{total_steps}{label} loss={loss.item():.4f}{extra_txt} lr={lr_at(step, sched_total):.2e}")
due_step = CKPT_EVERY_STEPS > 0 and step % CKPT_EVERY_STEPS == 0
due_time = (time.time() - last_ckpt_time) >= CKPT_EVERY_SECS
if (due_step or due_time) and step > start_step - 1:
save_checkpoint(model, opt, scaler, step, tok)
last_ckpt_time = time.time()
except KeyboardInterrupt:
print(f"\n[interrupt] Dừng ở step {last_step}, lưu checkpoint...")
save_checkpoint(model, opt, scaler, last_step, tok)
print(f"[interrupt] Chạy lại train.py để tiếp tục.")
raise SystemExit(0)
def _masked_targets(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
global _RESPONSE_MARKER_IDS
if not bool(cfg.get("response_only_loss", True)):
return y
_turn_y = _apply_loss_mask(x, y)
if _turn_y is not None:
return _turn_y
if _RESPONSE_MARKER_IDS is None:
# Chế độ H100 không đi qua get_batch nên marker phải được tạo ở đây,
# nếu không response_only_loss bị tắt âm thầm.
_RESPONSE_MARKER_IDS = tok.encode(RESPONSE_MARKER)
if not _RESPONSE_MARKER_IDS:
return y
masked = y.clone()
for b in range(masked.size(0)):
pos = _find_subsequence(x[b], _RESPONSE_MARKER_IDS)
if pos >= 0:
masked[b, :max(0, min(masked.size(1), pos + len(_RESPONSE_MARKER_IDS) - 1))] = -100
return masked
def _pad_window(ids: torch.Tensor):
n = min(BLOCK, max(0, ids.numel() - 1))
pad_id = tok.token_to_id("<pad>") or 0
x = torch.full((BLOCK,), pad_id, dtype=torch.long)
y = torch.full((BLOCK,), -100, dtype=torch.long)
if n > 0:
x[:n] = ids[:n]
y[:n] = ids[1:n + 1]
return x, y
def train_full_text_epoch(model, opt, scaler, tok, epoch_index: int, total_epochs: int, global_step: int):
"""H100: duyệt tuần tự mọi token trong mọi train shard, không target/cap."""
manifest = json.loads(SHARD_MANIFEST.read_text(encoding="utf-8"))
shards = list(manifest.get("train_shards", manifest.get("shards", [])))
if not shards:
raise RuntimeError("Full-corpus manifest không có train shards.")
estimated = max(1, math.ceil(
(int(manifest.get("train_bytes", 0)) / max(1.0, CHARS_PER_TOKEN))
/ max(1, BLOCK * BATCH)
))
print(f"[H100 TEXT] epoch {epoch_index + 1}/{total_epochs} | shards={len(shards):,} | estimated_steps≈{estimated:,} | NO CAP")
batch_x, batch_y = [], []
seen_tokens = 0
trained_batches = 0
last_ckpt_time = time.time()
rng = random.Random(1337 + epoch_index) # seed co dinh -> tai lap duoc
shard_order = list(range(len(shards)))
rng.shuffle(shard_order) # tron thu tu shard: tranh hoc lan luot tung nguon
for shard_index, shard_pos in enumerate(shard_order):
name = shards[shard_pos]
path = SHARD_DIR / name
if not path.exists():
continue
raw = path.read_text(encoding="utf-8", errors="replace")
ids = torch.tensor(tok.encode(raw), dtype=torch.long)
seen_tokens += max(0, ids.numel() - 1)
starts = list(range(0, max(0, ids.numel() - 1), BLOCK))
_ai = tok.token_to_id(RESPONSE_MARKER)
if _ai is not None and LONG_BOOST > 1:
# Hoi thoai dai (nhieu luot G/AI trong 1 cua so) duoc lap them LONG_BOOST-1 lan.
starts = boost_starts(starts, window_turn_counts(ids, _ai, starts, BLOCK),
LONG_MIN_TURNS, LONG_BOOST)
rng.shuffle(starts) # tron cua so trong shard: batch khong con la doan lien ke
for start in starts:
xw, yw = _pad_window(ids[start:start + BLOCK + 1])
batch_x.append(xw); batch_y.append(yw)
if len(batch_x) < BATCH:
continue
x = torch.stack(batch_x).to(device)
y = _masked_targets(x, torch.stack(batch_y)).to(device)
opt.zero_grad(set_to_none=True)
with torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_amp):
_, loss = model(x, y)
if use_amp:
scaler.scale(loss).backward(); scaler.unscale_(opt)
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); scaler.step(opt); scaler.update()
else:
loss.backward(); torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); opt.step()
global_step += 1; trained_batches += 1
batch_x, batch_y = [], []
for g in opt.param_groups:
g["lr"] = lr_at(global_step, max(estimated, 1))
if trained_batches % 100 == 0:
print(f"[H100 TEXT] epoch={epoch_index + 1}/{total_epochs} shard={shard_index + 1}/{len(shards)} step={global_step:,} loss={loss.item():.4f} tokens={seen_tokens:,}")
due_step = CKPT_EVERY_STEPS > 0 and trained_batches % CKPT_EVERY_STEPS == 0
due_time = (time.time() - last_ckpt_time) >= CKPT_EVERY_SECS
if due_step or due_time:
save_checkpoint(model, opt, scaler, global_step - 1, tok,
extra={"full_corpus_cursor": {"epoch": epoch_index, "shard": shard_index}})
last_ckpt_time = time.time()
if batch_x:
x = torch.stack(batch_x).to(device)
y = _masked_targets(x, torch.stack(batch_y)).to(device)
opt.zero_grad(set_to_none=True)
with torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_amp):
_, loss = model(x, y)
if use_amp:
scaler.scale(loss).backward(); scaler.unscale_(opt)
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); scaler.step(opt); scaler.update()
else:
loss.backward(); torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); opt.step()
global_step += 1
print(f"[H100 TEXT] final_partial_batch loss={loss.item():.4f}")
print(f"[H100 TEXT] complete | actual_steps={trained_batches:,} | tokens_seen={seen_tokens:,}")
return global_step
def train_all_images_epoch(model, opt, scaler, tok, epoch_index: int, total_epochs: int, global_step: int):
if pic_ds is None or len(pic_ds.train) == 0:
print("[H100 IMAGE] Không có ảnh trainable.")
return global_step
total = len(pic_ds.train)
ok = failed = 0
print(f"[H100 IMAGE] epoch {epoch_index + 1}/{total_epochs} | images={total:,} | all images, NO CAP")
for start in range(0, total, IMG_BATCH):
items = pic_ds.train[start:start + IMG_BATCH]
imgs, texts, starts = [], [], []
for local_idx, (p, lab) in enumerate(items):
try:
imgs.append(load_image(p, IMG_SIZE, augment=True))
q_idx = (start + local_idx) % len(QUESTIONS)
text_ids = tok.encode(make_image_turn(QUESTIONS[q_idx], pretty(pic_ds.labels[lab], pic_ds.names)))
text_ids = text_ids[:BLOCK - IMG_TOKENS + 1]
marker_ids = tok.encode(RESPONSE_MARKER)
answer_start = 0
if marker_ids:
for pos in range(0, len(text_ids) - len(marker_ids) + 1):
if text_ids[pos:pos + len(marker_ids)] == marker_ids:
answer_start = pos + len(marker_ids)
break
texts.append(text_ids); starts.append(answer_start); ok += 1
except Exception as exc:
failed += 1
print(f"[H100 IMAGE] bỏ ảnh lỗi {p}: {exc}")
if not imgs:
continue
max_len = max(len(x) for x in texts) - 1
pad_id = tok.token_to_id("<pad>") or 0
xi = torch.full((len(texts), max_len), pad_id, dtype=torch.long)
yi = torch.full((len(texts), max_len), -100, dtype=torch.long)
for i, (ids, st) in enumerate(zip(texts, starts)):
n = len(ids) - 1
xi[i, :n] = torch.tensor(ids[:-1])
yy = torch.tensor(ids[1:])
yy[:max(0, st - 1)] = -100
yi[i, :n] = yy
im = torch.stack(imgs).to(device)
xi = xi.to(device); yi = yi.to(device)
opt.zero_grad(set_to_none=True)
with torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_amp):
_, loss = model(xi, yi, images=im)
if use_amp:
scaler.scale(loss).backward(); scaler.unscale_(opt)
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); scaler.step(opt); scaler.update()
else:
loss.backward(); torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); opt.step()
global_step += 1
if (start // IMG_BATCH) % 25 == 0:
print(f"[H100 IMAGE] {min(total, start + IMG_BATCH):,}/{total:,} images | step={global_step:,} loss={loss.item():.4f}")
print(f"[H100 IMAGE] complete | trained={ok:,} failed={failed:,}")
return global_step
def train_hf_remote_corpus(model, opt, scaler, tok, start_step: int, total_steps: int):
"""Train from canonical HF shards in bounded RAM chunks; no dataset files are downloaded."""
global HF_STREAM_CURSOR
if HF_SOURCE is None:
raise RuntimeError("HF streaming source is not initialized.")
entries = HF_SOURCE.train_entries
total_bytes = max(1, HF_SOURCE.train_bytes)
global_step = int(start_step)
cursor = HF_STREAM_CURSOR or {}
resume_shard = max(0, int(cursor.get("shard_index", 0)))
resume_chunk = max(0, int(cursor.get("chunk_index", 0)))
cumulative_bytes = 0
print(
f"[HF TRAIN] repo={HF_REPO_ID}@{HF_SOURCE.revision} | "
f"shards={len(entries):,} | size={total_bytes / 1024**3:.2f} GiB | "
f"steps={global_step:,}->{total_steps:,} | chunk_chars={HF_STREAM_CHUNK_CHARS:,}",
flush=True,
)
for shard_index, (repo_path, file_size) in enumerate(entries):
file_start_step = int(total_steps * cumulative_bytes / total_bytes)
cumulative_bytes += file_size
file_end_step = total_steps if shard_index == len(entries) - 1 else int(
total_steps * cumulative_bytes / total_bytes
)
if shard_index < resume_shard:
continue
if global_step >= total_steps:
break
file_budget = max(0, file_end_step - file_start_step)
if file_budget <= 0:
continue
print(
f"[HF TRAIN] shard {shard_index + 1}/{len(entries)}: "
f"{Path(repo_path).name} | {file_size / 1024**2:.1f} MiB | "
f"step-window={file_start_step}->{file_end_step}",
flush=True,
)
bytes_seen = 0
chunk_index = 0
last_tensor = None
last_chunk_index = 0
for chunk in HF_SOURCE.iter_chunks(
repo_path,
chunk_chars=HF_STREAM_CHUNK_CHARS,
):
this_chunk = chunk_index
chunk_index += 1
last_chunk_index = this_chunk
bytes_seen += max(1, len(chunk.encode("utf-8", errors="replace")))
if shard_index == resume_shard and this_chunk < resume_chunk:
continue
fraction = min(1.0, bytes_seen / max(1, file_size))
chunk_end_step = file_start_step + min(
file_budget,
int(file_budget * fraction),
)
if chunk_end_step <= global_step:
continue
token_ids = tok.encode(chunk)
if len(token_ids) < BLOCK + 2:
continue
data_tensor = torch.tensor(token_ids, dtype=torch.long)
last_tensor = data_tensor
HF_STREAM_CURSOR = {
"shard_index": shard_index,
"chunk_index": this_chunk,
"chunk_end_step": chunk_end_step,
"dataset_fingerprint": HF_SOURCE.fingerprint,
}
train_on_data(
model, opt, scaler, tok, data_tensor,
start_step=global_step,
total_steps=chunk_end_step,
file_label=Path(repo_path).name,
schedule_total=total_steps,
)
global_step = chunk_end_step
del data_tensor, token_ids
if global_step % 100 == 0 or global_step >= total_steps:
print(
f"[HF TRAIN] step={global_step:,}/{total_steps:,} "
f"shard={shard_index + 1}/{len(entries)}",
flush=True,
)
# Account for newline conversion or UTF-8 replacement differences in the final chunk.
if global_step < file_end_step and last_tensor is not None:
HF_STREAM_CURSOR = {
"shard_index": shard_index,
"chunk_index": last_chunk_index,
"chunk_end_step": file_end_step,
"dataset_fingerprint": HF_SOURCE.fingerprint,
}
train_on_data(
model, opt, scaler, tok, last_tensor,
start_step=global_step,
total_steps=file_end_step,
file_label=Path(repo_path).name,
schedule_total=total_steps,
)
global_step = file_end_step
HF_STREAM_CURSOR = {
"shard_index": shard_index + 1,
"chunk_index": 0,
"chunk_end_step": file_end_step,
"dataset_fingerprint": HF_SOURCE.fingerprint,
}
save_checkpoint(model, opt, scaler, max(0, global_step - 1), tok)
print(
f"[HF TRAIN] completed {shard_index + 1}/{len(entries)} shards "
f"| global_step={global_step:,}/{total_steps:,}",
flush=True,
)
HF_STREAM_CURSOR = {
"shard_index": len(entries),
"chunk_index": 0,
"chunk_end_step": total_steps,
"dataset_fingerprint": HF_SOURCE.fingerprint,
"complete": global_step >= total_steps,
}
save_checkpoint(model, opt, scaler, max(0, global_step - 1), tok)
print(f"[HF TRAIN] finished | steps={global_step:,}/{total_steps:,}", flush=True)
return global_step
def load_validation_tensor(tok: Tokenizer, max_chars: int = 1_500_000) -> torch.Tensor | None:
"""Load only a small deterministic validation sample to keep low-RAM machines safe."""
if HF_SOURCE is not None:
parts = []
chars = 0
for piece in HF_SOURCE.iter_text(split="validation", max_chars=max_chars, chunk_chars=HF_STREAM_CHUNK_CHARS):
parts.append(piece)
chars += len(piece)
if chars >= max_chars:
break
if chars < BLOCK + 2:
return None
ids = tok.encode("\n".join(parts))
if len(ids) < BLOCK + 2:
return None
return torch.tensor(ids, dtype=torch.long)
manifest = json.loads(SHARD_MANIFEST.read_text(encoding="utf-8"))
parts, chars = [], 0
for name in manifest.get("val_shards", []):
p = VAL_SHARDS_DIR / name
if not p.exists():
continue
with p.open("r", encoding="utf-8", errors="replace") as fh:
for line in fh:
if not line.strip():
continue
take = min(len(line), max(0, max_chars - chars))
if take:
parts.append(line[:take]); chars += take
if chars >= max_chars:
break
if chars >= max_chars:
break
if chars < BLOCK + 2:
return None
ids = tok.encode("\n".join(parts))
if len(ids) < BLOCK + 2:
return None
return torch.tensor(ids, dtype=torch.long)
@torch.no_grad()
def evaluate_validation(model, tok, max_chars: int = 1_500_000, batches: int = 12):
data_tensor = load_validation_tensor(tok, max_chars=max_chars)
if data_tensor is None:
print("[val] Không đủ validation data để đánh giá.")
return None
was_training = model.training
model.eval()
losses = []
for _ in range(max(1, batches)):
x, y = get_batch(data_tensor)
_, loss = model(x, y)
losses.append(float(loss.item()))
if was_training:
model.train()
avg = sum(losses) / len(losses)
print(f"[val] loss={avg:.4f} trên {len(losses)} batch")
return avg
# ===========================================================================
# MAIN
# ===========================================================================
# --- Dataset contract ---
if HF_SOURCE is not None:
print("[dataset] Using validated canonical HF train/validation shards; no local builder or raw-source scan.")
elif IS_H100:
ensure_corpus()
elif not PARQUET_URLS:
if SHARD_MANIFEST.exists():
try:
dm = verify_manifest(require_dedup=True, require_validation=True)
print(f"[dataset] canonical manifest v{dm.get('version')} | train={dm.get('train_bytes', dm.get('actual_bytes',0))/1024**3:.3f} GiB | val={dm.get('val_bytes',0)/1024**3:.3f} GiB")
except Exception as exc:
print(f"[dataset] Manifest không hợp lệ: {exc}")
ensure_corpus()
else:
ensure_corpus()
tok = ensure_tokenizer_from_dataset()
# --- Dữ liệu ảnh: tự bổ sung ảnh có giấy phép mở từ Wikimedia Commons ---
if HF_SOURCE is None and VISION_ON and cfg.get("image_auto_download", False) and not IS_H100:
try:
import subprocess
image_script = ROOT / "data" / "import_picture_samples.py"
if image_script.exists():
target = int(cfg.get("image_target_per_class", 100))
max_run = int(cfg.get("image_max_per_run", 100))
print(f"[picture] Bổ sung ảnh bên ngoài: target={target}/nhãn, tối đa {max_run} ảnh/lượt")
subprocess.run([
os.environ.get("PYTHON", sys.executable), str(image_script),
"--target-per-class", str(target),
"--max-images-per-run", str(max_run),
"--max-seconds", str(int(cfg.get("image_max_seconds", 300))),
], cwd=str(ROOT / "data"), check=False)
except Exception as e:
print(f"[picture] Cảnh báo: không tự nhập được ảnh ngoài ({e})")
# --- Dữ liệu ảnh (data/picture/<nhãn>/<file>) ---
pic_ds = None
VISION_CFG = None
if VISION_ON:
if IS_H100:
roots = list(dict.fromkeys([*(dataset_roots()), PICTURE_DIR]))
_ds = AllImagesDataset(roots, img_size=IMG_SIZE)
else:
_ds = PictureDataset(PICTURE_DIR, img_size=IMG_SIZE)
if _ds.num_labels > 0 and len(_ds) > 0:
pic_ds = _ds
VISION_CFG = dict(img_size=IMG_SIZE, patch_size=IMG_PATCH, vit_dim=IMG_VIT_DIM,
vit_layers=IMG_VIT_LAYERS, vit_heads=IMG_VIT_HEADS, n_img_tokens=IMG_TOKENS)
mode = "ALL DATASET IMAGES" if IS_H100 else f"từ {PICTURE_DIR}"
print(f"[picture] {pic_ds.num_labels} nhãn, {len(pic_ds.train)} ảnh train / {len(pic_ds.val)} val {mode}")
print(f"[picture] nhãn: {', '.join(pretty(l, pic_ds.names) for l in pic_ds.labels)}")
else:
print(f"[picture] Chưa có ảnh trong {PICTURE_DIR} -> chỉ train văn bản.")
else:
print("[picture] Đã tắt (config vision=false).")
# --- Khởi tạo model ---
model = GromGPT(
len(tok), BLOCK, n_embd=N_EMBD, n_head=N_HEAD, n_layer=N_LAYER, dropout=DROPOUT,
vision=VISION_CFG, rope_theta=ROPE_THETA, gradient_checkpointing=GRAD_CKPT,
).to(device)
_decay_params = [p for p in model.parameters() if p.requires_grad and p.dim() >= 2]
_nodecay_params = [p for p in model.parameters() if p.requires_grad and p.dim() < 2]
opt = torch.optim.AdamW(
[{"params": _decay_params, "weight_decay": float(cfg.get("weight_decay", 0.1))},
{"params": _nodecay_params, "weight_decay": 0.0}],
lr=LR, betas=(0.9, 0.95), fused=(device == "cuda"),
)
use_amp = device == "cuda"
if IS_H100:
torch.backends.cuda.matmul.allow_tf32 = bool(cfg.get("tf32", True))
torch.backends.cudnn.allow_tf32 = bool(cfg.get("tf32", True))
print(f"[H100] precision={cfg.get('precision', 'bf16')} tf32={cfg.get('tf32', True)}")
scaler = torch.amp.GradScaler("cuda", enabled=use_amp)
STEPS_TARGET = estimate_training_steps()
print(f"Device: {device} | Vocab: {len(tok)} | Params: {sum(p.numel() for p in model.parameters()):,}")
print(f"block={BLOCK} batch={BATCH} embd={N_EMBD} head={N_HEAD} layer={N_LAYER} target_steps={STEPS_TARGET}")
# --- Resume checkpoint ---
start_step = 0
best_ckpt = find_best_checkpoint()
if best_ckpt:
try:
ckpt = torch.load(best_ckpt, map_location=device)
current_fp = HF_SOURCE.fingerprint if HF_SOURCE is not None else (dataset_fingerprint() if SHARD_MANIFEST.exists() else "")
ok = (ckpt.get("arch") == MODEL_ARCH
and float(ckpt.get("rope_theta", 10000.0)) == ROPE_THETA
and ckpt.get("vocab_size") == len(tok)
and ckpt.get("block_size") == BLOCK
and ckpt.get("n_embd") == N_EMBD
and ckpt.get("n_head") == N_HEAD
and ckpt.get("n_layer") == N_LAYER
and ckpt.get("vision") == VISION_CFG
and (not current_fp or ckpt.get("dataset_fingerprint") == current_fp)
and (HF_SOURCE is None or isinstance(ckpt.get("hf_stream_cursor"), dict)))
if ok:
model.load_state_dict(ckpt["model"])
opt.load_state_dict(ckpt["optimizer"])
if use_amp and ckpt.get("scaler"):
scaler.load_state_dict(ckpt["scaler"])
start_step = int(ckpt.get("step", -1)) + 1
if HF_SOURCE is not None:
HF_STREAM_CURSOR = ckpt.get("hf_stream_cursor")
print(f"[resume] Tiếp tục từ step {start_step}")
else:
print("[resume] Checkpoint lệch config -> train lại từ đầu.")
except Exception as e:
print(f"[resume] Lỗi đọc checkpoint ({e}) -> train lại từ đầu.")
# ===========================================================================
# CHẾ ĐỘ HF: TRAIN TRỰC TIẾP TỪ REPOSITORY, KHÔNG TẢI DATASET VỀ MÁY
# ===========================================================================
if HF_SOURCE is not None:
global_step = train_hf_remote_corpus(
model, opt, scaler, tok,
start_step=start_step,
total_steps=STEPS_TARGET,
)
val_loss = evaluate_validation(
model, tok,
max_chars=int(cfg.get("validation_max_chars", 1_500_000)),
batches=int(cfg.get("validation_batches", 12)),
)
if val_loss is not None:
print(f"[HF VAL] final_validation_loss={val_loss:.4f}")
save_final(model, tok)
if CKPT.exists():
CKPT.unlink()
print("[HF STREAM] Removed temporary checkpoint after successful final save.")
if DRIVE_CKPT and Path(DRIVE_CKPT).exists():
Path(DRIVE_CKPT).unlink()
# ===========================================================================
# CHẾ ĐỘ H100: FULL CORPUS + FULL IMAGE PASS (LOCAL MODE)
# ===========================================================================
elif IS_H100:
total_epochs = max(1, int(math.ceil(float(cfg.get("training_epochs_h100", 1.0)))))
global_step = start_step
print("\n[H100 MODE] FULL-CORPUS: mọi shard trainable + mọi ảnh trainable; không target GiB, không hard step cap, không tokenizer cap.")
for epoch in range(total_epochs):
global_step = train_full_text_epoch(model, opt, scaler, tok, epoch, total_epochs, global_step)
global_step = train_all_images_epoch(model, opt, scaler, tok, epoch, total_epochs, global_step)
save_checkpoint(model, opt, scaler, max(0, global_step - 1), tok,
extra={"full_corpus_cursor": {"epoch": epoch, "complete": True}})
val_loss = evaluate_validation(model, tok, max_chars=int(cfg.get("validation_max_chars", 1_500_000)),
batches=int(cfg.get("validation_batches", 12)))
if val_loss is not None:
print(f"[H100 VAL] final_validation_loss={val_loss:.4f}")
save_final(model, tok)
if CKPT.exists():
CKPT.unlink()
print("[H100 MODE] Đã xoá checkpoint tạm sau khi hoàn thành full pass.")
# ===========================================================================
# CHẾ ĐỘ 1: INCREMENTAL PARQUET (parquet_urls có trong config.json)
# ===========================================================================
elif PARQUET_URLS:
done = load_progress()
total = len(PARQUET_URLS)
global_step = start_step
print(f"\n[parquet] Tổng {total} file, đã xong: {len(done)} | target toàn cục: {STEPS_TARGET:,}")
for idx, url in enumerate(PARQUET_URLS):
if url in done:
print(f"[parquet] [{idx+1}/{total}] Đã train xong, bỏ qua: {url.split('/')[-1]}")
continue
fname = url.split("/")[-1].split("?")[0]
print(f"\n[parquet] [{idx+1}/{total}] === {fname} ===")
if url == "local://dialogue_dedup.jsonl":
data_tensor = load_local_dialogue(tok)
else:
data_tensor = download_and_tokenize_parquet(url, tok)
if data_tensor is None or len(data_tensor) < BLOCK + 2:
print(f"[parquet] Bỏ qua file này (không đủ data).")
done.add(url)
save_progress(done)
continue
remaining_files = max(1, total - len(done))
file_budget = max(1, math.ceil(max(0, STEPS_TARGET - global_step) / remaining_files))
file_budget = min(file_budget, max(1, STEPS_TARGET - global_step))
print(f"[parquet] Train {file_budget} steps | global {global_step}->{global_step + file_budget} / {STEPS_TARGET:,}")
if global_step < STEPS_TARGET:
train_on_data(model, opt, scaler, tok, data_tensor,
start_step=global_step, total_steps=global_step + file_budget,
file_label=fname, schedule_total=STEPS_TARGET)
global_step += file_budget
done.add(url)
save_progress(done)
save_checkpoint(model, opt, scaler, max(0, global_step - 1), tok)
print(f"[parquet] ✓ Xong {fname} ({len(done)}/{total})")
if global_step >= STEPS_TARGET:
print(f"[parquet] Đạt target {STEPS_TARGET:,} steps; tiếp tục đánh dấu dữ liệu nhưng không train thêm.")
print(f"\n[parquet] Hoàn thành tất cả {total} file!")
save_final(model, tok)
# ===========================================================================
# CHẾ ĐỘ 2: TRAIN THƯỜNG (data/train.txt)
# ===========================================================================
else:
# Ưu tiên corpus shard 7–8 GiB. Chỉ dùng train.txt kiểu cũ khi chưa có manifest.
if SHARD_MANIFEST.exists():
manifest = json.loads(SHARD_MANIFEST.read_text(encoding="utf-8"))
shard_names = manifest.get("train_shards", manifest.get("shards", []))
if not shard_names:
raise SystemExit("Shard manifest không có shard dữ liệu.")
global_step = start_step
remaining_bytes = sum((SHARD_DIR / name).stat().st_size for name in shard_names if (SHARD_DIR / name).exists())
print(f"[shards] {len(shard_names):,} shard | {manifest.get('actual_gib', 0):.2f} GiB | target steps={STEPS_TARGET:,}")
for idx, name in enumerate(shard_names, 1):
path = SHARD_DIR / name
if not path.exists():
print(f"[shards] Bỏ qua shard thiếu: {name}")
continue
raw = path.read_text(encoding="utf-8", errors="replace")
tensor = torch.tensor(tok.encode(raw), dtype=torch.long)
if len(tensor) < BLOCK + 2:
continue
shard_bytes = path.stat().st_size
budget_left = max(0, STEPS_TARGET - global_step)
file_steps = max(1, math.ceil(budget_left * shard_bytes / max(1, remaining_bytes))) if budget_left else 0
file_steps = min(file_steps, budget_left)
print(f"[shards] [{idx}/{len(shard_names)}] {name} | {shard_bytes/1024/1024:.1f} MiB | {len(tensor):,} tokens | {file_steps} steps")
if file_steps:
train_on_data(model, opt, scaler, tok, tensor, start_step=global_step, total_steps=global_step + file_steps, file_label=name, schedule_total=STEPS_TARGET)
global_step += file_steps
remaining_bytes = max(0, remaining_bytes - shard_bytes)
if global_step >= STEPS_TARGET:
break
val_loss = evaluate_validation(model, tok, max_chars=int(cfg.get("validation_max_chars", 1_500_000)),
batches=int(cfg.get("validation_batches", 12)))
if val_loss is not None:
print(f"[val] final_validation_loss={val_loss:.4f}")
save_final(model, tok)
else:
ensure_corpus()
text = DATA.read_text(encoding="utf-8")
if not TOKENIZER_PATH.exists():
tok = ensure_tokenizer_from_dataset()
data_tensor = torch.tensor(tok.encode(text), dtype=torch.long)
if len(data_tensor) < BLOCK + 2:
raise SystemExit("Corpus quá ngắn — chạy py data/build.py trước.")
print(f"Tokens: {len(data_tensor):,} | Target steps: {STEPS_TARGET:,}")
train_on_data(model, opt, scaler, tok, data_tensor, start_step=start_step, total_steps=STEPS_TARGET)
save_final(model, tok)
if CKPT.exists():
CKPT.unlink()
print("Đã xoá checkpoint tạm.")
if DRIVE_CKPT and Path(DRIVE_CKPT).exists():
Path(DRIVE_CKPT).unlink()
"""
GromGPT — train.py
Chế độ train bình thường (data/train.txt):
py train.py
Chế độ incremental parquet (tải từng file → train → xóa → tiếp):
- Thêm "parquet_urls" vào config.json (danh sách URL parquet HuggingFace)
- Mỗi file được tải về (~250MB), tokenize, train STEPS step, rồi XÓA NGAY
- Disk dùng tối đa = 1 file parquet (~250MB) + model/checkpoint
- Tiến độ (file nào đã train xong) lưu vào parquet_progress.json
- Nếu bị ngắt giữa chừng, chạy lại sẽ bỏ qua các file đã xong và tiếp tục
file đang dang dở từ step checkpoint cuối
Checkpoint/resume hoạt động bình thường xuyên suốt toàn bộ quá trình.
"""
import json
import math
import random
import os
import shutil
import subprocess
import sys
import time
from pathlib import Path
from grom_runtime import (
ROOT, CFG as BASE_CFG, load_config, training_config, print_runtime_status,
verify_manifest, dataset_fingerprint, h100_profile, dataset_roots, low_resource_profile,
AI_NAME, DEVELOPER_NAME, RESPONSE_MARKER,
DATA_ROOT, TRAIN_TXT, TRAIN_SHARDS_DIR, VAL_SHARDS_DIR, DATASET_MANIFEST, PICTURE_DIR,
MODEL_PATH, TOKENIZER_PATH, TOKENIZER_META_PATH, CHECKPOINT_PATH, PROGRESS_PATH,
)
CFG_PATH = ROOT / "config.json"
cfg = training_config(load_config())
HF_STREAMING = bool(cfg.get("hf_streaming", True))
HF_REPO_ID = str(cfg.get("hf_repo_id", "GRIMIAI-VNAnhdev/GROMAIVN"))
HF_REVISION = str(cfg.get("hf_revision", "main"))
HF_STREAM_CHUNK_CHARS = max(64_000, int(cfg.get("hf_stream_chunk_chars", 262_144)))
if cfg.get("force_cpu"):
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
import torch
IS_H100 = h100_profile()
IS_CPU = not torch.cuda.is_available()
from model import GromGPT
from vision import PictureDataset, make_image_turn, QUESTIONS, pretty, load_image
from tokenizer import DEFAULT_VOCAB_SIZE, Tokenizer
from curate_append_quality_v2 import HFShardDataset
DATA = TRAIN_TXT
SHARD_DIR = TRAIN_SHARDS_DIR
SHARD_MANIFEST = DATASET_MANIFEST
BUILD = ROOT / "data" / "build.py"
OUT = MODEL_PATH
CKPT = CHECKPOINT_PATH
CKPT_TMP = ROOT / "checkpoint.pt.tmp"
PARQUET_TMP = DATA_ROOT / "_parquet_tmp.parquet"
PROGRESS = PROGRESS_PATH
HF_STREAM_CURSOR = None
HF_SOURCE = HFShardDataset(repo_id=HF_REPO_ID, revision=HF_REVISION) if HF_STREAMING else None
print_runtime_status(cfg)
if HF_SOURCE is not None:
print("[HF STREAM] " + json.dumps(HF_SOURCE.summary(), ensure_ascii=False), flush=True)
VOCAB_SIZE = int(cfg.get("vocab_size", DEFAULT_VOCAB_SIZE))
LR = float(cfg.get("learning_rate", 3e-4))
DROPOUT = float(cfg.get("dropout", 0.05))
CKPT_EVERY_STEPS = int(cfg.get("checkpoint_every", 50))
CKPT_EVERY_SECS = float(cfg.get("checkpoint_every_seconds", 180))
STEPS_BASE = int(cfg.get("training_steps", 14000))
STEPS_MIN = int(cfg.get("training_steps_min", STEPS_BASE))
STEPS_UPGRADE = int(cfg.get("training_steps_upgrade", 8000))
AUTO_SCALE = bool(cfg.get("training_auto_scale", True))
TRAIN_EPOCHS = float(cfg.get("training_epochs", 1.0))
CHARS_PER_TOKEN = float(cfg.get("training_chars_per_token", 3.8))
TRAIN_HARD_MAX = int(cfg.get("training_steps_hard_max", 0) or 0)
if IS_H100 and bool(cfg.get("full_corpus_no_caps", True)):
TRAIN_HARD_MAX = 0
elif IS_CPU and cfg.get("low_resource_auto", True):
TRAIN_HARD_MAX = min(TRAIN_HARD_MAX or 8000, 8000)
def estimate_training_steps():
"""Ước lượng budget toàn cục theo quy mô dữ liệu, không tính lại theo từng shard."""
chars = int(HF_SOURCE.train_bytes) if HF_SOURCE is not None else 0
if chars <= 0 and SHARD_MANIFEST.exists():
try:
manifest = json.loads(SHARD_MANIFEST.read_text(encoding="utf-8"))
chars = int(manifest.get("actual_chars", 0) or 0)
if chars <= 0:
chars = int(manifest.get("actual_bytes", 0) or 0)
except Exception as exc:
print(f"[steps] Không đọc được shard manifest ({exc}), dùng fallback.")
if chars <= 0 and DATA.exists():
chars += DATA.stat().st_size