Terra-2.5 / test_bf16_bundle.py
openmodelai's picture
Upload 44 files
b838b2a verified
Raw History Blame Contribute Delete
3.83 kB
import json
import pytest
import torch
from transformers import AutoModelForCausalLM
from scripts.archive import restore, sha256
from scripts.bundle import make_bundle
from terra.train import make_optimizer, load_optimizer_state
from test_training import run_train
def test_adafactor_restores_fp32_statistics_for_bf16():
torch.manual_seed(123)
a = torch.nn.Linear(8, 8).bfloat16()
opt = make_optimizer(a, 'adafactor', 0.01)
x = torch.randn(2, 8).bfloat16()
a(x).float().square().sum().backward()
opt.step()
state = opt.state_dict()
b = torch.nn.Linear(8, 8).bfloat16()
b.load_state_dict(a.state_dict())
resumed = make_optimizer(b, 'adafactor', 0.01)
load_optimizer_state(resumed, state)
for left, right in zip(opt.state.values(), resumed.state.values()):
for key, value in left.items():
if torch.is_tensor(value):
assert value.dtype == right[key].dtype
assert torch.equal(value, right[key])
for model, optimizer in ((a, opt), (b, resumed)):
optimizer.zero_grad(set_to_none=True)
model(x).float().square().sum().backward()
optimizer.step()
for left, right in zip(a.parameters(), b.parameters()):
assert torch.equal(left, right)
def test_bf16_adafactor_resume_and_single_bundle(tmp_path):
(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.'}) + '\n')
full, split = tmp_path / 'full', tmp_path / 'split'
for args in (('--output', full, '--steps', 4, '--optimizer', 'adafactor', '--parameter-dtype', 'bfloat16'),
('--output', split, '--steps', 2, '--optimizer', 'adafactor', '--parameter-dtype', 'bfloat16'),
('--output', split, '--resume', split, '--steps', 2)):
result = run_train(tmp_path, *args, '--gradient-checkpointing')
assert result.returncode == 0, result.stdout + result.stderr
a = AutoModelForCausalLM.from_pretrained(full, local_files_only=True, torch_dtype='auto')
b = AutoModelForCausalLM.from_pretrained(split, local_files_only=True, torch_dtype='auto')
assert next(b.parameters()).dtype == torch.bfloat16
for key, value in a.state_dict().items():
assert torch.equal(value, b.state_dict()[key]), key
original_state_hash = sha256(split / 'training_state.pt')
archive = tmp_path / 'model.zip'
make_bundle(split, archive)
unpacked = tmp_path / 'unpacked'
restore(archive, unpacked) # CRC, traversal, manifest and per-file SHA verification.
assert sha256(split / 'model.safetensors') == sha256(unpacked / 'model.safetensors')
assert sha256(split / 'training_state.pt') == original_state_hash
assert (unpacked / 'training/terra/train.py').is_file()
state = torch.load(unpacked / 'training_state.pt', weights_only=True)
assert state['optimizer']['state'] == {} and state['step'] == 4
meta = json.loads((unpacked / 'training_meta.json').read_text())
assert meta['bundle_export']['weight_bytes_unchanged']
assert meta['bundle_export']['optimizer_restart_required']
result = run_train(tmp_path, '--resume', unpacked, '--output', tmp_path / 'warm', '--steps', 1)
assert result.returncode == 0, result.stdout + result.stderr
assert 'warm restart' in result.stdout
result = run_train(tmp_path, '--resume', split, '--output', tmp_path / 'bad',
'--steps', 1, '--optimizer', 'adamw')
assert result.returncode != 0 and 'requires --reset-optimizer' in result.stderr
with pytest.raises(ValueError):
make_bundle(split, archive)