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.
This commit is contained in:
gloamxun committed 2026-11-12 23:32:33 +08:00
commit e0feabec8f
596 files changed
+87356

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
"""Development-only selection, disk restore, and tied-weight round trip."""
from types import SimpleNamespace
import json
import pytest
import torch
from transformers import OPTConfig, OPTForCausalLM
from test_mezo_refactor import make_trainer
@torch.no_grad()
@pytest.mark.parametrize('sharded', [False, True])
def test_best_checkpoint_keeps_earliest_minimum_and_restores_weights(tmp_path, monkeypatch, sharded):
from methods.large_models import trainer as module
monkeypatch.setattr(module, 'figures', lambda *args: None)
model = OPTForCausalLM(OPTConfig(vocab_size=16, hidden_size=8, ffn_dim=16,
num_hidden_layers=1, num_attention_heads=2, max_position_embeddings=16))
engine = make_trainer(model, lambda batch: None)
engine.args.output_dir = str(tmp_path)
engine.args.select_best_checkpoint = True
engine.args.data_protocol = 'mezo'
engine.processing_class = SimpleNamespace(save_pretrained=lambda *args: None)
engine.train_dataset, engine.eval_dataset = [0], [1]
engine.curve = [];engine.started = 0
engine.progress = lambda *args: None
loss = [3.]
def evaluate(*args):
engine.counts['evaluation'] += 1
return dict(loss=loss[0], accuracy=.5)
engine.evaluate_dataset = evaluate
parameter = model.get_input_embeddings().weight
rng = torch.random.get_rng_state()
for step, value in enumerate((3., 2., 2., 4.), 1):
engine.state.global_step = step
engine.counts['training'] = step*2
parameter.fill_(float(step))
loss[0] = value
engine.measure()
assert float(parameter[0, 0]) == step # Saving does not rewind training.
assert engine.best_checkpoint['step'] == 2 # Tie retains earlier best.
assert json.loads((tmp_path/'best_checkpoint.json').read_text())['development']['loss'] == 2
if sharded:
engine.restore_best_model()
model.save_pretrained(tmp_path/'best_model', max_shard_size='1KB')
parameter.fill_(4.)
engine.restore_best_model()
assert torch.all(parameter == 2)
assert parameter is model.get_output_embeddings().weight
assert torch.equal(rng, torch.random.get_rng_state())
@torch.no_grad()
def test_initial_evaluation_is_not_a_train_checkpoint(tmp_path, monkeypatch):
from methods.large_models import trainer as module
monkeypatch.setattr(module, 'figures', lambda *args: None)
engine = module.OurTrainer.__new__(module.OurTrainer)
engine.args = SimpleNamespace(output_dir=str(tmp_path), select_best_checkpoint=True)
engine.state = SimpleNamespace(global_step=0)
engine.counts = dict(training=0, calibration=1, evaluation=0)
engine.train_dataset, engine.eval_dataset = [0], [1]
engine.curve = [];engine.started = 0;engine.progress = lambda *args: None
engine.evaluate_dataset = lambda *args: dict(loss=1.)
engine.save_model = lambda *args: (_ for _ in ()).throw(AssertionError('initial save'))
engine.measure()
assert not hasattr(engine, 'best_checkpoint')
+147
View File
@@ -0,0 +1,147 @@
"""Conditional implementation versus exact quadratic derivatives, not an LLM proxy."""
import copy
import pytest
import torch
from test_node_descent import quadratic_engine
def options():
return dict(certified_smoothness=10., basis_lr=.003, basis_radius=.02)
def quadratic_quantities(engine, batch):
x = batch['x'].reshape(-1, 2)
design = torch.cat([torch.ones(len(x), 1, dtype=x.dtype), x, x], dim=1)
# named_parameters orders the direct offset before child Linear weights.
theta = torch.cat([p.flatten() for _, p in engine.named_parameters])
residual = design @ theta-batch['target'].flatten()
return theta, design.T @ residual/len(x), design.T @ design/len(x)
def lifted(engine, bases, seed):
return torch.cat([(z @ bases[n].T if n in bases else z).flatten()
for n, _, z in engine.directions(seed)])
@torch.no_grad()
@pytest.mark.parametrize('smoothness', [None, 10.])
def test_refresh_matches_exact_cross_batch_score_and_basis_gradient(quadratic_engine, smoothness):
engine, batch = quadratic_engine
batches = [dict(batch, target=batch['target']+shift) for shift in [.2, -.3, .4]]
old_basis = copy.deepcopy(engine.basis)
weights = [p.clone() for p in engine.parameters]
g_a = quadratic_quantities(engine, batches[0])[1]
g_b = quadratic_quantities(engine, batches[1])[1]
k = quadratic_quantities(engine, batches[2])[2]
# Eigenvalue certificate for this quadratic only, not for a neural network.
assert float(torch.linalg.eigvalsh(k).max()) <= options()['certified_smoothness']
gen = torch.Generator().manual_seed(56)
tangents = {}
candidates = [{}, {}]
for name, d in old_basis.items():
v = torch.randn(d.shape, dtype=d.dtype, generator=gen)
v -= d*(d*v).sum()
tangents[name] = v
for bases, sign in zip(candidates, [1, -1]):
bases[name] = torch.nn.functional.normalize(d+sign*.02*v, dim=0)
expected = []
for bases in candidates:
u = lifted(engine, bases, 123)
h = u @ k @ u+(0 if smoothness is None else 2*smoothness)*(u @ u)
expected.append(float((g_a @ u)*(g_b @ u)*(1-engine.current_lr*h/2)))
before = engine.used()
event = engine.curvature_refresh(batches, 123, 56, **dict(options(), certified_smoothness=smoothness))
assert event['curvature_quantity'] == ('local_hessian' if smoothness is None else 'certified_quadratic_upper_bound')
assert engine.used()-before == event['cost'] == 13
assert engine.counts['evaluation'] == 0
assert [p['score'] for p in event['probes']] == pytest.approx(expected, abs=1e-11)
q = (expected[0]-expected[1])/.04
assert event['difference_quotient'] == pytest.approx(q, abs=1e-10)
for name, d in old_basis.items():
target = torch.nn.functional.normalize(d+.003*q*tangents[name], dim=0)
torch.testing.assert_close(engine.basis[name], target, atol=1e-12, rtol=1e-12)
for old, actual in zip(weights, engine.parameters):
torch.testing.assert_close(old, actual, atol=1e-12, rtol=1e-12)
assert actual.grad is None
@pytest.mark.parametrize('remaining', [14, 15])
@torch.no_grad()
def test_full_step_budget_and_exact_one_sided_weight_update(quadratic_engine, remaining):
engine, batch = quadratic_engine
engine.args.main_forward_budget = engine.used()+remaining
before = engine.used()
theta, g, k = quadratic_quantities(engine, batch)
draws = []
def independent_batches():
draws.append(1)
return [dict(batch) for _ in range(3)] # Deterministic objective; no sample noise.
result, event = engine.curvature_step(batch, 234, selection_batches=independent_batches, **options())
assert len(draws) == int(remaining == 15)
assert engine.used()-before == (15 if remaining == 15 else 2)
if event is not None:
assert event['seed'] != 234 and event['cost'] == 13
u = lifted(engine, engine.basis, 234)
slope = g @ u+engine.args.zo_eps*(u @ k @ u)/2
expected = theta-engine.current_lr*slope*u
actual = torch.cat([p.flatten() for p in engine.parameters])
torch.testing.assert_close(actual, expected, atol=1e-12, rtol=1e-12)
assert result['response'] == pytest.approx(float(slope), abs=1e-12)
@torch.no_grad()
def test_failed_refresh_restores_weights_without_switching_basis(quadratic_engine):
engine, batch = quadratic_engine
old_basis = copy.deepcopy(engine.basis)
weights = [p.clone() for p in engine.parameters]
original = engine._forward_outputs
def forward(inputs):
if engine.counts['training'] == 6:
raise RuntimeError('query failed')
return original(inputs)
engine._forward_outputs = forward
with pytest.raises(RuntimeError, match='query failed'):
engine.curvature_refresh([batch]*3, 123, 56, **options())
for n in old_basis:
torch.testing.assert_close(old_basis[n], engine.basis[n], atol=0, rtol=0)
for old, actual in zip(weights, engine.parameters):
torch.testing.assert_close(old, actual, atol=1e-12, rtol=1e-12)
@torch.no_grad()
def test_refresh_does_not_clone_full_parameters_or_change_global_rng(quadratic_engine, monkeypatch):
engine, batch = quadratic_engine
before_rng = torch.random.get_rng_state()
original = torch.Tensor.clone
def clone(tensor, *args, **kwargs):
assert tensor.numel() == 1, 'Cloned non-scalar parameter/noise'
return original(tensor, *args, **kwargs)
monkeypatch.setattr(torch.Tensor, 'clone', clone)
engine.curvature_refresh([batch]*3, 123, 56, **options())
assert torch.equal(before_rng, torch.random.get_rng_state())
@torch.no_grad()
def test_fp32_refresh_restoration_has_bounded_rounding_error(quadratic_engine):
engine, batch = quadratic_engine
engine.model.float()
engine.basis = {n: d.float() for n, d in engine.basis.items()}
batch = {n: x.float() if x.is_floating_point() else x for n, x in batch.items()}
before = [p.clone() for p in engine.parameters]
event = engine.curvature_refresh([batch]*3, 123, 56, **options())
assert event['cost'] == 13
for p, old in zip(engine.parameters, before):
torch.testing.assert_close(p, old, rtol=1e-6, atol=1e-7)
for d in engine.basis.values():
assert float(d.norm()) == pytest.approx(1., abs=1e-6)
@pytest.mark.parametrize('value', [0., -1., float('nan'), float('inf')])
def test_invalid_curvature_constants_fail_before_queries(quadratic_engine, value):
engine, batch = quadratic_engine
opts = options()
opts['certified_smoothness'] = value
before = engine.used()
with pytest.raises(ValueError, match='positive finite'):
engine.curvature_refresh([batch]*3, 123, 56, **opts)
assert engine.used() == before
+369
View File
@@ -0,0 +1,369 @@
"""Independent checks of the supplied descent theorem, not production training."""
import itertools
import numpy as np
import pytest
import torch
from methods.large_models.trainer import (
curvature_descent_reference, curvature_input_gradient_reference,
)
def quadratic():
generator = torch.Generator().manual_seed(73)
x = torch.randn(3, 3, generator=generator, dtype=torch.float64)
h = x.T @ x + torch.eye(3, dtype=torch.float64)
g = torch.tensor([.4, -.7, .2], dtype=torch.float64)
u = torch.linalg.qr(torch.randn(3, 2, generator=generator, dtype=torch.float64)).Q
return g, h, u
@pytest.mark.parametrize('mu', [0., .07])
@pytest.mark.parametrize('n', [1, 2])
def test_projection_derivative_matches_independent_autograd(mu, n):
g, h, u = quadratic()
raw = (u @ u.T).requires_grad_()
p = (raw + raw.T)/2
pg = p @ g
s, t = g @ pg, torch.trace(p @ h)
expected = s - .03/2*((1+1/n)*(pg @ h @ pg) + s*t/n)
if mu:
ph = p @ h
expected -= .03*mu**2/(8*n)*(t**3 + 6*t*torch.trace(ph@ph) + 8*torch.trace(ph@ph@ph))
derivative, = torch.autograd.grad(expected, raw)
value, actual = curvature_descent_reference(g, h, p.detach(), .03, n, mu)
torch.testing.assert_close(value, expected.detach(), rtol=1e-12, atol=1e-12)
torch.testing.assert_close(actual, derivative, rtol=1e-12, atol=1e-12)
def expected_next_loss(g, k, u, lr, n, mu):
# Degree-six Gaussian integrals are exact with four Hermite nodes per axis.
nodes, weights = np.polynomial.hermite.hermgauss(4)
nodes = nodes * np.sqrt(2)
weights = weights / np.sqrt(np.pi)
total = 0.
for indices in itertools.product(range(4), repeat=u.shape[1]*n):
z = torch.tensor(nodes[list(indices)], dtype=torch.float64).reshape(n, -1)
directions = z @ u.T
responses = directions @ g + mu/2*torch.einsum('bi,ij,bj->b', directions, k, directions)
update = -lr*(responses[:, None]*directions).mean(0)
loss = g @ update + (update @ k @ update)/2
total += float(loss)*float(np.prod(weights[list(indices)]))
return total
@pytest.mark.parametrize('n', [1, 2])
@pytest.mark.parametrize('mu', [0., .07])
def test_gaussian_descent_exact_on_quadratics(n, mu):
g, h, u = quadratic()
value, _ = curvature_descent_reference(g, h, u @ u.T, .03, n, mu)
actual = expected_next_loss(g, h, u, .03, n, mu)
assert actual == pytest.approx(-.03*float(value), abs=1e-12)
def test_known_quadratic_upper_bound_gives_inequality():
g, k, u = quadratic()
h = k + torch.eye(3, dtype=torch.float64)*2
value, _ = curvature_descent_reference(g, h, u @ u.T, .03, 2)
assert expected_next_loss(g, k, u, .03, 2, 0.) <= -.03*float(value)+1e-12
def test_ideal_formula_cannot_ignore_nonzero_single_sided_radius():
g = torch.zeros(1, dtype=torch.float64)
h = p = torch.ones(1, 1, dtype=torch.float64)
ideal, _ = curvature_descent_reference(g, h, p, .1)
corrected, _ = curvature_descent_reference(g, h, p, .1, quadratic_mu=.2)
actual = expected_next_loss(g, h, p, .1, 1, .2)
assert ideal == 0 and actual > 0
assert actual == pytest.approx(15*.1**2*.2**2/8, abs=1e-14)
assert actual == pytest.approx(-.1*float(corrected), abs=1e-14)
def test_structured_input_gradient_with_auxiliary_and_cross_blocks():
generator = torch.Generator().manual_seed(17)
d = torch.nn.functional.normalize(torch.randn(3, generator=generator, dtype=torch.float64), dim=0)
x = torch.randn(7, 7, generator=generator, dtype=torch.float64)
h = x.T @ x
g = torch.randn(7, generator=generator, dtype=torch.float64)
def objective(v):
local = torch.kron(torch.eye(2, dtype=torch.float64), torch.outer(v, v))
p = torch.block_diag(local, torch.ones(1, 1, dtype=torch.float64))
return curvature_descent_reference(g, h, p, .001, quadratic_mu=.03)
_, m = objective(d)
tangent = curvature_input_gradient_reference(m[:6, :6], d, 2)
v = torch.randn(3, generator=generator, dtype=torch.float64)
v -= d*(d @ v)
eps = 1e-6
normalize = lambda q: torch.nn.functional.normalize(q, dim=0)
fd = (objective(normalize(d+eps*v))[0]-objective(normalize(d-eps*v))[0])/(2*eps)
torch.testing.assert_close(tangent @ v, fd, rtol=1e-7, atol=1e-8)
assert abs(float(d @ tangent)) < 1e-12
new = normalize(d+1e-5*tangent)
assert objective(new)[0] > objective(d)[0]
torch.testing.assert_close(new.norm(), torch.ones((), dtype=torch.float64))
# Multiplying the objective gradient by two must double the basis gradient.
doubled = curvature_input_gradient_reference(2*m[:6, :6], d, 2)
torch.testing.assert_close(doubled, 2*tangent)
def estimator_moments(observed_gradient, h, u, n, mu):
nodes, weights = np.polynomial.hermite.hermgauss(4)
nodes, weights = nodes*np.sqrt(2), weights/np.sqrt(np.pi)
mean = torch.zeros_like(observed_gradient)
curvature = 0.
for ids in itertools.product(range(4), repeat=u.shape[1]*n):
z = torch.tensor(nodes[list(ids)], dtype=torch.float64).reshape(n, -1)
directions = z @ u.T
response = directions @ observed_gradient + mu/2*torch.einsum('bi,ij,bj->b', directions, h, directions)
estimate = (response[:, None]*directions).mean(0)
weight = float(np.prod(weights[list(ids)]))
mean += weight*estimate
curvature += weight*float(estimate @ h @ estimate)
return mean, curvature
@pytest.mark.parametrize('n', [1, 2])
def test_independent_batch_covariance_and_single_sided_error_bounds(n):
g, h, u = quadratic()
p = u @ u.T
noise = torch.tensor([.3, -.1, .4], dtype=torch.float64)
covariance = torch.outer(noise, noise)
s, trace = g @ p @ g, torch.trace(p @ h)
l_u = torch.linalg.eigvalsh(u.T @ h @ u).max()
noise_cost = (1+1/n)*torch.trace(p @ h @ p @ covariance) + trace/n*torch.trace(p @ covariance)
ideal_c = (1+1/n)*(g @ p @ h @ p @ g) + s*trace/n
mean0, c0 = estimator_moments(g+noise, h, u, n, 0.)
mean1, c1 = estimator_moments(g-noise, h, u, n, 0.)
torch.testing.assert_close((mean0+mean1)/2, p @ g)
assert (c0+c1)/2 == pytest.approx(float(ideal_c+noise_cost), abs=1e-10)
mu = .07
mean0, c0 = estimator_moments(g+noise, h, u, n, mu)
mean1, c1 = estimator_moments(g-noise, h, u, n, mu)
k = u.shape[1]
l_f = torch.linalg.eigvalsh(h).max()
b_mu = l_f**2*mu**2/4*k*(k+2)*(k+4)
actual_alignment = g @ ((mean0+mean1)/2)
assert actual_alignment >= s/2-b_mu/2-1e-12
bound = 2*((1+1/n)*l_u+trace/n)*s + 2*noise_cost + 2*l_u*b_mu
assert (c0+c1)/2 <= bound+1e-10
def test_independent_direction_noise_does_not_remove_batch_selection_coupling():
batches = torch.eye(2, dtype=torch.float64)
projections = [torch.diag(row) for row in batches]
g = batches.mean(0)
average_p = sum(projections)/2
expected_update = sum(p @ b for p, b in zip(projections, batches))/2
coupling = sum((p-average_p) @ (b-g) for p, b in zip(projections, batches))/2
torch.testing.assert_close(expected_update, average_p @ g + coupling)
assert coupling.norm() > 0
assert not torch.allclose(expected_update, average_p @ g)
@pytest.mark.parametrize('n', [1, 2])
def test_nonquadratic_single_sided_bias_and_error_bounds(n):
# F(x)=sin(x), theta=0: g=1, L_f=H=P=1 globally.
# E[z sin(mu*z)/mu] = exp(-mu^2/2), so the observation bias is nonzero.
mu = .4
nodes, weights = np.polynomial.hermite.hermgauss(48)
z, weights = nodes*np.sqrt(2), weights/np.sqrt(np.pi)
ideal = z**2
observed = z*np.sin(mu*z)/mu
error = observed-ideal
mean = float(weights @ observed)
mean_error = float(weights @ error)
assert mean == pytest.approx(np.exp(-mu**2/2), abs=1e-13)
assert mean_error == pytest.approx(mean-1, abs=1e-13)
assert mean_error < 0
# Average n independent directions; retain the off-diagonal mean products.
error_second = float(weights @ error**2)/n + (1-1/n)*mean_error**2
curvature = float(weights @ observed**2)/n + (1-1/n)*mean**2
cross = float(weights @ (ideal*error))/n + (1-1/n)*mean_error
ideal_curvature = 1+2/n
assert abs(cross) > 1e-3
assert curvature == pytest.approx(ideal_curvature+2*cross+error_second, abs=1e-12)
b_mu = 15*mu**2/4
assert error_second <= b_mu
assert mean >= 1/2-b_mu/2
assert curvature <= 2*ideal_curvature+2*b_mu
def test_isotropic_curvature_is_a_declared_exact_special_case():
g, _, u = quadratic()
p = u @ u.T
h = 5*torch.eye(3, dtype=torch.float64)
for n in [1, 2]:
value, _ = curvature_descent_reference(g, h, p, .001, n)
coefficient = 1-.001*5/2*(1+(u.shape[1]+1)/n)
assert coefficient > 0
torch.testing.assert_close(value, (g @ p @ g)*coefficient)
def gaussian_rule(dimension, order):
nodes, weights = np.polynomial.hermite.hermgauss(order)
ids = np.array(list(itertools.product(range(order), repeat=dimension)))
return np.sqrt(2)*nodes[ids], np.prod(weights[ids]/np.sqrt(np.pi), axis=1)
def forward_score_pair(losses, directions, mu, lr, smoothness):
"""Section 6.3, on tiny test objectives at theta=0; no derivative oracle."""
clean_c = losses[2](np.zeros_like(directions[0]))
scores = []
for direction in directions:
a, b = [(loss(mu*direction)-loss(-mu*direction))/(2*mu) for loss in losses[:2]]
c = (losses[2](mu*direction)-2*clean_c+losses[2](-mu*direction))/mu**2
scores.append(a*b*(1-lr/2*(c+2*smoothness*(direction @ direction))))
return np.array(scores)
def test_independent_forward_products_match_full_anisotropic_descent():
g, k, u = quadratic()
v = torch.linalg.qr(torch.tensor([[1., 2.], [-1., 3.], [.3, -.5]], dtype=torch.float64)).Q
smoothness = float(torch.linalg.eigvalsh(k).max())
h = k+2*smoothness*torch.eye(3, dtype=torch.float64)
# The stated certificate is global for these quadratic objectives.
assert torch.linalg.eigvalsh(h-k).min() > 0
assert torch.linalg.eigvalsh(h).min() >= smoothness
z, weights = gaussian_rule(2, 4)
grad_noise = np.array([.3, -.1, .4])
hess_noise = np.diag([.2, -.1, .3])
average = np.zeros(2)
calls = [0, 0, 0]
for signs in itertools.product([-1., 1.], repeat=3):
losses = []
for index in range(3):
gradient = g.numpy()+signs[index]*grad_noise
curvature = k.numpy()+(signs[index]*hess_noise if index == 2 else 0.)
def loss(x, index=index, gradient=gradient, curvature=curvature):
calls[index] += 1
return gradient @ x+x @ curvature @ x/2
losses.append(loss)
for noise, weight in zip(z, weights):
before = sum(calls)
scores = forward_score_pair(losses, [u.numpy() @ noise, v.numpy() @ noise], .05, .003, smoothness)
assert sum(calls)-before == 13
average += weight*scores/8
expected = [float(curvature_descent_reference(g, h, basis @ basis.T, .003)[0]) for basis in [u, v]]
np.testing.assert_allclose(average, expected, rtol=1e-11, atol=1e-12)
assert calls[0] == calls[1] and calls[2]*4 == calls[0]*5
# Same-batch squaring has a nonzero extra quadratic-gradient contribution.
noise_term, _ = curvature_descent_reference(torch.tensor(grad_noise), h, u @ u.T, .003)
assert abs(float(noise_term)) > 1e-3
def test_joint_basis_two_point_mean_converges_to_structured_gradient():
generator = torch.Generator().manual_seed(130)
g = torch.randn(7, generator=generator, dtype=torch.float64)
x = torch.randn(7, 7, generator=generator, dtype=torch.float64)
k = x.T @ x
h = k+2*torch.linalg.eigvalsh(k).max()*torch.eye(7, dtype=torch.float64)
angles = np.array([.3, -.7])
d = np.stack([np.cos(angles), np.sin(angles)], axis=1)
tangent = np.stack([-np.sin(angles), np.cos(angles)], axis=1)
def basis(v):
result = np.zeros((7, 4))
result[:2, 0], result[2:4, 1], result[4:6, 2], result[6, 3] = v[0], v[0], v[1], 1.
return result
p = torch.tensor(basis(d) @ basis(d).T)
_, m = curvature_descent_reference(g, h, p, .001)
true_gradient = np.array([
float(curvature_input_gradient_reference(m[:4, :4], torch.tensor(d[0]), 2) @ torch.tensor(tangent[0])),
float(curvature_input_gradient_reference(m[4:6, 4:6], torch.tensor(d[1]), 1) @ torch.tensor(tangent[1])),
])
z, weights = gaussian_rule(4, 4)
def score(v):
directions = z @ basis(v).T
a = directions @ g.numpy()
c = np.einsum('bi,ij,bj->b', directions, h.numpy(), directions)
return float(weights @ (a**2*(1-.001*c/2)))
outer, outer_weights = gaussian_rule(2, 16)
errors = []
for delta in [.02, .01, .005]:
mean = np.zeros(2)
for v, weight in zip(outer, outer_weights):
plus = d+delta*v[:, None]*tangent
minus = d-delta*v[:, None]*tangent
plus /= np.linalg.norm(plus, axis=1, keepdims=True)
minus /= np.linalg.norm(minus, axis=1, keepdims=True)
mean += weight*(score(plus)-score(minus))/(2*delta)*v
errors.append(np.linalg.norm(mean-true_gradient))
assert np.linalg.norm(true_gradient) > .01
assert errors[1] < .3*errors[0]
assert errors[2] < .3*errors[1]
def test_nonquadratic_forward_score_has_controlled_finite_radius_bias():
# F(theta+x)=sin(theta+x), known global L=M3=M4=1, H=2-sin(theta).
theta, lr = .4, .01
g, h = np.cos(theta), 2-np.sin(theta)
z, weights = gaussian_rule(1, 48)
exact = g**2*(1-3*lr*h/2)
loss = lambda x: float(np.sin(theta+x[0]))
errors = []
for mu in [.08, .04, .02]:
mean = 0.
for direction, weight in zip(z, weights):
score = forward_score_pair([loss]*3, [direction, -direction], mu, lr, 1.)[0]
radius = abs(float(direction[0]))
a, curvature = g*direction[0], h*radius**2
b_bound, e_bound = mu**2*radius**3/6, mu**2*radius**4/12
bound = abs(1-lr*curvature/2)*(2*abs(a)*b_bound+b_bound**2)+lr/2*e_bound*(abs(a)+b_bound)**2
assert abs(score-a*a*(1-lr*curvature/2)) <= bound+1e-10
mean += weight*score
errors.append(abs(mean-exact))
assert errors[1] < .3*errors[0]
assert errors[2] < .3*errors[1]
def test_valid_upper_bounds_can_reverse_basis_ranking():
k = torch.diag(torch.tensor([100., 1.], dtype=torch.float64))
g = torch.tensor([np.sqrt(1.1), 1.], dtype=torch.float64)
p0 = torch.diag(torch.tensor([0., 1.], dtype=torch.float64))
p1 = torch.eye(2, dtype=torch.float64)-p0
scores = []
for shift in [0., 500.]:
h = k+shift*torch.eye(2, dtype=torch.float64)
assert .0005 <= 1/(3*float(torch.linalg.eigvalsh(h).max()))
scores.append([float(curvature_descent_reference(g, h, p, .0005)[0]) for p in [p0, p1]])
np.testing.assert_allclose(scores, [[.99925, 1.0175], [.62425, .605]], atol=1e-12)
assert scores[0][1] > scores[0][0] and scores[1][1] < scores[1][0]
def test_final_layernorm_global_option_loss_envelope():
gen = torch.Generator().manual_seed(591)
h, vocab = 4, 7
w = torch.randn(vocab, h, generator=gen, dtype=torch.float64)
gamma = torch.randn(h, generator=gen, dtype=torch.float64)
beta = torch.randn(h, generator=gen, dtype=torch.float64)
a = w.norm(dim=1).max()
t = np.sqrt(h)*gamma.abs().max()+beta.norm()
c = np.sqrt(h)+1
a0 = np.log(2)+np.log(vocab)+2*a*t
a1, a2 = 2*(a*c+t), 2*c
for radius in [.001, .1, 1., 10.]:
change = torch.randn(vocab*h+2*h, generator=gen, dtype=torch.float64)
change *= radius/change.norm()
dw, dg, db = change[:vocab*h].reshape_as(w), change[vocab*h:-h], change[-h:]
# Arbitrary internal activations; their norms need not be bounded.
activations = torch.randn(2, 3, h, generator=gen, dtype=torch.float64)*1000
hidden = torch.nn.functional.layer_norm(activations, (h,), gamma+dg, beta+db)
logits = hidden @ (w+dw).T
labels = torch.tensor([[0, 1, 2], [3, 4, 5]])
option_scores = logits.log_softmax(-1).gather(-1, labels[..., None]).mean(1).squeeze(-1)
loss = torch.nn.functional.cross_entropy(option_scores[None], torch.tensor([0]))
assert logits.abs().max() <= (a+radius)*(t+c*radius)+1e-10
assert loss <= a0+a1*radius+a2*radius**2
def test_local_certificate_and_growth_envelope_patch_global_upper_bound():
# F(x)=1+sin(x): nonnegative, globally <=2; local ell=G=kappa=1.
theta, radius = .3, .7
ell = gradient_bound = kappa = 1.
a0, a1, a2 = 2., 0., 0.
q = max(ell, 2*a2+2*(a1+gradient_bound)/radius+2*a0/radius**2)
k = -np.sin(theta)
anisotropic_upper = k+q+kappa
assert anisotropic_upper >= q
delta = np.concatenate([np.linspace(-20, 20, 1001), [-radius, radius, -1e-5, 1e-5]])
remainder = np.sin(theta+delta)-np.sin(theta)-np.cos(theta)*delta
assert np.all(remainder <= q*delta**2/2+1e-12)
+178
View File
@@ -0,0 +1,178 @@
"""Actual forward queries versus exact Gaussian/sign quadrature; no training."""
import itertools
from unittest.mock import patch
import numpy as np
import pytest
import torch
from test_mezo_refactor import make_trainer
from methods.large_models.trainer import seed_for
@torch.enable_grad()
def fixture(power=1):
model = torch.nn.ModuleDict({n: torch.nn.Linear(2, 1, bias=False, dtype=torch.float64)
for n in ('left', 'right')})
with torch.no_grad():
model['left'].weight.copy_(torch.tensor([[.3, -.2]]))
model['right'].weight.copy_(torch.tensor([[-.1, .4]]))
x = torch.tensor([[[1., .3], [-.4, .8]]], dtype=torch.float64)
c = torch.tensor([[[.7], [-.2]]], dtype=torch.float64)
def forward(batch):
t = (model['left'](x)*c + model['right'](x)*(1-c)).sum()/2
loss = t if power == 1 else (t.square()/2 if power == 2 else t.square()/2+.1*t**3+.02*t**4)
return loss, t
engine = make_trainer(model, forward)
engine.basis = {'left.weight': torch.tensor([[.6], [.8]], dtype=torch.float64),
'right.weight': torch.tensor([[-.8], [.6]], dtype=torch.float64)}
engine.history = {} # No EMA is needed.
loss = forward({})[0]
gs = torch.autograd.grad(loss, list(model.parameters()))
truth = {}
for (n, d), g in zip(engine.basis.items(), gs):
v = 2*g.T @ g @ d
truth[n] = v-d*(d*v).sum()
return engine, truth
def quadrature(power=1, mu=.04, eps=.06, targets=None):
"""Order 4 integrates all moments of the quartic response product exactly."""
engine, truth = fixture(power)
engine.args.zo_eps, engine.args.node_epsilon = mu, eps
names = list(engine.basis)
chosen = names if targets is None else targets
nodes, weights = np.polynomial.hermite.hermgauss(4)
nodes, weights = nodes*np.sqrt(2), weights/np.sqrt(np.pi)
mean = {n: torch.zeros_like(engine.basis[n]) for n in chosen}
second = {n: torch.zeros(2, 2, dtype=torch.float64) for n in chosen}
max_tangent = 0.
before = {n: p.detach().clone() for n, p in engine.named_parameters}
for indices in itertools.product(range(4), repeat=2):
zs = [nodes[i] for i in indices]
weight = float(np.prod([weights[i] for i in indices]))/16
engine.directions = lambda seed: iter((n, engine.parameter_map[n],
torch.tensor([[z]], dtype=torch.float64)) for n, z in zip(names, zs))
for signs in itertools.product((0, 1), repeat=4):
patterns = {seed_for(123, j): torch.tensor(signs[2*j:2*j+2]).reshape(1, 2)
for j in range(2)}
def draw(low, high, size, *, device, generator):
return patterns[generator.initial_seed()].to(device)
engine._estimate = None
with patch('torch.randint', draw):
result = engine.coverage_gradient_probe({}, 5, 123, chosen)
assert result['cost'] == 3
for n, v in result['gradients'].items():
mean[n] += weight*v
second[n] += weight*torch.outer(v.flatten(), v.flatten())
max_tangent = max(max_tangent, abs(float((v*engine.basis[n]).sum())))
for n, p in engine.named_parameters:
torch.testing.assert_close(p, before[n], atol=2e-13, rtol=0)
covariance = {n: second[n]-torch.outer(mean[n].flatten(), mean[n].flatten()) for n in chosen}
return dict(mean=mean, truth=truth, covariance=covariance,
max_error=max(float((mean[n]-truth[n]).abs().max()) for n in chosen),
max_tangent=max_tangent, forwards=engine.counts['training'])
@pytest.mark.parametrize('power', [1, 2])
def test_exact_linear_and_quadratic_means(power):
result = quadrature(power)
assert result['max_error'] < 1e-11
assert result['max_tangent'] < 1e-12
assert result['forwards'] == 768
def test_smooth_finite_difference_bias_is_second_order():
# Vary each radius separately; extrapolate the other radius to zero.
for varying in ('mu', 'eps'):
errors = []
for radius in (.08, .04, .02):
kwargs = dict(mu=1e-5, eps=1e-5)
kwargs[varying] = radius
errors.append(quadrature(4, **kwargs)['max_error'])
assert 3.8 < errors[0]/errors[1] < 4.2
assert 3.8 < errors[1]/errors[2] < 4.2
@torch.no_grad()
def test_probe_reuses_exact_old_basis_training_update_and_rng():
engine, _ = fixture(4)
reference, _ = fixture(4)
rng = torch.random.get_rng_state()
old = {n: d.clone() for n, d in engine.basis.items()}
result = engine.coverage_gradient_probe({}, 41, 123, list(old))
assert result['cost'] == 3
reference.zo_step(reference.model, {}, 41)
assert result['response'] == reference._estimate['slope']
with torch.no_grad():
engine.zo_update(engine.model)
reference.zo_update(reference.model)
for (_, p), (_, q) in zip(engine.named_parameters, reference.named_parameters):
torch.testing.assert_close(p, q, atol=1e-14, rtol=0)
for n in old:
assert torch.equal(old[n], engine.basis[n])
assert torch.equal(rng, torch.random.get_rng_state())
assert all(not m._forward_hooks for m in engine.model.modules())
def test_joint_covariance_penalty_matches_closed_form():
joint = quadrature()
engine, _ = fixture()
x = torch.tensor([[1., .3], [-.4, .8]], dtype=torch.float64)
sensitivities = [torch.tensor([[.7], [-.2]], dtype=torch.float64)/2,
torch.tensor([[.3], [1.2]], dtype=torch.float64)/2]
names = list(engine.basis)
gs = [a.T @ x for a in sensitivities]
coefficients = [g @ engine.basis[n] for n, g in zip(names, gs)]
norm_a = sum(float(a.square().sum()) for a in coefficients)
for i, n in enumerate(names):
separate = quadrature(targets=[n])
d = engine.basis[n]
pi = torch.eye(2, dtype=d.dtype)-d @ d.T
j = 1-i
factor = norm_a*float(sensitivities[j].square().sum()) + 2*float(
(sensitivities[j] @ coefficients[j]).square().sum())
expected = 4*factor*pi @ x.T @ x @ pi
observed = joint['covariance'][n]-separate['covariance'][n]
torch.testing.assert_close(observed, expected, atol=1e-11, rtol=1e-10)
def test_failed_node_query_removes_hooks_and_leaves_no_pending_update():
engine, _ = fixture()
forward = engine._forward_outputs
calls = 0
def fail(batch):
nonlocal calls
calls += 1
if calls == 3:
raise RuntimeError('node failed')
return forward(batch)
engine._forward_outputs = fail
with pytest.raises(RuntimeError, match='node failed'):
engine.coverage_gradient_probe({}, 41, 123, list(engine.basis))
assert getattr(engine, '_estimate', None) is None
assert all(not m._forward_hooks for m in engine.model.modules())
@torch.no_grad()
def test_downstream_sketch_uses_clean_inputs():
model = torch.nn.Sequential(torch.nn.Linear(2, 2, bias=False, dtype=torch.float64),
torch.nn.Linear(2, 1, bias=False, dtype=torch.float64))
model[0].weight.copy_(torch.tensor([[.2, .4], [-.3, .5]]))
model[1].weight.copy_(torch.tensor([[.7, -.2]]))
x = torch.tensor([[[1., 2.], [.3, -.1]]], dtype=torch.float64)
engine = make_trainer(model, lambda batch: (model(x).square().mean(), None))
engine.basis = {n: torch.tensor([[1.], [0.]], dtype=torch.float64)
for n in engine.linear_map}
v_clean = model[0](x).sum((0, 1))[:, None]
with patch('torch.randint', lambda low, high, size, **kwargs:
torch.ones(size, dtype=torch.long, device=kwargs['device'])):
result = engine.coverage_gradient_probe({}, 41, 123, list(engine.basis))
d = engine.basis['1.weight']
factor = 2*result['response']*result['node_response']
expected = factor*(v_clean-d*(d*v_clean).sum())
torch.testing.assert_close(result['gradients']['1.weight'], expected)
z0 = next(z for n, _, z in engine.directions(41) if n == '0.weight')
wrong_v = v_clean+2*engine.args.node_epsilon*z0
wrong = factor*(wrong_v-d*(d*wrong_v).sum())
assert float((wrong-expected).norm()) > 1e-8
+42
View File
@@ -0,0 +1,42 @@
"""Full step: actual old-basis SGD, magnitude-preserving basis retraction, budgets."""
import pytest
import torch
from test_history_free_coverage import fixture
@torch.no_grad()
def test_full_step_matches_derived_retraction_and_old_basis_sgd():
engine, _ = fixture(4)
reference, _ = fixture(4)
engine.args.basis_lr = reference.args.basis_lr = .003
from methods.large_models.trainer import seed_for
probe = reference.coverage_gradient_probe({}, 41, seed_for(42, 1801, 1), list(reference.basis))
expected = {n: torch.nn.functional.normalize(d+.003*probe['gradients'][n], dim=0)
for n, d in reference.basis.items()}
reference.zo_update(reference.model)
_, event = engine.coverage_step({}, 41)
assert event['cost'] == 1 and event['total_step_cost'] == 3
assert event['variant'] == 'history_free_coverage_gradient_v1'
for (_, p), (_, q) in zip(engine.named_parameters, reference.named_parameters):
torch.testing.assert_close(p, q, atol=1e-14, rtol=0)
for n in expected:
torch.testing.assert_close(engine.basis[n], expected[n], atol=1e-14, rtol=0)
assert engine._estimate is None and engine.history == {}
@pytest.mark.parametrize('remaining', [2, 3])
@torch.no_grad()
def test_refresh_reserves_three_queries(remaining):
engine, _ = fixture()
engine.args.basis_lr = .003
engine.args.main_forward_budget = remaining
_, event = engine.coverage_step({}, 41)
assert engine.used() == remaining
assert (event is not None) == (remaining == 3)
def test_cli_selects_explicit_history_free_variant(tmp_path):
from methods.large_models.run import parse_args
args = parse_args(['--trainer', 'node', '--node_update', 'history_free',
'--output_dir', str(tmp_path)])
assert args.node_update == 'history_free'
+50
View File
@@ -0,0 +1,50 @@
"""Small numerical checks, not pretrained-model performance evidence."""
from types import SimpleNamespace
import copy
import torch
from transformers import OPTConfig,OPTForCausalLM
from experiments_codebase.task import Task,top_basis
def tiny():
torch.manual_seed(42)
t=Task.__new__(Task);t.device=torch.device('cpu')
t.args=SimpleNamespace(task='sst2',mu=.001,history_beta=.9,node_queries=2,node_epsilon=.001)
t.model=OPTForCausalLM(OPTConfig(vocab_size=32,hidden_size=16,ffn_dim=24,num_hidden_layers=3,num_attention_heads=2,max_position_embeddings=32,dropout=0,attention_dropout=0)).eval()
t.named_parameters=list(t.model.named_parameters());t.parameter_map=dict(t.named_parameters);t.parameters=list(t.parameter_map.values())
t.linear_map={n+'.weight':m for n,m in t.model.named_modules() if isinstance(m,torch.nn.Linear) and n+'.weight' in t.parameter_map}
t.label_ids=[5,7];t.counts=dict(training=0,calibration=0,evaluation=0,diagnostic=0)
t.structured={};t.noise=None;t.handles=[];t.history={}
inputs=dict(input_ids=torch.tensor([[2,4,6,3],[2,5,9,3]]),attention_mask=torch.ones(2,4,dtype=torch.long),labels=torch.tensor([0,1]))
return t,inputs
@torch.no_grad()
def test_basis_restoration_and_switch():
t,x=tiny();t.configure(x);clean=t.call(x,'diagnostic')[0].clone();old=t.dense_snapshot()
t.shifted(x,t.bases(),t.directions(91),.001,old)
assert all(torch.equal(t.parameter_map[n],v) for n,v in old.items())
torch.testing.assert_close(clean,t.call(x,'diagnostic')[0],rtol=0,atol=0)
t.update(x,33,1e-5);before=t.call(x,'diagnostic')[0].clone()
t.switch({n:-d for n,d in t.bases().items()})
torch.testing.assert_close(before,t.call(x,'diagnostic')[0],rtol=0,atol=0)
t.close()
@torch.no_grad()
def test_same_basis_probe_has_zero_gain_and_five_queries():
t,x=tiny();t.configure(x);before=t.counts['training'];old=[p.clone() for p in t.parameters]
event=t.probe(x,x,t.bases(),17,1e-5)
assert event['gain']==0 and t.counts['training']-before==5
assert all(torch.equal(p,v) for p,v in zip(t.parameters,old));t.close()
@torch.no_grad()
def test_node_refresh_preserves_function_and_charges_seven_queries():
t,x=tiny();t.configure(x);t.configure_history();t.update(x,18,1e-5)
before=t.call(x,'diagnostic')[0].clone();q=t.counts['training'];event=t.node_refresh(x,19)
assert t.counts['training']-q==7
assert len(event)==3
torch.testing.assert_close(before,t.call(x,'diagnostic')[0],rtol=0,atol=0);t.close()
def test_pca_order_and_orthogonality():
x=torch.tensor([[9.,0,0,0],[0,2.,0,0],[0,0,1.,0]])
d=top_basis(x,2)
torch.testing.assert_close(d.T@d,torch.eye(2))
assert abs(float(d[0,0]))>.9999 and abs(float(d[1,1]))>.9999
+226
View File
@@ -0,0 +1,226 @@
"""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)
+239
View File
@@ -0,0 +1,239 @@
"""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)])