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