ppai-code / ppai /make_base.py
AdminHugging's picture
PPAI code only: без чужих проектов
ee15e43 verified
Raw History Blame Contribute Delete
5.93 kB
"""Собрать базовую PP-H (PacPerlar-Hydrogen) с случайной инициализацией.
Создаёт каталог, который тренеры проекта грузят как обычную HF-модель
(auto_map -> configuration_ppai / modeling_ppai), плюс кладёт рядом токенизатор.
Запуск:
python make_base.py --out /kaggle/working/ppai/model/base [--self-test]
"""
from __future__ import annotations
import argparse
import json
import os
import shutil
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from configuration_ppai import PPAIConfig, param_report # noqa: E402
from modeling_ppai import PPAIForCausalLM # noqa: E402
PRESETS = {
# PP-H: MoE, 100M всего / 12.4M активных
"pp-h": dict(vocab_size=24576, d_model=192, n_layers=10, n_heads=6, n_kv_heads=2,
head_dim=32, num_experts=20, ffn_dim=800, ffn_shared_dim=256),
# PP-OSR-H: dense, ~10.5M всего, без роутинга (проще для TPU)
"pp-osr-h": dict(vocab_size=16384, d_model=256, n_layers=6, n_heads=8, n_kv_heads=2,
head_dim=32, num_experts=0, ffn_dim=1024, ffn_shared_dim=256),
# PP-He: dense 600M, окно 4k, для SFT (instruct)
"pp-he": dict(vocab_size=24576, d_model=1280, n_layers=24, n_heads=20, n_kv_heads=5,
head_dim=64, num_experts=0, ffn_dim=5120, ffn_shared_dim=256),}
COMMON = dict(ngram_buckets=16384, ngram_dim=12, ngram_sizes=(2, 3, 4), ngram_seed=1337,
rope_theta=10000.0, rms_norm_eps=1e-6, max_position_embeddings=1024,
gate_dim=12, logit_softcap=30.0)
# у PP-He окно 4k — переопределяем после сборки пресета
CTX_OVERRIDE = {"pp-he": 4096}
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--out", default="/kaggle/working/ppai/model/base")
ap.add_argument("--tok-repo", default="AdminHugging/PP-Hydrogen")
ap.add_argument("--tok-token", default=os.environ.get("HF_TOKEN"))
ap.add_argument("--self-test", action="store_true")
ap.add_argument("--preset", default="pp-h", choices=list(PRESETS))
args = ap.parse_args()
os.makedirs(args.out, exist_ok=True)
cfg = PPAIConfig(**{**PRESETS[args.preset], **COMMON})
if args.preset in CTX_OVERRIDE:
cfg.max_position_embeddings = CTX_OVERRIDE[args.preset]
r = param_report(cfg)
print(f"[ppai] всего {r['total']/1e6:.1f}M | активных {r['active']/1e6:.1f}M "
f"| эмбеддинги {r['embedding']/1e6:.1f}M")
model = PPAIForCausalLM(cfg)
n = sum(p.numel() for p in model.parameters())
print(f"[ppai] создано параметров: {n/1e6:.2f}M")
model.save_pretrained(args.out, safe_serialization=True)
# auto_map, чтобы грузилось через trust_remote_code
cpath = os.path.join(args.out, "config.json")
with open(cpath, encoding="utf-8") as fh:
conf = json.load(fh)
conf["architectures"] = ["PPAIForCausalLM"]
conf["model_type"] = "ppai"
conf["auto_map"] = {
"AutoConfig": "configuration_ppai.PPAIConfig",
"AutoModelForCausalLM": "modeling_ppai.PPAIForCausalLM",
}
with open(cpath, "w", encoding="utf-8") as fh:
json.dump(conf, fh, ensure_ascii=False, indent=2)
for name in ("configuration_ppai.py", "modeling_ppai.py"):
shutil.copy2(os.path.join(HERE, name), os.path.join(args.out, name))
# токенизатор: из репозитория PPAI/tokenizer
got = False
if args.tok_token:
try:
from huggingface_hub import snapshot_download
d = snapshot_download(args.tok_repo, allow_patterns=["tokenizer/*"],
token=args.tok_token)
src = os.path.join(d, "tokenizer")
for f in os.listdir(src):
shutil.copy2(os.path.join(src, f), os.path.join(args.out, f))
got = True
print("[ppai] токенизатор скопирован из", src)
except Exception as exc: # noqa: BLE001
print("[ppai] токенизатор не скачался:", str(exc)[:150])
if not got:
for f in ("tokenizer.json", "tokenizer_config.json", "special_tokens_map.json"):
local = os.path.join(HERE, "tokenizer", f)
if os.path.exists(local):
shutil.copy2(local, os.path.join(args.out, f))
print("[ppai] токенизатор взят локально (если был)")
if args.self_test:
import torch
vocab = cfg.vocab_size
x = torch.randint(3, vocab, (2, 64))
model.eval()
with torch.no_grad():
out = model(input_ids=x, use_cache=False)
print(f"[test] logits: {tuple(out.logits.shape)} (ожидалось (2, 64, {vocab}))")
with torch.no_grad():
probe = torch.nn.functional.cross_entropy(
out.logits[:, :-1].reshape(-1, vocab).float(), x[:, 1:].reshape(-1))
print(f"[test] loss на случайных данных: {float(probe):.3f} "
f"(ожидаемо ~{torch.log(torch.tensor(float(vocab))):.2f})")
model.train()
logits = model(input_ids=x, use_cache=False).logits
loss = torch.nn.functional.cross_entropy(
logits[:, :-1].reshape(-1, vocab).float(), x[:, 1:].reshape(-1))
loss.backward()
total = len(list(model.parameters()))
grads = sum(1 for p in model.parameters() if p.grad is not None)
print(f"[test] градиенты посчитаны для {grads} тензоров из {total}")
print(f"[test] токенизатор на месте: {os.path.exists(os.path.join(args.out, 'tokenizer.json'))}")
print("[test] OK")
if __name__ == "__main__":
main()