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.
702 lines
39 KiB
Python
702 lines
39 KiB
Python
"""MeZO-style OurTrainer on the supported HF Trainer API, with structured ZO branches."""
|
|
from datetime import datetime,timezone
|
|
import math
|
|
import os
|
|
from pathlib import Path
|
|
import time
|
|
import numpy as np
|
|
import torch
|
|
from transformers import Trainer
|
|
from transformers.trainer_utils import TrainOutput
|
|
from experiments_codebase.paths import save,append
|
|
from .data import ProtocolSampler,seed_for
|
|
from .losses import LegacyLoss
|
|
from .native_losses import MeZOLoss
|
|
from .logging_utils import figures,memory
|
|
|
|
def top_basis(x, rank=1):
|
|
"""从[token数, 输入维度]的激活提取主方向,返回[输入维度, rank]。
|
|
|
|
这里按未中心化激活做SVD,不减去均值;当前训练入口只支持rank=1。
|
|
"""
|
|
x = x.float()
|
|
if x.shape[0] < x.shape[1]:
|
|
values, vectors = torch.linalg.eigh(x @ x.T)
|
|
ids = torch.arange(len(values) - 1, len(values) - rank - 1, -1, device=x.device)
|
|
if values[ids[-1]] <= values[-1] * 1e-08:
|
|
raise ValueError('Insufficient activation rank')
|
|
d = x.T @ (vectors[:, ids] / values[ids].sqrt())
|
|
return torch.linalg.qr(d, mode='reduced').Q.contiguous()
|
|
return torch.linalg.svd(x, full_matrices=False).Vh[:rank].T.contiguous()
|
|
|
|
|
|
def curvature_descent_reference(g, h, p, lr, n=1, quadratic_mu=0.):
|
|
"""Small-matrix numerical reference, not a model-training estimator.
|
|
|
|
Implements Proposition 2.1 with supplied g and effective upper bound h.
|
|
Nonzero quadratic_mu is exact only for a quadratic with Hessian equal to h.
|
|
Returns the value and its Euclidean derivative with respect to p.
|
|
"""
|
|
if n < 1 or int(n) != n or lr <= 0 or quadratic_mu < 0:
|
|
raise ValueError('Invalid reference parameters')
|
|
a = torch.outer(g, g)
|
|
pg = p @ g
|
|
s = g @ pg
|
|
t = torch.trace(p @ h)
|
|
alpha, beta = lr * (1 + 1/n) / 2, lr / (2*n)
|
|
value = s - alpha * (pg @ h @ pg) - beta * s * t
|
|
gradient = a - alpha * (h @ p @ a + a @ p @ h) - beta * (t*a + s*h)
|
|
if quadratic_mu:
|
|
ph = p @ h
|
|
t2 = torch.trace(ph @ ph)
|
|
t3 = torch.trace(ph @ ph @ ph)
|
|
factor = lr * quadratic_mu**2 / (8*n)
|
|
value = value - factor * (t**3 + 6*t*t2 + 8*t3)
|
|
gradient = gradient - factor * ((3*t**2 + 6*t2)*h
|
|
+ 12*t*(h @ p @ h) + 24*(h @ p @ h @ p @ h))
|
|
return value, gradient
|
|
|
|
|
|
def curvature_input_gradient_reference(projection_gradient, d, output_size):
|
|
"""Contract one Linear block of grad_P for P=I_out kron dd.T; small tests only."""
|
|
k = d.numel()
|
|
blocks = projection_gradient.reshape(output_size, k, output_size, k)
|
|
c = sum(blocks[a, :, a, :] for a in range(output_size))
|
|
gradient = 2 * c @ d
|
|
return gradient - d * (d * gradient).sum()
|
|
|
|
|
|
class OurTrainer(Trainer):
|
|
def __init__(self,*args,tokenizer=None,**kwargs):
|
|
if tokenizer is not None:kwargs['processing_class']=tokenizer
|
|
super().__init__(*args,**kwargs)
|
|
self.tokenizer_for_zo=self.processing_class
|
|
self.loss_backend=LegacyLoss(self.model,self.processing_class,self.args.task_name) if self.args.data_protocol=='legacy' else MeZOLoss(self.model)
|
|
self.init_zo()
|
|
self._last_outputs=None;self._estimate=None;self.current_lr=self.args.learning_rate
|
|
self.curve=[];self.latest={};self.started=time.monotonic()
|
|
|
|
def _get_train_sampler(self,train_dataset=None):
|
|
if self.args.data_protocol=='mezo':return super()._get_train_sampler(train_dataset)
|
|
return ProtocolSampler(self.train_dataset if train_dataset is None else train_dataset,self.args.seed)
|
|
|
|
def compute_loss(self,model,inputs,return_outputs=False,num_items_in_batch=None):
|
|
self._last_outputs=self.loss_backend(inputs)
|
|
loss=self._last_outputs[0].mean()
|
|
return (loss,{'loss':loss,'logits':self._last_outputs[1]}) if return_outputs else loss
|
|
|
|
# This function is copied verbatim from pinned MeZO OurTrainer. See MEZO_REUSE.json.
|
|
def zo_forward(self, model, inputs):
|
|
"""
|
|
Get (no gradient) loss from the model. Dropout is turned off too.
|
|
"""
|
|
model.eval()
|
|
if self.args.non_diff:
|
|
# Non-differentiable objective (may require autoregressive generation)
|
|
return self.zo_forward_nondiff(model, inputs)
|
|
|
|
with torch.inference_mode():
|
|
inputs = self._prepare_inputs(inputs)
|
|
with self.compute_loss_context_manager():
|
|
loss = self.compute_loss(model, inputs)
|
|
if self.args.n_gpu > 1:
|
|
# Warning: this is copied from the original Huggingface Trainer. Untested.
|
|
loss = loss.mean() # mean() to average on multi-gpu parallel training
|
|
return loss.detach()
|
|
|
|
def _forward_outputs(self,inputs):
|
|
self.zo_forward(self.model,inputs)
|
|
return self._last_outputs
|
|
|
|
def init_zo(self):
|
|
"""只保存模型参数、各层输入基和node历史;不创建B、C或常驻hook。"""
|
|
self.named_parameters = list(self.model.named_parameters()) # tied权重只出现一次。
|
|
self.parameter_map = dict(self.named_parameters)
|
|
self.parameters = list(self.parameter_map.values())
|
|
self.linear_map = {
|
|
name+'.weight': module for name, module in self.model.named_modules()
|
|
if isinstance(module, torch.nn.Linear) and name+'.weight' in self.parameter_map
|
|
}
|
|
self.basis = {}
|
|
self.history = {}
|
|
self.counts = dict(training=0, calibration=0, evaluation=0, diagnostic=0)
|
|
|
|
def call(self, inputs, category='training'):
|
|
self.counts[category] += 1
|
|
loss, logits = self._forward_outputs(inputs)
|
|
if not bool(torch.isfinite(loss).all()):
|
|
raise FloatingPointError('Nonfinite loss')
|
|
return loss, logits
|
|
|
|
def collect_basis(self, inputs, category='training'):
|
|
"""一次前向读取各Linear的有效token输入,求未中心化激活的首个右奇异向量。"""
|
|
mask = inputs['attention_mask'].bool().reshape(-1)
|
|
bases, handles = {}, []
|
|
for name, module in self.linear_map.items():
|
|
def capture(module, args, name=name):
|
|
x = args[0].reshape(-1, args[0].shape[-1])[mask]
|
|
d = top_basis(x).to(dtype=self.parameter_map[name].dtype)
|
|
if name in self.basis and float((d.T @ self.basis[name]).sum()) < 0:
|
|
d = -d
|
|
bases[name] = d
|
|
handles.append(module.register_forward_pre_hook(capture))
|
|
try:
|
|
self.call(inputs, category)
|
|
finally:
|
|
for handle in handles:
|
|
handle.remove()
|
|
if len(bases) != len(self.linear_map):
|
|
raise RuntimeError('Not every linear layer executed')
|
|
return bases
|
|
|
|
def configure_basis(self, inputs):
|
|
self.basis = self.collect_basis(inputs, 'calibration')
|
|
self.model.requires_grad_(False)
|
|
|
|
def directions(self, seed):
|
|
"""按种子逐参数重建方向;不保存全模型噪声。Linear方向为z @ D.T。"""
|
|
generator = torch.Generator(device=self.args.device).manual_seed(seed)
|
|
for name, p in self.named_parameters:
|
|
z = torch.randn((p.shape[0], 1) if name in self.basis else p.shape,
|
|
device=p.device, dtype=p.dtype, generator=generator)
|
|
yield name, p, z
|
|
|
|
def shifted(self, inputs, bases, seed, scale, response=None):
|
|
"""原地加扰动查询,再按同一种子减回;无权重备份,FP32恢复允许舍入误差。"""
|
|
applied = 0
|
|
try:
|
|
for name, p, z in self.directions(seed):
|
|
direction = z if response is None else z * response
|
|
if name in bases:
|
|
direction = direction @ bases[name].T
|
|
p.add_(direction, alpha=scale)
|
|
applied += 1
|
|
return self.call(inputs)[0].detach().clone()
|
|
finally:
|
|
# 前向异常也减回;扰动中途失败时,只恢复已经加过扰动的参数。
|
|
for index, (name, p, z) in enumerate(self.directions(seed)):
|
|
if index >= applied:
|
|
break
|
|
direction = z if response is None else z * response
|
|
if name in bases:
|
|
direction = direction @ bases[name].T
|
|
p.add_(direction, alpha=-scale)
|
|
|
|
def zo_step(self, model, inputs, seed):
|
|
clean = self.call(inputs)[0]
|
|
plus = self.shifted(inputs, self.basis, seed, self.args.zo_eps)
|
|
slope = float((plus - clean).double().mean()) / self.args.zo_eps
|
|
if not math.isfinite(slope):
|
|
raise FloatingPointError('Nonfinite ZO response')
|
|
self.projected_grad = slope
|
|
self._estimate = dict(seed=seed, clean=clean, slope=slope)
|
|
return clean.mean()
|
|
|
|
@torch.no_grad()
|
|
def coverage_gradient_probe(self, inputs, seed, node_seed, targets):
|
|
"""Two ordinary ZO queries plus one joint node query.
|
|
|
|
At fixed weights/bases, estimate 2 (I-dd.T) G.T G d without history.
|
|
See HISTORY_FREE_COVERAGE.md for the linear-response proof and bias.
|
|
Clean hooks retain only X.T @ signs; perturbed downstream inputs must
|
|
not replace these clean sketches. Only selected output-sized Gaussian
|
|
vectors are retained, never full parameter noise or activations.
|
|
|
|
This helper does not select/install bases; coverage_step owns the update.
|
|
The pending SGD estimate belongs to the OLD bases: consume it with
|
|
zo_update before installing any candidate for the next iteration.
|
|
"""
|
|
if getattr(self, '_estimate', None) is not None:
|
|
raise RuntimeError('Consume the pending weight update before probing')
|
|
targets = list(targets)
|
|
if not targets or len(set(targets)) != len(targets):
|
|
raise ValueError('Coverage targets must be nonempty and unique')
|
|
if any(n not in self.basis or n not in self.linear_map for n in targets):
|
|
raise ValueError('Coverage targets must be initialized Linear weights')
|
|
mu, epsilon = self.args.zo_eps, self.args.node_epsilon
|
|
if not all(math.isfinite(x) and x > 0 for x in (mu, epsilon)):
|
|
raise ValueError('Coverage perturbation scales must be positive and finite')
|
|
aliases = list(self.model.named_parameters(remove_duplicate=False))
|
|
for n in targets:
|
|
if sum(p is self.parameter_map[n] for _, p in aliases) != 1:
|
|
raise ValueError('Coverage probes require untied target weights')
|
|
# Reuse exactly the Gaussian coefficients of the ordinary weight query.
|
|
noises = {n: z for n, _, z in self.directions(seed) if n in targets}
|
|
sketches = {}
|
|
shapes = {}
|
|
before = self.used()
|
|
|
|
def query(inject):
|
|
handles, seen = [], set()
|
|
def hook_for(n, index):
|
|
def hook(module, args, output):
|
|
if n in seen:
|
|
raise ValueError('Coverage target Linear must execute once per forward')
|
|
seen.add(n)
|
|
x = args[0]
|
|
if inject and tuple(x.shape) != shapes[n]:
|
|
raise ValueError('Coverage target shape changed across queries')
|
|
gen = torch.Generator(device=x.device).manual_seed(seed_for(node_seed, index))
|
|
signs = (2*torch.randint(0, 2, x.shape[:-1], device=x.device,
|
|
generator=gen)-1).to(x.dtype)
|
|
if inject:
|
|
return output + epsilon*signs[..., None]*noises[n].flatten()
|
|
shapes[n] = tuple(x.shape)
|
|
# The scalar loss already contains its batch/token reduction.
|
|
# Summation here is essential: another mean changes the gradient.
|
|
sketches[n] = x.reshape(-1, x.shape[-1]).T @ signs.reshape(-1, 1)
|
|
return hook
|
|
try:
|
|
for index, n in enumerate(targets):
|
|
handles.append(self.linear_map[n].register_forward_hook(hook_for(n, index)))
|
|
loss = self.call(inputs)[0]
|
|
if seen != set(targets):
|
|
raise ValueError('Every coverage target must execute in each forward')
|
|
return loss
|
|
finally:
|
|
for handle in handles:
|
|
handle.remove()
|
|
|
|
clean = query(False)
|
|
plus = self.shifted(inputs, self.basis, seed, mu)
|
|
slope = float((plus-clean).double().mean())/mu # Same arithmetic as zo_step.
|
|
node_loss = query(True)
|
|
node_slope = float((node_loss-clean).double().mean())/epsilon
|
|
if not all(math.isfinite(x) for x in (slope, node_slope)):
|
|
raise FloatingPointError('Nonfinite coverage response')
|
|
gradients = {}
|
|
for n in targets:
|
|
d, v = self.basis[n], sketches[n]
|
|
gradients[n] = 2*slope*node_slope*(v-d*(d*v).sum())
|
|
if not bool(torch.isfinite(gradients[n]).all()):
|
|
raise FloatingPointError('Nonfinite coverage gradient')
|
|
self._estimate = dict(seed=seed, clean=clean, slope=slope)
|
|
return dict(variant='history_free_coverage_probe_v1', gradients=gradients,
|
|
response=slope, node_response=node_slope, cost=self.used()-before)
|
|
|
|
@torch.no_grad()
|
|
def coverage_step(self, inputs, seed):
|
|
"""Current-batch coverage gradient; old-basis SGD, then retract new bases."""
|
|
step, args = self.state.global_step, self.args
|
|
if step == 0 or step % args.refresh_every or self.used()+3 > args.main_forward_budget:
|
|
return self.fix_step(inputs, seed)
|
|
before = self.used()
|
|
node_seed = seed_for(args.seed, 1801, step)
|
|
probe = self.coverage_gradient_probe(inputs, seed, node_seed, list(self.basis))
|
|
new, layers = {}, {}
|
|
for n, gradient in probe['gradients'].items():
|
|
d = self.basis[n]
|
|
candidate = d+args.basis_lr*gradient
|
|
norm = float(candidate.norm())
|
|
if not math.isfinite(norm) or norm == 0:
|
|
raise FloatingPointError('Nonfinite coverage basis retraction')
|
|
new[n] = candidate/norm
|
|
layers[n] = dict(gradient_norm=float(gradient.norm()),
|
|
overlap=float((d*new[n]).sum().square()))
|
|
# The saved response belongs to the old direction. Install only after SGD.
|
|
result = self.zo_update(self.model)
|
|
self.basis.update(new)
|
|
event = dict(step=step, variant='history_free_coverage_gradient_v1',
|
|
seed=seed, node_seed=node_seed, response=probe['response'],
|
|
node_response=probe['node_response'], basis_lr=args.basis_lr,
|
|
layers=layers, cost=self.used()-before-2, total_step_cost=self.used()-before,
|
|
main_forwards=self.used(), basis_installation='after_old_basis_sgd')
|
|
return result, event
|
|
|
|
|
|
def zo_update(self, model):
|
|
estimate = self._estimate
|
|
lr = self.current_lr
|
|
self._estimate = None
|
|
slope = estimate['slope']
|
|
square = 0
|
|
for n, p, z in self.directions(estimate['seed']):
|
|
g = z.mul_(slope)
|
|
square += float(g.float().square().sum()) * lr ** 2
|
|
# Linear: g is [dout, 1]; lift it into the full weight matrix.
|
|
delta = g @ self.basis[n].T if n in self.basis else g
|
|
p.add_(delta, alpha=-lr)
|
|
if n in self.history:
|
|
self.history[n].mul_(self.args.history_beta).add_(g, alpha=1 - self.args.history_beta)
|
|
return dict(batch_loss=float(estimate['clean'].mean()), response=slope, update_norm=math.sqrt(square), learning_rate=lr)
|
|
|
|
def fix_step(self, inputs, seed):
|
|
"""The basis is initialized once; every step is two forwards and SGD."""
|
|
before = self.used()
|
|
self.zo_step(self.model, inputs, seed)
|
|
result = self.zo_update(self.model)
|
|
assert self.used() - before == 2
|
|
return result, None
|
|
|
|
|
|
def adjust_step(self, inputs, seed):
|
|
"""Every r updates, compare one old/new virtual SGD step."""
|
|
args = self.args
|
|
step = self.state.global_step
|
|
event = None
|
|
due = step > 0 and step % args.refresh_every == 0
|
|
if due and self.used() + 6 + 2 <= args.main_forward_budget:
|
|
before = self.used()
|
|
new = self.collect_basis(self.probe_batch())
|
|
trial = self.adjust_probe(self.probe_batch(), self.probe_batch(), new,
|
|
seed_for(args.seed, 91, step), self.current_lr)
|
|
accept = trial['gain'] > 0
|
|
if accept:
|
|
self.basis.update(new)
|
|
event = dict(step=step, variant='adjust_single_probe_v1', trial=trial,
|
|
accepted=bool(accept), main_forwards=self.used(), cost=self.used()-before)
|
|
result, _ = self.fix_step(inputs, seed)
|
|
return result, event
|
|
|
|
def node_step(self, inputs, seed):
|
|
"""Control: refresh every r updates, without comparing old/new bases."""
|
|
args = self.args
|
|
step = self.state.global_step
|
|
cost = 1 + len(self.history) * args.node_queries
|
|
due = step > 0 and step % args.refresh_every == 0
|
|
if not due or self.used() + cost + 2 > args.main_forward_budget:
|
|
return self.fix_step(inputs, seed)
|
|
before = self.used()
|
|
new, metrics = self.node_proposal(self.probe_batch(), seed_for(args.seed, 705, step))
|
|
self.basis.update(new)
|
|
for name in new:
|
|
self.history[name].zero_()
|
|
event = dict(step=step, variant='node_unconditional_refresh_control_v1', layers=metrics,
|
|
learning_rate=self.current_lr, accepted=bool(new),
|
|
main_forwards=self.used(), cost=self.used()-before)
|
|
return self.fix_step(inputs, seed)[0], event
|
|
|
|
def adjust_probe(self, inputs, reference, new, seed, lr):
|
|
clean = self.call(inputs)[0]
|
|
a0 = float((self.shifted(inputs, self.basis, seed, self.args.zo_eps) - clean).double().mean()) / self.args.zo_eps
|
|
a1 = float((self.shifted(inputs, new, seed, self.args.zo_eps) - clean).double().mean()) / self.args.zo_eps
|
|
l0 = self.shifted(reference, self.basis, seed, -lr, response=a0)
|
|
l1 = self.shifted(reference, new, seed, -lr, response=a1)
|
|
return dict(gain=float((l0 - l1).double().mean()), old_loss=float(l0.mean()), new_loss=float(l1.mean()))
|
|
|
|
@torch.no_grad()
|
|
def curvature_refresh(self, batches, seed, tangent_seed, *, certified_smoothness=None,
|
|
basis_lr, basis_radius):
|
|
"""Plan section 6: full n=1 anisotropic objective, 13 main forwards.
|
|
|
|
Caller supplies independent A/B/C batches and a proven global L for F.
|
|
Numeric positivity below does not certify L. This conditional API is not
|
|
With certified_smoothness=None, explicitly use the user-authorized local
|
|
Hessian engineering variant; no upper-bound guarantee is claimed.
|
|
"""
|
|
mu, lr = self.args.zo_eps, self.current_lr
|
|
values = (basis_lr, basis_radius, mu, lr)
|
|
if certified_smoothness is not None:
|
|
values += (certified_smoothness,)
|
|
if not all(math.isfinite(x) and x > 0 for x in values):
|
|
raise ValueError('Curvature selection requires positive finite L, rho, delta, mu and eta')
|
|
if len(batches) != 3 or not self.basis:
|
|
raise ValueError('Curvature selection requires three independent batches and initialized bases')
|
|
before = self.used()
|
|
generator = torch.Generator(device=self.args.device).manual_seed(tangent_seed)
|
|
tangents, plus, minus = {}, {}, {}
|
|
for name, d in self.basis.items():
|
|
v = torch.randn(d.shape, device=d.device, dtype=d.dtype, generator=generator)
|
|
v -= d * (d * v).sum() # Tangent Gaussian; do not normalize v.
|
|
tangents[name] = v
|
|
plus[name] = torch.nn.functional.normalize(d + basis_radius*v, dim=0)
|
|
minus[name] = torch.nn.functional.normalize(d - basis_radius*v, dim=0)
|
|
# Stream the shared latent noise. Unit bases imply ||U z||^2=||z||^2.
|
|
norm_square = sum(float(z.double().square().sum()) for _, _, z in self.directions(seed))
|
|
clean_c = self.call(batches[2])[0].detach().clone().double().mean()
|
|
scores, observations = [], []
|
|
for bases in (plus, minus):
|
|
responses = []
|
|
for batch in batches[:2]:
|
|
fp = self.shifted(batch, bases, seed, mu).double().mean()
|
|
fm = self.shifted(batch, bases, seed, -mu).double().mean()
|
|
responses.append(float(fp-fm)/(2*mu))
|
|
fp = self.shifted(batches[2], bases, seed, mu).double().mean()
|
|
fm = self.shifted(batches[2], bases, seed, -mu).double().mean()
|
|
curvature = float(fp-2*clean_c+fm)/mu**2
|
|
upper_curvature = curvature + (0. if certified_smoothness is None else 2*certified_smoothness*norm_square)
|
|
score = responses[0]*responses[1]*(1-lr*upper_curvature/2)
|
|
scores.append(score)
|
|
observations.append(dict(responses=responses, curvature=curvature,
|
|
upper_curvature=upper_curvature, score=score))
|
|
q = (scores[0]-scores[1])/(2*basis_radius)
|
|
if not all(math.isfinite(x) for x in (*scores, q)):
|
|
raise FloatingPointError('Nonfinite curvature basis score/gradient')
|
|
updated, overlaps = {}, {}
|
|
gradient_square = 0.
|
|
for name, d in self.basis.items():
|
|
gradient = q*tangents[name] # Keep magnitude; no sign or clipping.
|
|
candidate = d + basis_lr*gradient
|
|
norm = float(candidate.double().norm())
|
|
if not math.isfinite(norm) or norm == 0:
|
|
raise FloatingPointError('Nonfinite curvature basis update')
|
|
updated[name] = candidate/norm
|
|
gradient_square += float(gradient.double().square().sum())
|
|
overlaps[name] = float((d.double()*updated[name].double()).sum().square())
|
|
assert self.used()-before == 13
|
|
self.basis.update(updated)
|
|
return dict(variant='local_curvature_gradient_v1' if certified_smoothness is None else 'curvature_descent_cross_batch_v1', cost=self.used()-before,
|
|
curvature_quantity='local_hessian' if certified_smoothness is None else 'certified_quadratic_upper_bound',
|
|
main_forwards=self.used(), seed=seed, tangent_seed=tangent_seed,
|
|
certified_smoothness=certified_smoothness, basis_lr=basis_lr,
|
|
basis_radius=basis_radius, weight_radius=mu, learning_rate=lr,
|
|
probes=observations, score_difference=scores[0]-scores[1],
|
|
difference_quotient=q, gradient_norm=math.sqrt(gradient_square),
|
|
direction_norm_square=norm_square, overlaps=overlaps)
|
|
|
|
@torch.no_grad()
|
|
def curvature_step(self, inputs, seed, *, selection_batches, certified_smoothness=None,
|
|
basis_lr, basis_radius):
|
|
"""Conditional full step; inputs/seed must be fresh versus selection.
|
|
|
|
selection_batches is a callable drawing independent A/B/C on refresh only.
|
|
Existing HF RandomSampler training is not asserted to be an iid oracle.
|
|
"""
|
|
step = self.state.global_step
|
|
event = None
|
|
if step > 0 and step % self.args.refresh_every == 0 and self.used()+15 <= self.args.main_forward_budget:
|
|
selection_seed = seed_for(self.args.seed, 1701, step)
|
|
tangent_seed = seed_for(self.args.seed, 1702, step)
|
|
if seed == selection_seed:
|
|
raise ValueError('Training and selection directions must have independent seeds')
|
|
event = self.curvature_refresh(selection_batches(), selection_seed, tangent_seed,
|
|
certified_smoothness=certified_smoothness, basis_lr=basis_lr,
|
|
basis_radius=basis_radius)
|
|
event['step'] = step
|
|
return self.fix_step(inputs, seed)[0], event
|
|
|
|
def configure_history(self):
|
|
names = [n for n in self.basis if n.endswith('self_attn.v_proj.weight')]
|
|
if len(names) < 3:
|
|
raise ValueError('Node proposal needs three v_proj layers')
|
|
ids = sorted(set((min(len(names) - 1, int(len(names) * v / 24)) for v in (15, 17, 19))))
|
|
if len(ids) < 3:
|
|
ids = list(range(len(names) - 3, len(names)))
|
|
self.history = {names[i]: self.parameter_map[names[i]].new_zeros(self.parameter_map[names[i]].shape[0], 1) for i in ids}
|
|
|
|
def node_proposal(self, inputs, seed):
|
|
"""Estimate G.T @ p using node probes, then normalize it into a basis.
|
|
|
|
p is the normalized EMA of projected coefficient gradients G @ d.
|
|
The sketch estimates a vector, not the scalar coverage s = ||G @ d||^2.
|
|
"""
|
|
clean, logits = self.call(inputs)
|
|
mask = inputs['attention_mask'].bool()
|
|
new = {}
|
|
metrics = {}
|
|
if self.args.task_name.lower() == 'sst2':
|
|
residual = logits.softmax(1)[:, 1] - inputs['labels']
|
|
margin = logits[:, 1] - logits[:, 0]
|
|
for ni, (n, hist) in enumerate(self.history.items()):
|
|
norm = float(hist.norm())
|
|
if norm <= 1e-20:
|
|
metrics[n] = {'skipped': 'zero history'}
|
|
continue
|
|
p = hist.flatten() / norm
|
|
est = []
|
|
for k in range(self.args.node_queries):
|
|
gen = torch.Generator(device=self.args.device).manual_seed(seed_for(seed, ni, k))
|
|
eta = (torch.randint(0, 2, mask.shape, generator=gen, device=self.args.device) * 2 - 1) * mask
|
|
features = {}
|
|
|
|
def hook(mod, args, output):
|
|
x = args[0].reshape(*mask.shape, -1)
|
|
features['x'] = (x * eta[:, :, None]).sum(1)
|
|
return output + (self.args.node_epsilon * eta[:, :, None] * p).reshape_as(output)
|
|
handle = self.linear_map[n].register_forward_hook(hook)
|
|
try:
|
|
pert_loss, pert_logits = self.call(inputs)
|
|
finally:
|
|
handle.remove()
|
|
if self.args.task_name.lower() == 'sst2':
|
|
d = residual * (pert_logits[:, 1] - pert_logits[:, 0] - margin) / self.args.node_epsilon
|
|
else:
|
|
d = (pert_loss - clean) / self.args.node_epsilon
|
|
est.append((features['x'] * d[:, None]).mean(0))
|
|
sketch = torch.stack(est).mean(0)
|
|
sn = float(sketch.norm())
|
|
if sn <= 1e-20:
|
|
metrics[n] = {'skipped': 'zero sketch'}
|
|
continue
|
|
d = sketch[:, None] / sn
|
|
old = self.basis[n]
|
|
if float((d.T @ old).sum()) < 0:
|
|
d = -d
|
|
new[n] = d
|
|
metrics[n] = dict(history_norm=norm, sketch_norm=sn, overlap=float((d.T @ old).square().sum()))
|
|
return (new, metrics)
|
|
|
|
def descent_probe(self, inputs, candidates, seed, lr):
|
|
"""Predict the actual one-sided SGD step from three same-batch loss values.
|
|
|
|
Exact for a quadratic objective; no virtual update or diagnostic gradient.
|
|
All candidates share the clean forward and coefficient-space Gaussian z.
|
|
"""
|
|
mu = self.args.zo_eps
|
|
clean = self.call(inputs)[0].detach().clone()
|
|
trials = []
|
|
for bases in candidates:
|
|
plus = self.shifted(inputs, bases, seed, mu)
|
|
minus = self.shifted(inputs, bases, seed, -mu)
|
|
slope = float((plus.double() - minus.double()).mean()) / (2 * mu)
|
|
curvature = float((plus.double() - 2 * clean.double() + minus.double()).mean()) / mu ** 2
|
|
response = float((plus - clean).double().mean()) / mu
|
|
first_order = lr * slope * response
|
|
second_order = 0.5 * lr ** 2 * response ** 2 * curvature
|
|
predicted = first_order - second_order
|
|
if not all((math.isfinite(v) for v in (slope, curvature, response, predicted))):
|
|
raise FloatingPointError('Nonfinite node descent prediction')
|
|
trials.append(dict(clean_loss=float(clean.double().mean()), plus_loss=float(plus.double().mean()), minus_loss=float(minus.double().mean()), slope=slope, curvature=curvature, response=response, first_order=first_order, second_order=second_order, predicted_descent=predicted))
|
|
return trials
|
|
|
|
def used(self):return self.counts['training']+self.counts['calibration']
|
|
|
|
def learning_rate_at(self,q):
|
|
a=self.args
|
|
if a.zo_schedule=='constant':return a.learning_rate
|
|
f=min(1,max(0,(q-a.decay_start)/max(1,a.main_forward_budget-a.decay_start)))
|
|
return a.lr_min+(a.learning_rate-a.lr_min)*.5*(1+math.cos(math.pi*f))
|
|
|
|
def progress(self,stage):
|
|
out=Path(self.args.output_dir);point=self.curve[-1] if self.curve else None
|
|
best=min(self.curve,key=lambda p:p['development']['loss']) if self.curve else None
|
|
value=dict(stage=stage,completed=self.used(),total=self.args.main_forward_budget,current_unit=self.args.trainer,pid=os.getpid(),output_directory=str(out),
|
|
elapsed_seconds=time.monotonic()-self.started,last_update=datetime.now(timezone.utc).isoformat(),step=self.state.global_step,latest_training_batch=self.latest,evaluation=point,query_counts=self.counts.copy(),
|
|
best_development=None if best is None else {'loss':best['development']['loss'],'main_forwards':best['main_forwards']},current_lr=self.current_lr,memory=memory(),data_protocol=self.args.data_protocol)
|
|
save(out/'progress.json',value)
|
|
text=f"# {self.args.trainer}: {stage}\n\nMain forwards: {self.used()}/{self.args.main_forward_budget}; updates: {self.state.global_step}; PID: {os.getpid()}\n\nLatest batch: {self.latest}\n\nLast evaluation (actual query count): {point}\n\nBest development: {value['best_development']}\n\nLR: {self.current_lr}; elapsed: {value['elapsed_seconds']:.1f}s\n\nUpdated UTC: {value['last_update']}\n"
|
|
tmp=out/'progress.md.tmp';tmp.write_text(text);tmp.replace(out/'progress.md')
|
|
print(value,flush=True)
|
|
|
|
def collate(self,indices,dataset=None):
|
|
dataset=self.train_dataset if dataset is None else dataset
|
|
return self._prepare_inputs(self.data_collator([dataset[int(i)] for i in indices]))
|
|
|
|
@torch.no_grad()
|
|
def evaluate_dataset(self,dataset,indices=None):
|
|
indices=list(range(len(dataset))) if indices is None else list(indices)
|
|
total=weight_sum=correct=label_count=0
|
|
size=self.args.per_device_eval_batch_size
|
|
for start in range(0,len(indices),size):
|
|
chosen=indices[start:start+size];inputs=self.collate(chosen,dataset)
|
|
losses,logits=self.call(inputs,'evaluation')
|
|
weight=self.loss_backend.last_weight if self.args.data_protocol=='mezo' else len(chosen)
|
|
total+=float(losses.double().mean())*weight;weight_sum+=weight
|
|
if self.args.task_name=='SST2':
|
|
correct+=int((logits.argmax(1)==inputs['labels']).sum());label_count+=len(inputs['labels'])
|
|
result=dict(loss=total/weight_sum,examples=len(indices))
|
|
if label_count:result['accuracy']=correct/label_count
|
|
return result
|
|
|
|
def measure(self):
|
|
point=dict(step=self.state.global_step,main_forwards=self.used(),elapsed_seconds=time.monotonic()-self.started,
|
|
train_probe=self.evaluate_dataset(self.train_dataset,range(min(128,len(self.train_dataset)))),development=self.evaluate_dataset(self.eval_dataset))
|
|
if getattr(self.args, 'select_best_checkpoint', False) and self.state.global_step > 0:
|
|
if not hasattr(self, 'best_checkpoint') or point['development']['loss'] < self.best_checkpoint['development']['loss']:
|
|
self.save_model(str(Path(self.args.output_dir)/'best_model'))
|
|
self.best_checkpoint = dict(step=point['step'], main_forwards=point['main_forwards'],
|
|
development=point['development'], criterion='minimum development loss',
|
|
evaluation_forwards=self.counts['evaluation'])
|
|
save(Path(self.args.output_dir)/'best_checkpoint.json', self.best_checkpoint)
|
|
self.curve.append(point);out=Path(self.args.output_dir);save(out/'curve.json',self.curve);figures(out,self.curve);self.progress('evaluation')
|
|
|
|
@torch.no_grad()
|
|
def restore_best_model(self):
|
|
"""Stream saved tensors into the existing model, preserving tied weights."""
|
|
import json
|
|
from safetensors import safe_open
|
|
folder = Path(self.args.output_dir)/'best_model'
|
|
index = folder/'model.safetensors.index.json'
|
|
files = sorted(set(json.loads(index.read_text())['weight_map'].values())) if index.exists() else ['model.safetensors']
|
|
state = self.model.state_dict() # References, not a weight snapshot.
|
|
key = lambda t: (t.data_ptr(), t.storage_offset(), tuple(t.shape))
|
|
missing = {key(t) for t in state.values()}
|
|
for filename in files:
|
|
with safe_open(str(folder/filename), framework='pt', device='cpu') as handle:
|
|
for name in handle.keys():
|
|
state[name].copy_(handle.get_tensor(name))
|
|
missing.discard(key(state[name]))
|
|
if missing:
|
|
raise RuntimeError('Best checkpoint does not cover all model tensors')
|
|
|
|
@torch.no_grad()
|
|
def _inner_training_loop(self,batch_size=None,args=None,resume_from_checkpoint=None,trial=None,ignore_keys_for_eval=None):
|
|
args=args or self.args
|
|
if resume_from_checkpoint:raise ValueError('Resume is not implemented; use a fresh run or load a merged HF model for inference')
|
|
self._train_batch_size=batch_size or args.per_device_train_batch_size
|
|
out=Path(args.output_dir);self.progress('calibration')
|
|
try:
|
|
self.configure_basis(self.collate(range(min(args.calibration_samples,len(self.train_dataset)))))
|
|
local_curvature = args.trainer=='node' and getattr(args,'node_update','original')=='local_curvature'
|
|
history_free = args.trainer=='node' and getattr(args,'node_update','original')=='history_free'
|
|
if args.trainer=='node' and not (local_curvature or history_free):self.configure_history()
|
|
save(out/'parameter_inventory.json',dict(unique_tensors=len(self.parameters),unique_parameters=sum(p.numel() for p in self.parameters),
|
|
structured_weights=len(self.basis),node_targets=list(self.basis) if history_free else list(self.history),coverage='direct_weights_inplace_v2: Linear low-rank SGD on W; dense embedding/norm/bias SGD; tied head once'))
|
|
if args.preflight_only:
|
|
inputs=self.collate(range(min(2,len(self.train_dataset))));before=self.call(inputs,'diagnostic')[0].clone()
|
|
self.shifted(inputs,self.basis,71,args.zo_eps)
|
|
torch.testing.assert_close(before,self.call(inputs,'diagnostic')[0],rtol=1e-5,atol=1e-6)
|
|
self.basis.update({n:-d for n,d in self.basis.items()})
|
|
torch.testing.assert_close(before,self.call(inputs,'diagnostic')[0],rtol=1e-5,atol=1e-6)
|
|
save(out/'preflight.json',dict(passed=True,counts=self.counts));self.progress('complete')
|
|
return TrainOutput(0,0.,{'main_forwards':self.used()})
|
|
dataloader=self.get_train_dataloader();iterator=iter(dataloader)
|
|
rng_probe=np.random.default_rng(seed_for(args.seed,12))
|
|
def probe_batch():
|
|
ids=rng_probe.choice(len(self.train_dataset),min(args.per_device_train_batch_size,len(self.train_dataset)),replace=False)
|
|
return self.collate(ids)
|
|
self.probe_batch = probe_batch
|
|
# Independent selection draws; preserve the author's HF training sampler.
|
|
rng_selection = np.random.default_rng(seed_for(args.seed,1710))
|
|
def selection_batches():
|
|
return [self.collate(rng_selection.choice(len(self.train_dataset),
|
|
args.per_device_train_batch_size,replace=False)) for _ in range(3)]
|
|
self.measure();next_eval=args.eval_main_forwards;sum_loss=0.
|
|
while self.used()+2<=args.main_forward_budget and (args.max_steps<=0 or self.state.global_step<args.max_steps):
|
|
step=self.state.global_step;self.current_lr=self.learning_rate_at(self.used())
|
|
try:inputs=next(iterator)
|
|
except StopIteration:iterator=iter(dataloader);inputs=next(iterator)
|
|
step+=1;inputs=self._prepare_inputs(inputs)
|
|
np.random.seed(seed_for(args.seed,33,step)%2**32);torch.manual_seed(seed_for(args.seed,22,step))
|
|
update_seed = seed_for(args.seed,33,step)
|
|
if args.trainer == 'fix':
|
|
self.latest, event = self.fix_step(inputs, update_seed)
|
|
elif args.trainer == 'adjust':
|
|
self.latest, event = self.adjust_step(inputs, update_seed)
|
|
elif history_free:
|
|
self.latest, event = self.coverage_step(inputs, update_seed)
|
|
elif local_curvature:
|
|
self.latest, event = self.curvature_step(inputs, update_seed,
|
|
selection_batches=selection_batches, basis_lr=args.basis_lr,
|
|
basis_radius=args.basis_radius)
|
|
else:
|
|
self.latest, event = self.node_step(inputs, update_seed)
|
|
if event is not None:
|
|
append(out/'refresh.jsonl', event)
|
|
self.state.global_step=step;sum_loss+=self.latest['batch_loss'];append(out/'records.jsonl',dict(step=step,main_forwards=self.used(),**self.latest))
|
|
if step%10==0:self.progress('training')
|
|
if self.used()>=next_eval:self.measure();next_eval=(self.used()//args.eval_main_forwards+1)*args.eval_main_forwards
|
|
if self.curve[-1]['main_forwards']!=self.used():self.measure()
|
|
save(out/'query_ledger.json',dict(main_forwards=self.used(),counts=self.counts,all_detection_charged=True,evaluations_separate=True))
|
|
if getattr(args, 'select_best_checkpoint', False):self.restore_best_model()
|
|
save(out/'summary.json',dict(status='complete',steps=self.state.global_step,main_forwards=self.used(),counts=self.counts,memory=memory(),elapsed_seconds=time.monotonic()-self.started,data_protocol=args.data_protocol,
|
|
evaluated_weights='development_best' if getattr(args,'select_best_checkpoint',False) else 'final_iterate',
|
|
best_checkpoint=getattr(self,'best_checkpoint',None)))
|
|
if args.save_final_checkpoint:self.save_model(str(out/'model'))
|
|
self.progress('complete')
|
|
return TrainOutput(self.state.global_step,sum_loss/max(1,self.state.global_step),{'main_forwards':self.used()})
|
|
except BaseException:
|
|
import traceback
|
|
save(out/'failure.json',{'traceback':traceback.format_exc()});self.progress('failed');raise
|
|
|
|
@torch.no_grad()
|
|
def save_model(self, output_dir=None, _internal_call=False):
|
|
"""W already contains all learned updates; export an ordinary HF model."""
|
|
out = Path(output_dir or self.args.output_dir)
|
|
out.mkdir(parents=True, exist_ok=True)
|
|
self.model.save_pretrained(out)
|
|
self.processing_class.save_pretrained(out)
|
|
save(out/'weights_export.json', dict(format='Standard HF weights',
|
|
parameterization='direct_weights_inplace_v2', resume_supported=False,
|
|
source_protocol=self.args.data_protocol))
|