Files
gloamxun e0feabec8f Initialize optimizer research workspace with official baselines and history-free coverage
Vendor pinned MeZO, AGZO, LOZO and LoREN sources with independent environments. Add direct in-place fix/adjust/node training, derived history-free basis gradients, development-best checkpoints and experiment tooling. Keep models, datasets, caches and credentials outside Git.

Validation: 93 project tests passed; 521 vendored author files verified.
2026-11-12 23:32:33 +08:00

240 lines
11 KiB
Python

"""Unconditional node refresh transitions and retained descent-probe reference."""
import copy
from types import SimpleNamespace
import pytest
import torch
from test_mezo_refactor import algorithm, make_trainer
class QuadraticModel(torch.nn.Module):
def __init__(self):
super().__init__()
self.left = torch.nn.Linear(2, 1, bias=False, dtype=torch.float64)
self.right = torch.nn.Linear(2, 1, bias=False, dtype=torch.float64)
self.offset = torch.nn.Parameter(torch.tensor([0.3], dtype=torch.float64))
with torch.no_grad():
self.left.weight.copy_(torch.tensor([[0.2, -0.1]]))
self.right.weight.copy_(torch.tensor([[0.1, 0.4]]))
def forward(self, x):
return self.left(x) + self.right(x) + self.offset
@pytest.fixture
def quadratic_engine():
model = QuadraticModel()
inputs = {
'x': torch.tensor([[[1., 0.], [0., 2.]]], dtype=torch.float64),
'attention_mask': torch.ones(1, 2, dtype=torch.long),
'target': torch.tensor([[[1.], [-1.]]], dtype=torch.float64),
}
def forward_loss(batch):
predictions = model(batch['x'])
return (predictions - batch['target']).square().mean() / 2, predictions
engine = make_trainer(model, forward_loss)
with torch.no_grad():
engine.configure_basis(inputs)
engine.basis = {name: torch.tensor([[1.], [0.]], dtype=torch.float64)
for name in engine.linear_map}
engine.history = {
'left.weight': torch.tensor([[1.]], dtype=torch.float64),
'right.weight': torch.tensor([[2.]], dtype=torch.float64),
}
yield engine, inputs
def snapshot(engine):
return {
'parameters': [p.clone() for p in engine.parameters],
'basis': copy.deepcopy(engine.basis),
'history': {name: value.clone() for name, value in engine.history.items()},
}
def assert_unchanged(engine, before):
for original, current in zip(before['parameters'], engine.parameters):
torch.testing.assert_close(original, current, rtol=1e-12, atol=1e-12)
for name, basis in before['basis'].items():
torch.testing.assert_close(basis, engine.basis[name], rtol=0, atol=0)
for name, value in before['history'].items():
torch.testing.assert_close(value, engine.history[name], rtol=0, atol=0)
@torch.no_grad()
def test_descent_probe_matches_actual_quadratic_update_and_restores_state(quadratic_engine):
engine, inputs = quadratic_engine
candidates = [engine.basis, dict(engine.basis, **{
'left.weight': torch.tensor([[0.], [1.]], dtype=torch.float64),
})]
before = snapshot(engine)
count = engine.counts['training']
seed, lr = 451, 0.07
probes = algorithm(engine, mu=.03, task="DROP").descent_probe(inputs, candidates, seed, lr)
assert engine.counts['training'] - count == 5
assert engine.counts['evaluation'] == 0
assert_unchanged(engine, before)
clean = float(engine._forward_outputs(inputs)[0])
for candidate, result in zip(candidates, probes):
updated = engine.shifted(inputs, candidate, seed, -lr,
response=result['response'])
assert result['predicted_descent'] == pytest.approx(clean - float(updated),
rel=1e-10, abs=1e-12)
assert result['response'] == pytest.approx(
result['slope'] + .03 * result['curvature'] / 2,
rel=1e-11, abs=1e-12)
assert_unchanged(engine, before)
@torch.no_grad()
def test_node_refreshes_proposed_bases_without_comparison(quadratic_engine, monkeypatch):
engine, inputs = quadratic_engine
before = snapshot(engine)
loss_before = engine._forward_outputs(inputs)[0].clone()
trainer = algorithm(engine)
trainer.probe_batch = lambda: inputs
proposed = torch.tensor([[0.], [1.]], dtype=torch.float64)
calls = []
def proposal(inputs, seed):
calls.append(('proposal', seed))
trainer.counts['training'] += 1 + len(trainer.history) * trainer.args.node_queries
return {'left.weight': proposed}, {'left.weight': {'history_norm': 1.}}
def next_update(inputs, seed):
calls.append(('update', seed))
torch.testing.assert_close(trainer.basis['left.weight'], proposed, rtol=0, atol=0)
assert torch.count_nonzero(trainer.history['left.weight']) == 0
return {}, None
monkeypatch.setattr(trainer, 'node_proposal', proposal)
monkeypatch.setattr(trainer, 'descent_probe', lambda *args: pytest.fail('Unexpected comparison'))
monkeypatch.setattr(trainer, 'fix_step', next_update)
_, event = trainer.node_step(inputs, 81)
assert event['accepted'] is True
assert event['variant'] == 'node_unconditional_refresh_control_v1'
assert event['cost'] == 5
assert all(name not in event for name in ('probes', 'old_descent', 'new_descent', 'gain'))
assert [kind for kind, _ in calls] == ['proposal', 'update']
assert calls[1][1] == 81
assert calls[0][1] != calls[1][1]
torch.testing.assert_close(engine.basis['left.weight'], proposed, rtol=0, atol=0)
torch.testing.assert_close(engine.basis['right.weight'], before['basis']['right.weight'],
rtol=0, atol=0)
assert torch.count_nonzero(engine.history['left.weight']) == 0
torch.testing.assert_close(engine.history['right.weight'], before['history']['right.weight'],
rtol=0, atol=0)
for before_weight, weight in zip(before['parameters'], engine.parameters):
torch.testing.assert_close(before_weight, weight, rtol=0, atol=0)
torch.testing.assert_close(engine._forward_outputs(inputs)[0], loss_before, rtol=0, atol=0)
@torch.no_grad()
def test_empty_node_proposal_keeps_basis_and_history(quadratic_engine, monkeypatch):
engine, inputs = quadratic_engine
before = snapshot(engine)
trainer = algorithm(engine)
trainer.probe_batch = lambda: inputs
monkeypatch.setattr(trainer, 'node_proposal', lambda inputs, seed: ({}, {}))
monkeypatch.setattr(trainer, 'descent_probe', lambda *args: pytest.fail('Unexpected comparison'))
trainer.fix_step = lambda *args: ({}, None)
_, event = trainer.node_step(inputs, 81)
assert event['accepted'] is False
assert 'reason' not in event
assert 'probes' not in event
assert_unchanged(engine, before)
@pytest.mark.parametrize(('method', 'budget', 'refreshes', 'used', 'cost'), [
('node', 11, 0, 5, 7), ('node', 12, 1, 12, 7),
('adjust', 10, 0, 5, 6), ('adjust', 11, 1, 11, 6),
])
def test_trainer_reserves_full_refresh_and_next_update(monkeypatch, tmp_path,
method, budget, refreshes, used, cost):
from methods.large_models import trainer as module
# Exercise the real scheduling loop without writing model/result artifacts.
events = []
monkeypatch.setattr(module, 'save', lambda *args: None)
monkeypatch.setattr(module, 'append', lambda path, data:
events.append(data) if path.name == 'refresh.jsonl' else None)
monkeypatch.setattr(module, 'memory', lambda: {})
trainer = module.OurTrainer.__new__(module.OurTrainer)
trainer.args = SimpleNamespace(output_dir=str(tmp_path), per_device_train_batch_size=1,
calibration_samples=1, trainer=method, preflight_only=False, seed=42,
main_forward_budget=budget, max_steps=2, refresh_every=1, node_queries=2,
eval_main_forwards=100, save_final_checkpoint=False, data_protocol='mezo')
trainer.state = SimpleNamespace(global_step=0);trainer.model = None
trainer.counts = dict(training=0, calibration=0, evaluation=0, diagnostic=0)
trainer.history = {name: torch.ones(1) for name in ('a', 'b', 'c')}
trainer.parameters = [];trainer.basis = {'a': torch.ones(1)}
trainer.refreshes = 0
def configure(inputs): trainer.counts['calibration'] += 1
trainer.configure_basis = configure
trainer.train_dataset = [0];trainer.curve = [];trainer.started = 0
trainer.progress = lambda *args: None
trainer.collate = lambda *args: {}
trainer.get_train_dataloader = lambda: [{}]
trainer._prepare_inputs = lambda inputs: inputs
trainer.learning_rate_at = lambda q: 1e-3
trainer.measure = lambda: trainer.curve.append(dict(main_forwards=trainer.used()))
def proposal(inputs, seed):
trainer.refreshes += 1
trainer.counts['training'] += 7
return {'a': torch.ones(1)}, {}
trainer.node_proposal = proposal
def descent_probe(*args):
pytest.fail('Unconditional node refresh must not query a descent comparison')
trainer.descent_probe = descent_probe
def collect_basis(inputs):
trainer.refreshes += 1
trainer.counts['training'] += 1
return {'a': torch.ones(1)}
trainer.collect_basis = collect_basis
def adjust_probe(*args):
trainer.counts['training'] += 5
return dict(gain=1., old_loss=2., new_loss=1.)
trainer.adjust_probe = adjust_probe
def update(model, inputs, seed):
trainer.counts['training'] += 2
trainer.zo_step = update
trainer.zo_update = lambda model: dict(batch_loss=1.)
trainer.configure_history = lambda: None
result = trainer._inner_training_loop()
assert trainer.refreshes == refreshes
assert result.metrics['main_forwards'] == used <= budget
assert len(events) == refreshes
if events:
assert events[0]['cost'] == cost
assert trainer.counts['evaluation'] == 0
def test_minimal_cli_has_no_search_controls(tmp_path):
from methods.large_models.run import parse_args
args = parse_args(['--trainer', 'node', '--output_dir', str(tmp_path)])
assert all(not hasattr(args, name) for name in ('node_variant', 'probe_pairs', 'gate_k', 'gate_margin'))
@pytest.mark.parametrize(('flag', 'value'), [
('--probe_pairs', '2'), ('--gate_k', '1'), ('--gate_margin', '0'),
('--node_variant', 'unconditional'), ('--probe-pairs', '2'),
('--gate-k', '1'), ('--gate-margin', '0'), ('--node-variant', 'unconditional'),
('--node_variant', 'descent_gradient_proxy_v1'),
('--node-variant', 'descent_gradient_proxy_v1'),
])
def test_removed_search_controls_fail_explicitly(tmp_path, flag, value):
from methods.large_models.run import parse_args
with pytest.raises(ValueError, match='not used'):
parse_args(['--trainer', 'node', flag, value, '--output_dir', str(tmp_path)])
@pytest.mark.parametrize('epsilon', ['-1', '0', 'nan', 'inf'])
def test_invalid_node_epsilon_is_rejected(tmp_path, epsilon):
from methods.large_models.run import parse_args
with pytest.raises(ValueError):
parse_args(['--trainer', 'node', '--node_epsilon', epsilon, '--output_dir', str(tmp_path)])