"""Direct-weight SGD, in-place inverse restoration, and MeZO integration checks.""" import ast import copy import math from pathlib import Path from types import SimpleNamespace import pytest import torch from methods.large_models.trainer import OurTrainer, seed_for def make_trainer(model, forward_loss, mu=.03, task='DROP'): trainer = OurTrainer.__new__(OurTrainer) trainer.model = model trainer.args = SimpleNamespace(zo_eps=mu, task_name=task, history_beta=.9, node_queries=2, node_epsilon=.001, refresh_every=1, main_forward_budget=100000, seed=42, device=next(model.parameters()).device) trainer._forward_outputs = forward_loss trainer.init_zo() trainer.current_lr = .01 trainer.state = SimpleNamespace(global_step=1) return trainer def algorithm(trainer, mu=.03, task='DROP'): trainer.args.zo_eps = mu trainer.args.task_name = task return trainer @torch.no_grad() def test_direct_weight_steps_match_explicit_coefficient_representation(): """同一批方向/响应下,换基前后的直接W更新等于W0+C+B D.T。""" model = torch.nn.Linear(2, 2, bias=True, dtype=torch.float64) model.weight.copy_(torch.tensor([[.2, -.1], [.4, .3]])) x = torch.tensor([[1., 2.]], dtype=torch.float64) model = torch.nn.Sequential(model) trainer = make_trainer(model, lambda batch: (model(x).square().mean(), model(x))) name = '0.weight' trainer.basis = {name: torch.tensor([[1.], [0.]], dtype=torch.float64)} initial = model[0].weight.clone();offset = torch.zeros_like(initial) coefficient = torch.zeros(2, 1, dtype=torch.float64) reference_bias = model[0].bias.clone() for step in range(4): if step == 2: offset += coefficient @ trainer.basis[name].T coefficient.zero_() before = model[0].weight.clone() trainer.basis[name] = torch.tensor([[0.], [1.]], dtype=torch.float64) assert torch.equal(before, model[0].weight) trainer.zo_step(model, {}, 100+step) estimate = trainer._estimate noise = {n: z for n, _, z in trainer.directions(estimate['seed'])} g = noise[name] * estimate['slope'] coefficient.add_(g, alpha=-trainer.current_lr) reference_bias.add_(noise['0.bias'] * estimate['slope'], alpha=-trainer.current_lr) trainer.zo_update(model) torch.testing.assert_close(model[0].weight, initial+offset+coefficient@trainer.basis[name].T, rtol=1e-12, atol=1e-12) torch.testing.assert_close(model[0].bias, reference_bias, rtol=1e-12, atol=1e-12) assert trainer.counts['training'] == 8 @torch.no_grad() def test_tied_parameters_are_updated_once_and_remain_tied(): from transformers import OPTConfig, OPTForCausalLM model = OPTForCausalLM(OPTConfig(vocab_size=16, hidden_size=8, ffn_dim=16, num_hidden_layers=1, num_attention_heads=2, max_position_embeddings=16)) trainer = make_trainer(model, lambda inputs: None) embedding = model.get_input_embeddings().weight assert embedding is model.get_output_embeddings().weight assert sum(p is embedding for _, p in trainer.named_parameters) == 1 before = embedding.clone() z = {name: direction for name, _, direction in trainer.directions(9)} name = next(name for name, p in trainer.named_parameters if p is embedding) expected = before.clone().add_(z[name]*2, alpha=-trainer.current_lr) trainer._estimate = dict(seed=9, slope=2., clean=torch.tensor(1.)) trainer.zo_update(model) assert torch.equal(embedding, expected) assert embedding is model.get_output_embeddings().weight @torch.no_grad() def test_shifted_restores_all_weights_even_when_forward_raises(): model = torch.nn.Sequential(torch.nn.Linear(2, 1)) trainer = make_trainer(model, lambda inputs: (_ for _ in ()).throw(RuntimeError('query failed'))) trainer.basis = {'0.weight': torch.tensor([[1.], [0.]])} old = {name: p.clone() for name, p in trainer.named_parameters} with pytest.raises(RuntimeError, match='query failed'): trainer.shifted({}, trainer.basis, 1, .01) for name, p in trainer.named_parameters: torch.testing.assert_close(p, old[name], rtol=1e-6, atol=1e-7) assert trainer.counts['training'] == 1 @torch.no_grad() def test_step_rebuilds_noise_without_parameter_clones(monkeypatch): model = torch.nn.Sequential(torch.nn.Linear(2, 2, bias=False)) x = torch.ones(1, 2) trainer = make_trainer(model, lambda inputs: (model(x).square().mean(), model(x))) trainer.basis = {'0.weight': torch.tensor([[1.], [0.]])} clone = torch.Tensor.clone def checked_clone(tensor, *args, **kwargs): assert tensor.numel() == 1, 'Training cloned a parameter/noise tensor' return clone(tensor, *args, **kwargs) monkeypatch.setattr(torch.Tensor, 'clone', checked_clone) trainer.fix_step({}, 7) assert trainer._estimate is None assert not hasattr(trainer, 'snapshot') def test_direction_stream_repeats_without_changing_global_rng(): model = torch.nn.Sequential(torch.nn.Linear(2, 2)) trainer = make_trainer(model, lambda inputs: None) trainer.basis = {'0.weight': torch.tensor([[1.], [0.]])} before = torch.random.get_rng_state() first = list(trainer.directions(123)) second = list(trainer.directions(123)) assert torch.equal(before, torch.random.get_rng_state()) assert [name for name, _, _ in first] == [name for name, _, _ in second] assert all(torch.equal(a[2], b[2]) for a, b in zip(first, second)) @torch.no_grad() def test_partial_perturbation_failure_restores_touched_parameters(): model = torch.nn.Sequential(torch.nn.Linear(2, 2), torch.nn.Linear(2, 1)) trainer = make_trainer(model, lambda inputs: None) trainer.basis = {name: torch.tensor([[1.], [0.]]) for name in trainer.linear_map} candidates = dict(trainer.basis, **{'1.weight': torch.ones(3, 1)}) before = {name: p.clone() for name, p in trainer.named_parameters} with pytest.raises(RuntimeError): trainer.shifted({}, candidates, 7, .01) for name, p in trainer.named_parameters: torch.testing.assert_close(p, before[name], rtol=1e-6, atol=1e-7) assert trainer.counts['training'] == 0 @pytest.mark.parametrize('method', ['fix', 'adjust', 'node']) @torch.no_grad() def test_direct_steps_run_on_tiny_opt_with_actual_refreshes(method): from transformers import OPTConfig, OPTForCausalLM torch.manual_seed(12) model = OPTForCausalLM(OPTConfig(vocab_size=16, hidden_size=8, ffn_dim=16, num_hidden_layers=3, num_attention_heads=2, max_position_embeddings=16, dropout=0., attention_dropout=0.)).eval() inputs = dict(input_ids=torch.tensor([[2,3,4,5]]), attention_mask=torch.ones(1,4,dtype=torch.long), labels=torch.tensor([[2,3,4,5]])) def forward(batch): result = model(**batch) # Match MeZOLoss's repeated scalar loss for the collated batch rows. return result.loss.expand(len(batch['input_ids'])), result.logits trainer = make_trainer(model, forward, mu=.01) trainer.current_lr = 1e-5 trainer.configure_basis(inputs) if method == 'node':trainer.configure_history() trainer.probe_batch = lambda: inputs trainer.state.global_step = 0 getattr(trainer, method+'_step')(inputs, 100) assert trainer.counts['training'] == 2 trainer.state.global_step = 1 before = trainer.used() result, event = getattr(trainer, method+'_step')(inputs, 101) assert math.isfinite(result['batch_loss']) assert all(bool(torch.isfinite(p).all()) for p in trainer.parameters) assert trainer.counts['evaluation'] == 0 if method == 'fix': assert event is None and trainer.used()-before == 2 else: assert event is not None assert trainer.used()-before == event['cost']+2 assert all(not module._forward_hooks and not module._forward_pre_hooks for module in model.modules()) def test_actual_mezo_zo_forward_is_reused(): import inspect root=Path(__file__).resolve().parents[1] tree=ast.parse((root/'baselines/mezo/large_models/trainer.py').read_text()) cls=next(n for n in tree.body if isinstance(n,ast.ClassDef) and n.name=='OurTrainer') original=next(n for n in cls.body if isinstance(n,ast.FunctionDef) and n.name=='zo_forward') import textwrap port=ast.parse(textwrap.dedent(inspect.getsource(OurTrainer.zo_forward))).body[0] # inspect.getsource + dedent changes docstring indentation, not executable code. assert inspect.cleandoc(ast.get_docstring(original))==inspect.cleandoc(ast.get_docstring(port)) original.body=original.body[1:];port.body=port.body[1:] assert ast.dump(original,include_attributes=False)==ast.dump(port,include_attributes=False) def test_aliases_default_to_mezo_and_explicit_legacy(tmp_path): from methods.large_models.run import parse_args args=parse_args(['--method','adjust','--task','sst2','--budget','45','--lr','2e-6','--refresh-every','2','--lr_scheduler_type','constant','--output_dir',str(tmp_path)]) assert args.trainer=='adjust' and args.task_name=='SST2' and args.main_forward_budget==45 assert args.learning_rate==2e-6 and args.refresh_every==2 and args.data_protocol=='mezo' and args.dataloader_drop_last is False assert args.zo_schedule=='constant' and args.max_grad_norm==0 legacy=parse_args(['--data_protocol','legacy','--output_dir',str(tmp_path)]) assert legacy.data_protocol=='legacy' and legacy.dataloader_drop_last is True native=parse_args(['--trainer','node','--task_name','DROP','--data_protocol','mezo','--output_dir',str(tmp_path)]) assert native.data_protocol=='mezo' and native.train_as_classification is False and native.zo_schedule=='cosine' def test_incompatible_native_and_structured_controls_fail_explicitly(tmp_path): from methods.large_models.run import parse_args with pytest.raises(ValueError,match='consistent'): parse_args(['--output_dir',str(tmp_path),'--schedule','constant','--lr_scheduler_type','cosine']) with pytest.raises(ValueError,match='clipping'): parse_args(['--output_dir',str(tmp_path),'--max_grad_norm','1']) @pytest.mark.parametrize('method', ['fix','adjust','node']) @pytest.mark.parametrize('task', ['SST2','DROP']) def test_all_methods_default_to_author_data_protocol(tmp_path,method,task): from methods.large_models.run import parse_args args=parse_args(['--trainer',method,'--task_name',task,'--output_dir',str(tmp_path)]) assert args.data_protocol=='mezo' and args.dataloader_drop_last is False assert args.only_train_option and args.train_as_classification==(task=='SST2') def test_author_sampler_and_legacy_sampler_are_separate(): from torch.utils.data import RandomSampler from methods.large_models.data import ProtocolSampler trainer=OurTrainer.__new__(OurTrainer) trainer.train_dataset=list(range(5)) trainer.args=SimpleNamespace(data_protocol='mezo',group_by_length=False,seed=42) assert isinstance(trainer._get_train_sampler(),RandomSampler) assert sorted(trainer._get_train_sampler())==list(range(5)) trainer.args.data_protocol='legacy' assert isinstance(trainer._get_train_sampler(),ProtocolSampler)