Download test_training.py from openmodelai/Terra-2.5: direct link, hf CLI and curl.
- Browser
- Download file 4.9 kB
-
https://huggingface.co/openmodelai/Terra-2.5/resolve/main/test_training.py
- Command line
-
hf download hf://openmodelai/Terra-2.5/test_training.py
-
curl -L -o test_training.py https://huggingface.co/openmodelai/Terra-2.5/resolve/main/test_training.py
4.9 kB
| import json | |
| import os | |
| from pathlib import Path | |
| import subprocess | |
| import sys | |
| import pytest | |
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| from terra.common import batch, encode_pairs, read_pairs | |
| from terra.train import new_tokenizer | |
| ROOT = Path(__file__).resolve().parents[1] | |
| def test_label_masking_and_byte_roundtrip(): | |
| pairs = [{"question": "Кто ты?", "answer": "Terra 2.5 от SpaceModel."}] | |
| tok = new_tokenizer(pairs, 300) | |
| text = "Привет, Беларусь! 🪐" | |
| assert tok.decode(tok.encode(text)) == text | |
| assert "token_type_ids" not in tok(text) | |
| rows = encode_pairs(pairs, tok, 256) | |
| ids, labels = rows[0] | |
| assert labels[0] == -100 | |
| assert labels[-1] == tok.eos_token_id | |
| assert len(ids) == len(labels) | |
| b = batch([rows[0], ([1, 2], [-100, 2])], tok.pad_token_id) | |
| assert b["attention_mask"][1, 2:].sum() == 0 | |
| assert (b["labels"][1, 2:] == -100).all() | |
| with pytest.raises(ValueError, match="длиннее"): | |
| encode_pairs(pairs, tok, 1) | |
| def test_seed_dataset_is_disjoint(): | |
| train = read_pairs(ROOT / "data/train.jsonl") | |
| val = read_pairs(ROOT / "data/validation.jsonl") | |
| assert len(train) == 129 and len(val) == 12 | |
| assert not {p["question"] for p in train} & {p["question"] for p in val} | |
| def run_train(tmp_path, *extra): | |
| command = [sys.executable, "-m", "terra.train", "--config", str(tmp_path / "config.json"), | |
| "--data", str(tmp_path / "train.jsonl"), "--validation", str(tmp_path / "val.jsonl"), | |
| "--threads", "1", "--batch-size", "2", "--save-every", "2", *map(str, extra)] | |
| env = {**os.environ, "OMP_NUM_THREADS": "1", "MKL_NUM_THREADS": "1"} | |
| return subprocess.run(command, cwd=ROOT, env=env, capture_output=True, text=True, timeout=90) | |
| def test_resume_matches_uninterrupted_training(tmp_path, gradient_checkpointing): | |
| (tmp_path / "config.json").write_text(json.dumps({"vocab_size": 300, "n_positions": 128, | |
| "n_embd": 32, "n_layer": 1, "n_head": 2})) | |
| for name, question in (("train", "Имя?"), ("val", "Кто ты?")): | |
| (tmp_path / f"{name}.jsonl").write_text(json.dumps({"question": question, "answer": "Terra."}, ensure_ascii=False) + "\n") | |
| full, split = tmp_path / "full", tmp_path / "split" | |
| for args in (("--output", full, "--steps", 4), | |
| ("--output", split, "--steps", 2), | |
| ("--output", split, "--resume", split, "--steps", 2)): | |
| gc_args = ("--gradient-checkpointing",) if gradient_checkpointing else () | |
| result = run_train(tmp_path, *args, *gc_args) | |
| assert result.returncode == 0, result.stdout + result.stderr | |
| a = AutoModelForCausalLM.from_pretrained(full, local_files_only=True).state_dict() | |
| b = AutoModelForCausalLM.from_pretrained(split, local_files_only=True).state_dict() | |
| assert a.keys() == b.keys() | |
| for key in a: | |
| assert torch.equal(a[key], b[key]), key | |
| assert json.loads((split / "training_meta.json").read_text())["step"] == 4 | |
| assert json.loads((split / "training_meta.json").read_text())["gradient_checkpointing"] is gradient_checkpointing | |
| tok = AutoTokenizer.from_pretrained(split, local_files_only=True) | |
| assert "token_type_ids" not in tok("Вопрос: Имя?\nОтвет:") | |
| model = AutoModelForCausalLM.from_pretrained(split, local_files_only=True).eval() | |
| assert model.generate(**tok("Вопрос: Имя?\nОтвет:", return_tensors="pt"), max_new_tokens=2).shape[1] > 0 | |
| # Изменённые данные нельзя незаметно подмешать в resume. | |
| with (tmp_path / "train.jsonl").open("a") as f: | |
| f.write(json.dumps({"question": "Новое имя?", "answer": "Terra 2.5."}) + "\n") | |
| result = run_train(tmp_path, "--output", split, "--resume", split, "--steps", 1) | |
| assert result.returncode != 0 and "Данные изменились" in result.stderr | |
| result = run_train(tmp_path, "--output", split, "--resume", split, "--steps", 1, "--allow-new-data") | |
| assert result.returncode == 0, result.stdout + result.stderr | |
| # A compact restore may be trained and exported again; distinguish current | |
| # FP32 storage from its earlier lossy BF16 lineage. | |
| from terra.compact import export_compact | |
| compact = tmp_path / 'compact' | |
| export_compact(split, compact) | |
| continued = tmp_path / 'continued' | |
| result = run_train(tmp_path, '--output', continued, '--resume', compact, '--steps', 1) | |
| assert result.returncode == 0, result.stdout + result.stderr | |
| meta = json.loads((continued / 'training_meta.json').read_text()) | |
| assert meta['step'] == 6 | |
| assert 'compact_export' not in meta and len(meta['compact_export_history']) == 1 | |
| export_compact(continued, tmp_path / 'compact-again') | |