"""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