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

+551
View File
@@ -0,0 +1,551 @@
# Curvature-aware descent: derivation and implementation contract
Current engineering execution: section 8 records the user's authorization to use
explicit local-curvature approximations and proceed with real-model experiments.
Certified reference status: a conditional forward-query algorithm is derived in section 6 and implemented
as OurTrainer.curvature_refresh / curvature_step, without enabling the real-model CLI. Its effective
upper-bound certificate is not established for the real model. No production implementation
or hyperparameter search may substitute unverified quantities for this contract.
The earlier `descent_gradient_proxy_v1` is withdrawn and is not a test of this theory.
## 0. 对用户补充全文的核对(2026-11-12)
原文假设 1.1 将 H 定义为分析用的有效二次上界,没有要求每个 ZO 算法
显式构建 H。不能把“未计算出完整 H”作为所有实模实验的统一禁止条件。
只有当算法声称实际优化给定各向异性 H 下的式 (2.3) 时,才需要给出该目标
及其梯度所需量的获取方式。分析假设与算法实际调用的量必须分别列明。
全文给出了比较框架,而没有给出最大化 (2.3) 的低查询选基算法。
以下两种目标不可混称为同一算法:
- 采用 H=L I、固定参数子空间秩 k:式 (2.9) 的系数为正时,最大化
D(P) 严格等价于最大化 s(P)。这是文档已证明的各向同性特例,不是
各向异性曲率目标的代理。若采用,必须明确声明该特例、学习率条件与 k。
- 保留各向异性 (2.3):必须推导完整的选基估计器,不能用局部三点曲率
自动代替上界 H,也不能只实现 G'Gd 而宣称已优化全部曲率项。
单边误差已有原文接口,不必把理想公式硬说成精确有限差分公式。下面补出
可直接代入 (1.9)-(1.10) 的一组充分条件,常数较松但每一步均可验证。
### 0.1 固定当前子空间下的单边与 batch 误差界
条件于选基历史及 U,要求当前训练 batch xi 与选基样本独立,方向独立于
两者;U'U=I_k,z_i 独立同分布于 N(0,I_k)。以下期望、无偏条件
E[g_xi]=g 及 Cov(g_xi)=Sigma 均条件于当前
历史、theta 和 U;且各样本目标在所有查询线段上有
统一梯度 Lipschitz 常数 L_f。对于无界高斯,该条件不能仅限于一个未控制
逃逸概率的有限邻域。设 F 满足原文 H 的上界条件,H 在上述条件下固定且
历史可测。
记 k=rank(P)、s=g'Pg、L_U=||U'HU||op、tau=tr(PH),并定义
B_mu = L_f^2 * mu^2/4 * k(k+2)(k+4)
C0 = (1+1/n)*L_U + tau/n
N_xi = (1+1/n)*tr(P H P Sigma) + tau/n * tr(P Sigma).
同一个 batch 用于本次 n 个方向;各方向使用同一 batch 的 clean/plus 差分。
把估计器写成 ghat=ghat_batch_ideal+r_mu。Taylor 余项满足
|e_i| <= L_f*mu/2 * ||z_i||^2
E||r_mu||^2 <= B_mu.
第二式用平均向量的 Jensen 不等式与高斯六阶径向矩成立,并没有假设
e_i 条件零均值,也没有错误地将其均值按 1/n 消去。
先对 batch 和方向精确取矩,再用 Cauchy-Schwarz/Young:
A >= s - sqrt(s B_mu) >= s/2 - B_mu/2
C_batch_ideal <= C0*s + N_xi
C <= 2*C0*s + 2*N_xi + 2*L_U*B_mu.
故在相应常数沿轨迹有统一上界时,主定理接口可取
c = 1/2, C_master = 2*C0,
delta = B_mu/2, nu = 2*N_xi + 2*L_U*B_mu.
这是充分上界,不是对 OPT 的常数估计或学习率建议,也不声称该界紧。
浮点查询误差、额外函数噪声若存在,还要进入 r_mu 并控制相应矩。
非二次例子 F(x)=sin(x)、theta=0、P=1 满足全局 L_f=1,且 H=1 是
有效上界。单边估计的均值为 exp(-mu^2/2),不同于真实梯度 1,故不能
把一般 r_mu 的均值或与理想估计的交叉项设为零。测试用高阶高斯求积
核对该解析均值及上述误差界;它不依赖二次函数的奇偶抵消。
### 0.2 选择与训练 batch 的独立性
原文 (2.16)-(2.19) 已明确:同一当前 batch 上先选 P 再训练,会产生 h_t。
独立的方向 seed 只能消除选基与训练方向的复用,不能消除 batch 耦合。
因此,若要使用 0.1 的独立性结论,刷新需要独立的选基样本,不能复用训练
batch 的 f0 来节省一次 forward。若仍复用,必须控制 h_t 以及相应的 C_t。
此前宣称“额外 4 次前向”并不能同时作为独立 batch 方案的预算。
HF RandomSampler 的 epoch 内无放回采样也不能直接认作条件独立的 iid
随机梯度 oracle。保持作者数据流时,要将随机重排分析作为额外理论任务,
或仅报告实验协议,不宣称上述条件收敛保证已经在实模上核验。
### 0.3 实验推进的准确门槛
继续保留单边 SGD。第 6 节保留各向异性目标,给出一种有证明的 H 构造和
对应估计器;其全局光滑常数证书仍须针对实模建立。各向同性特例仍是另一
明确目标,不能悄然替换。不能以未知 H 为由否定所有 ZO 实验。
现有训练入口的 fix/adjust/历史 node 不因此自动成为命题 (2.3) 的优化器。
只有在新选基步骤明确并通过对应测试后,才继续既定的调度和刷新参数实验。
## 1. Given-subspace objective (Proposition 2.1)
At a fixed parameter point, let g be the objective gradient, H the symmetric effective
quadratic upper-bound matrix, P an orthogonal projector, and n the number of independent
Gaussian directions averaged in one weight update. n is not the batch size or refresh interval.
Set s = g'Pg, t = tr(PH), alpha = eta(1+1/n)/2, beta = eta/(2n).
D(P) = s - alpha g'PHPg - beta s t
M(P) = gg' - alpha(HPgg' + gg'PH) - beta(t gg' + s H)
M is the Euclidean projection gradient. P is constrained; M=0 is not the condition.
For P=UU', the tangent gradient is 2(I-P) M U. g and H stay fixed during selection.
This objective does not require third derivatives merely to differentiate P.
## 2. Actual Linear parameterization
For W with m output rows and k input columns, use row-major vectorization:
P(d) = I_m kron (d d'), ||d||=1, rank(P)=m, s=||Gd||^2.
This is not a rank-one parameter-space projector. Within a full-model block projector,
all other parameter blocks stay present. Contract the relevant diagonal output blocks
of M into C = sum_a M[a,:,a,:]. Then
grad_d D = 2 C d
tangent_grad_d D = grad_d D - d (d' grad_d D)
d_next = normalize(d + rho tangent_grad_d D).
Keep gradient magnitudes. No sign replacement, fixed-angle substitution, clipping,
or sampling normalization without a derivation and an explicitly agreed algorithm.
Updating d must not change W. Fresh training noise is independent of selection noise.
## 3. Single-sided finite differences are an additional theory obligation
Proposition 2.1 assumes ideal linear directional observations. Production training uses
`(F(theta+mu*u)-F(theta))/mu`. These are not identical at nonzero mu.
On an exact quadratic whose Hessian equals H, write a=g'u and c=u'Hu. The observed
response is a+mu*c/2. Gaussian symmetry gives an exact corrected objective:
D_mu(P) = D(P) - eta*mu^2/(8*n) T3(P)
T3 = t^3 + 6*t*tr((PH)^2) + 8*tr((PH)^3)
grad_P T3 = (3*t^2 + 6*tr((PH)^2))*H
+ 12*t*HPH + 24*HPHPH.
If H is merely an upper bound and K is the actual quadratic Hessian, the additional
moment is E[(u'Ku)^2 (u'Hu)], not E[(u'Hu)^3]. Do not silently identify H with K.
For nonquadratic losses, derive/control the remaining finite-difference bias and moments.
Specifically, let ghat_0 denote the averaged ideal estimator and r the averaged
observation-error contribution, so ghat_mu=ghat_0+r. The same upper-bound argument gives
D_bound(P) = D(P) + g' E[r] - eta E[ghat_0' H r]
- eta/2 E[r' H r]
E[F(theta_next)] <= F(theta) - eta D_bound(P).
Replacing D(P) in the original guaranteed inequality by the displayed
expression is valid under the same upper-bound assumption; equality of this expression
with actual descent is not claimed. These extra terms cannot simply be omitted or
declared zero for a general neural-network loss.
Counterexample to ignoring this issue: F(theta)=theta^2/2, theta=0, n=1.
Ideal D=0, but single-sided Gaussian SGD has
E[F(theta_next)] = 15*eta^2*mu^2/8 > 0.
## 4. Real-model requirements for optimizing anisotropic (2.3)
Section 6 resolves the formal estimator under stated oracle assumptions; it does not
establish those assumptions or a useful upper-bound certificate for OPT/SST2.
Before exposing a new training mode, specify all of the following:
1. Which objective g refers to (population/full training objective versus one batch).
A batch-dependent squared gradient includes covariance terms and cannot silently
replace a squared mean gradient.
2. For this anisotropic selection objective, how the chosen effective upper-bound H,
its required actions, and trace information are obtained within budget. H is not
automatically a runtime requirement of every algorithm covered by the framework.
A three-point directional curvature is
a local Hessian measurement; it is not a verified upper bound over actual updates.
3. A derived estimator for the complete structured basis gradient, with its sampling
covariance, normalization, finite-mu error, finite-delta error if used, and batch noise.
4. Actual forwards for each quantity, including any cross-moments and selection queries.
The old claim of four extra forwards is not a budget proof for this implementation.
No full model snapshots, full-model stored noise, diagnostic backprop in training, or
unbudgeted oracle calls. Dense reference matrices are permitted only in small numerical tests.
## 5. Acceptance tests and execution order
Numerical reference tests (CPU float64; no model training/evaluation queries):
- Evaluate Proposition 2.1 and independently differentiate with autograd in tests.
- Check structured basis gradient against directional finite differences, including
cross-output and fixed auxiliary blocks in the full P.
- Check the ideal Gaussian descent moments and the finite-mu correction using exact
Gauss-Hermite integration on small quadratic objectives.
- Check shared-batch covariance terms and the sufficient finite-difference bounds;
include a smooth nonquadratic example with analytically nonzero estimator bias.
- Verify the selection–batch coupling identity and the declared isotropic special case.
- Integrate the three-batch forward score against the complete anisotropic objective;
verify its 13-query selection cost, joint basis gradient limit, and nonquadratic bias.
- Verify the upper-bound inequality with a known PSD slack H-K, where applicable.
- Check basis retraction preserves unit norm, moves uphill locally for a small step,
and preserves the gradient's magnitude scaling.
For a new mode claiming to optimize anisotropic (2.3), resolve section 4 first;
implement the complete agreed estimator in trainer.py; compare it to the reference
under controlled known models; verify budget, restoration, tied weights, and independent
RNG; perform a real-model short check. An explicitly chosen isotropic special case or
another algorithm must be validated against its own stated objective and assumptions.
After the chosen algorithm passes these checks, perform the authorized experiment
sequence: same-LR constant controls,
cosine starts at main query 3600/4200, matched fix control, refresh interval/basis-step
study, and finally separately derived weight decay. Keep 6000-query budgets and choose
hyperparameters with development data only. Do not mix historical protocols.
The numerical reference does not establish section 4 for OPT/SST2 and must not be
presented as a production algorithm or a validation of real-model convergence.
Verified on 2026-11-12: independent autograd, exact Gaussian quadrature, structured
directional finite differences, known-upper-bound inequality, and the single-sided
finite-radius counterexample pass. Test code is `tests/test_curvature_theory.py`;
the small-matrix reference is in `trainer.py`. Autograd is used only in these tests.
## 6. 完整条件算法:各向异性上界目标的前向选基梯度
本节对应当前每步一个 Gaussian 方向,即 n=1。固定刷新时刻的 theta、eta,
令所有候选基共同使用同一个 H。目标仍为命题 (2.3),没有改成单 batch
梯度平方、实际虚拟更新收益或局部 Hessian 目标。训练继续使用单边差分。
### 6.1 先把完整目标写成可估计的标量期望
令 u=U(d)z,z~N(0,I_k),a=g'u,h=u'Hu。高斯矩给出
E[a^2] = s(P)
E[a^2 h] = 2*g'PHPg + s(P)*tr(PH).
因此,在 n=1 时精确有
D(P) = E_z[a^2*(1-eta*h/2)]. (6.1)
这同时保留方向曲率和曲率迹项,不需要分别存储 g、H 或 P。
Linear 的 u_l=z_l d_l',z_l~N(0,I_out);dense 辅助参数保留完整高斯方向。
两侧候选基必须使用同一个潜变量 z,包括所有固定基和 dense 辅助块。
不能再将 u 归一化,否则 (6.1) 的高斯矩发生变化。
### 6.2 一种合法的可查询 H 构造
原文没有指定唯一 H。本节额外明确以下充分假设:F 二阶可微,且已知
经过证明的全局常数 L>0,满足 ||Hess F(x)||op<=L;F 的函数值可由无偏
独立训练 batch 查询。L 是上界证书,不是从几个观测拟合后随意调节的超参数。
定义 K=Hess F(theta),并选择
H = K + 2*L*I. (6.2)
由于 -L I <= K <= L I,对任意 x 都有
Hess F(x) <= L I <= H, L I <= H <= 3 L I.
沿更新线段积分即得原文 (1.5),所以 H 为有效 PSD 全局上界,也适用于
无界 Gaussian 更新。它保留 K 的各向异性,但通常保守;不宣称是最紧上界。
这是本节新给出的充分构造,不是原文已提供的实模曲率结论。
只需估计 u'Ku,再加 2L||u||^2。若已有更紧且能合法查询 u'Hu 的 H,
可直接使用 (6.1),无需上述构造。仅函数查询不能识别任意选定的上界:
例如 F(x)=||x||^2/2 同时容许 H=I 和 H=diag(1,4),但两者给出不同 D。
有限局部查询也不能验证未知函数在未查询区域的全局 L。
### 6.3 用独立 batch 的乘积估计总体目标
从训练分布独立抽取 A、B、C,三个 batch 的损失均满足 E[f_X(x)]=F(x)。
独立抽样允许碰巧重叠;强制互斥抽样不自动等于独立。对固定 u 定义
a_A(u) = [f_A(theta+mu*u)-f_A(theta-mu*u)]/(2*mu)
a_B(u) = [f_B(theta+mu*u)-f_B(theta-mu*u)]/(2*mu)
c_C(u) = [f_C(theta+mu*u)-2*f_C(theta)+f_C(theta-mu*u)]/mu^2
Y_mu(u) = a_A(u)*a_B(u)*[1-eta/2*(c_C(u)+2*L*||u||^2)]. (6.3)
A、B 的独立性使方向响应的乘积估计总体响应平方,而不是其二阶矩。
C 与 A、B 独立,使曲率乘积不再包含额外的 batch 协方差。不能把它们换成
同 batch 的 a^2*c 而仍声称估计原式。两侧基允许共享同一组 A、B、C,
以减少差分方差;A、B、C 在组内仍独立。额外模型随机性必须纳入 oracle,
各组保持独立,组内各扰动查询配对固定随机性。
设总体中心差分均值为 a+b_mu、总体三点曲率为 u'Ku+e_mu,则条件于 u:
E_ABC[Y_mu(u)] = (a+b_mu)^2 * [1-eta/2*(h+e_mu)]. (6.4)
理想导数极限下 b_mu=e_mu=0,因此 E_zABC Y_0=D(P)。在精确二次目标上,
中心响应和曲率差分对任意非零 mu 都精确(精确算术下),故该恒等式直接成立。
中心差分只用于选基目标的估计,不改变权重训练的单边更新。
### 6.4 有限 mu 的误差与所需矩条件
额外假设沿查询线段存在统一三、四阶导数界 M3、M4,或足够的高斯可积包络。
仅 C4 和 L-smooth 并不自动提供有限全局 M3、M4。Taylor 展开给出
|b_mu| <= B(u) = M3*mu^2*||u||^3/6
|e_mu| <= E(u) = M4*mu^2*||u||^4/12.
由 (6.4),相对理想标量 a^2*(1-eta*h/2) 的误差至多
|1-eta*h/2|*(2*|a|*B+B^2) + eta/2*E*(|a|+B)^2. (6.5)
对 z 积分得到 |D_mu(P)-D(P)|<=epsilon_mu,固定维度和上述常数时为 O(mu^2)。
有限半径估计有显式可控偏差,不称作原 D 的有限半径无偏估计。
还需 batch 方向响应及曲率的足够矩,令 Y_mu 和后续梯度估计二阶矩有限。
总体 F 光滑并不自动保证随机 oracle 的方差有限。
不对可能为负的随机曲率取绝对值、截断或裁剪,否则会改变期望目标。
### 6.5 联合切空间梯度估计
对所有拟更新的输入基 d_l 独立采 eps_l~N(0,I_in),投影到切空间:
v_l = (I-d_l d_l') eps_l
d_l,+ = normalize(d_l+delta*v_l)
d_l,- = normalize(d_l-delta*v_l).
不再归一化 v_l。用同一个内层 z 分别生成 u_+、u_-,并用同一组独立
A、B、C 计算 (6.3)。定义
q = [Y_mu(u_+)-Y_mu(u_-)]/(2*delta)
b_hat_l = q*v_l
d_l,new = normalize(d_l+rho*b_hat_l). (6.6)
保留 q 的大小与符号。rho 为基的学习率,delta 为基查询半径,mu 为权重
查询半径;三者作用不同。换基不修改 W。可联合更新全部 Linear 基;若只
选择部分层,须声明优化的是其余基固定后的限制问题,不能冒充全基优化。
证明其对应梯度:在当前 d 的联合切空间取正交坐标 x,维度
p=sum_l(in_l-1),令 R_d(x) 为逐层归一化,f_mu(x)=D_mu(P(R_d(x)))。
在交换微分和期望合法时,Gaussian 分部积分与对称性给出
E[b_hat] = grad_x E_v[f_mu(x+delta*v)] at x=0. (6.7)
所以有限 delta 时,它对固定切空间坐标下的 Gaussian 平滑目标梯度无偏。
不是对原始 D 的球面梯度无偏。若理想 pullback 的三阶导数范数上界为 T3,
则平滑偏差至多 T3*delta^2*p/2;若 (6.5) 对候选基一致成立,保守的总偏差为
||E[b_hat]-grad_tangent D||
<= T3*delta^2*p/2 + epsilon_mu*sqrt(p)/delta. (6.8)
因此取 delta->0 且 mu^2/delta->0 可消除该偏差;没有额外 C1 误差证明时,
不能直接写 O(mu^2+delta^2)。浮点损失误差还会被 1/mu、1/mu^2、1/delta
放大,必须实测,不能被这段精确算术推导覆盖。
即使没有内层噪声,线性极限的单次 Gaussian 梯度估计也满足
E||b_hat||^2=(p+2)||b||^2。联合多层并不增加前向次数,但可能显著增加方差。
本流程每次只有一个联合方向,不擅自增加重复试探、筛选或确认步骤。
### 6.6 为什么这是改进方向,保证到什么程度
记真实切向梯度为 b,估计偏差上界为 e,E||b_hat||^2<=V,且当前
retraction pullback 在更新范围满足梯度 Lipschitz 常数 L_D。则一次选基满足
E[D(P_new)-D(P)]
>= rho*||b||^2-rho*||b||*e-rho^2*L_D*V/2
>= rho/2*||b||^2-rho/2*e^2-rho^2*L_D*V/2. (6.9)
因此在偏差和方差代价足够小时,小步可提高期望理论下降量;单次随机基
更新不保证一定提高 D,也不保证实际训练 loss 必降或得到全局最优基。
原文理想权重更新的下降保证仍为 -eta*D(P_new)。实际单边 batch SGD
还包含第 0.1 节的误差与噪声,选基原 D 不等于自动优化这些附加项。
已知 H<=3LI 时,理想条件可用 C<=3L(k+2);第 0.1 节那组保守有限差分
常数允许 eta<=1/[12L(k+2)]。这些是充分界,不是 OPT 的学习率建议。
### 6.7 完整算法与查询预算
输入:初始化基、eta、rho、mu、delta、刷新间隔 r、主查询预算,以及已验证
的 L/上界 oracle 条件。所有选择 batch 来自训练分布,不使用 dev/val。
初始化各 Linear 的单位输入基;构基前向计入主预算。
for t = 0, 1, ...:
若达到刷新点且剩余预算容纳 13+2 次前向:
固定当前 theta、eta、所有原基。
独立抽 A、B、C;采各层切向 v 和一个全模型潜变量 z。
构造基 d_+、d_-;按相同 z 生成 u_+、u_-。
查询 (6.3),得到 Y_+、Y_-;所有扰动均逆向恢复到 theta。
q = (Y_+-Y_-)/(2*delta)。
每层 d <- normalize(d+rho*q*v),权重不变。
独立抽训练 batch 和新的 Gaussian 潜变量 z_train。
u_train = U(d)*z_train。
s_train = [f_train(theta+mu*u_train)-f_train(theta)]/mu。
theta <- theta-eta*s_train*u_train。
记录训练/选基主查询;评估查询单独记录。
正常权重更新为 2 次。刷新时 A、B 各查询两基的 +/- 扰动,共 8 次;
C 查询两基的 +/- 扰动共 4 次,共享一次 f_C(theta),合计选基 13 次,
刷新步连同正常训练合计 15 次。R 次刷新、T 次权重更新且初始化 1 次时,
主预算为 Q=1+2T+13R。若已给出不需要 F 查询的精确 u'Hu oracle,选基
降为 8 次 F 查询加 2 次上界 oracle 调用;不能把后者的真实成本隐去。
确定性 F 没有 batch 乘积偏差时,两侧各三点共享 f0,只需 5 次选择查询,
但若 F 需遍历全训练集,每次 F 的全部 batch 前向都必须计数。
所有权重扰动使用相同 seed 按参数再生噪声并原地逆向恢复。不保存全模型
副本、全模型噪声或反向图。只保存小基及其切向量、标量、种子。FP32 恢复
允许舍入误差,不能声称逐位恢复。联合探测覆盖的方向及 ||u||^2 可流式计算。
当前保留 HF RandomSampler 的原训练协议;它不是本节条件 iid oracle 的
自动实现。未来落地必须显式声明采样协议,不能暗改作者数据流以声称定理成立。
本节给出了理论上闭合的条件流程;真实模型的 L/上界证书、可接受的方差和
有限精度误差尚未建立,因此没有启动这套流程的实模调参。
实现对应:`curvature_refresh` 实现 (6.3)-(6.6),流式计算 Gaussian 方向范数,
只保存基、切向量与标量;`curvature_step` 实现刷新间隔、15 次预算预留、
独立选择 seed 和普通单边权重更新。三个独立 batch 由调用方提供,函数无法
仅凭张量值检查统计独立性。`certified_smoothness` 只检查数值合法性,不虚构证明。
实际训练循环保持原协议,尚未分派到这个条件 API。
`tests/test_curvature_steps.py` 用具有解析全局上界的二次模型验证真实函数实现,
覆盖分数、基更新、权重更新、预算、异常恢复、RNG 隔离及无完整权重克隆;
这些是数值验收而非 LLM 性能代理实验。
本轮数值验证:全套 68 项测试通过;新增三 batch 纯函数值查询与完整 D
的高斯矩核对、13 次选择查询计数、包含跨层曲率与 dense 辅助块的联合
双基梯度极限、非二次 sin 目标的误差界及 O(mu^2) 收缩检验。主模型查询
与评估模型查询均为 0。证明和测试不能替代真实模型上界证书。
## 7. 去掉全局 L 前提:可以推到哪里,哪些量仍不可省略
L 是第 6 节为实现 H 而引入的充分条件,不是用户需要提供的原始输入,也不是
所有 ZO 实验的必要条件。原文需要有效 H;具体算法是否需要查询它取决于实际
更新公式。MeZO 的分析使用局部曲率假设,权重更新本身不调用完整曲率上界。
本项目新选基步骤直接优化 D_H,因而必须明确 H,不能把分析量的存在当作
对算法查询的实现。以下是新的推导,尚未替换第 6 节条件 API。
### 7.1 未指定的上界不能从目标中一般性消去
令 K 为真实二次 Hessian,H_lambda=K+lambda I,投影秩 k 固定。则
D_lambda(P) = [1-eta*lambda/2*(1+(k+1)/n)]*s(P)
-eta/2*[(1+1/n)*g'PKPg+s(P)/n*tr(PK)].
lambda 乘的是随 P 改变的 s(P),不是可删除的常数。例:
K=diag(100,1),g=(sqrt(1.1),1),n=k=1,eta=0.0005。
P0=e2 e2',P1=e1 e1'。H0=K 与 H500=K+500I 都是有效全局上界。
lambda=0: D(P0)=0.99925, D(P1)=1.0175
lambda=500: D(P0)=0.62425, D(P1)=0.605.
两种情形都满足所用投影上的保守 eta<=1/C 条件,但排序不同。即使函数值
全部已知,也不能确定未指定的 H。改变 eta 抵消该系数同时改变权重更新,
不能称为原学习率下同一目标。优化实际虚拟更新收益也一般不是优化 D_H。
### 7.2 当前 OPT 的结构性全局增长包络
检查本地 config 与安装的源码:OPT-1.3B 使用 ReLU,decoder 有最终 LayerNorm,
hidden_size=word_embed_proj_dim=2048,没有 project_out。不能把 C4 全局
光滑假设直接应用到 ReLU 参数空间。也不能仅因全局 Hessian 不有界就断言
当前点不存在相切二次上界;以下拼接恰好可以绕开该过强要求。
LayerNorm 的归一化部分满足 ||q||2<=sqrt(h)。设输出头行范数最大值为 A,
最终 LayerNorm 参数为 gamma,beta,T=sqrt(h)||gamma||inf+||beta||2,
c=sqrt(h)+1。对唯一参数空间中任意 ||Delta||2=r(绑定权重只计一次):
max_j ||W_j+Delta W_j||2 <= A+r
||LN_output||2 <= T+c*r
||logits||inf <= (A+r)*(T+c*r).
token CE <= log(V)+2||logits||inf。当前 SST2 作者 wrapper 对平均 token
log-prob 做二选项 CE;每个 option 分数在 [-log(V)-2||logits||inf,0],
因此 loss <= log(2)+log(V)+2||logits||inf。故其总体目标有
0 <= F(theta+Delta) <= a0+a1*r+a2*r^2
a0=log(2)+log(V)+2*A*T
a1=2*(A*c+T), a2=2*c. (7.1)
该界不要求内部注意力/MLP 权重有界,因为最终归一化控制了输出;不能应用
到去掉最终 LN、有额外可训练 project_out 或其他未核对的架构。
对当前检查点的只读分块扫描得到(浮点数是分析记录,不是向上舍入证书):
A≈3.55166360,||gamma||inf=1,||beta||2≈4.35554257,
a0≈363.91708848,a1≈427.78397403,a2≈92.50966799。
未执行训练/评估模型前向。这个包络不是相切上界,不能直接作为第 6 节 L。
### 7.3 局部证书与全局包络拼接
假设在当前 theta 能由模型结构验证 R>0、ell_R>=0、G>=||g||,满足
F(theta+Delta)<=F(theta)+g'Delta+ell_R/2*||Delta||^2
for ||Delta||<=R.
令
q=max(ell_R, 2*a2+2*(a1+G)/R+2*a0/R^2). (7.2)
内球由局部证书成立。外部 r>=R,由 (7.1)、F(theta)>=0 和
-g'Delta<=G*r 得到余项/r^2<=a2+(a1+G)/R+a0/R^2。
因此 H_iso=q I 是当前点对所有 Delta 有效的相切 PSD 上界。
若当前点 Hessian K 存在且已证 ||K||op<=kappa,则
H=K+(q+kappa)I >= q I (7.3)
是可用的各向异性上界。只需三点估 u'Ku 再加 (q+kappa)||u||^2,
无需全局光滑常数 L。它定义了一个明确的合法 D_H;不保证等于先前某个
未被指定/验证的 H 所对应的目标。实现时必须明确推广为“已认证 shift”,
不能把 (q+kappa)/2 传作虚构的全局 L。
剩余证书不是从几个三点值取最大:对有限训练样本,可尝试验证所有 ReLU
preactivation 在半径 R 内保持符号,再对 smooth DAG(attention、LN、CE)
传播一、二阶算子界。需包括所有 token 和样本、LN epsilon、绑定权重及损失
归一化。如果某点确在 kink,原文 g/K 或 C4 误差论证可能不成立,不能默认
存在正半径。当前未完成这套 24 层网络的局部证书;(7.2) 中的 R、ell_R、G、
kappa 不可用经验最大曲率代替。小 R 还可能令 1/R^2 项极大,证书即使成立
也未必有用。尚不能据此宣布实模可运行。
### 7.4 选基差分不必要求全空间 C4,但需要局部/尾部误差分析
若当前点有上述无 kink 局部球,则在 ||u||<=R/mu 上使用局部 M3/M4 余项。
外部用 (7.1) 控制函数值:记 A_mu=a0+a1*mu*||u||+a2*mu^2*||u||^2,
中心响应绝对值 <=A_mu/(2mu),三点曲率绝对值 <=2*A_mu/mu^2。
于是误差可分为局部多项式 O(mu^2) 项与 Gaussian 尾部上的多项式矩。
固定 R>0 时,该尾项随 mu->0 比任何 mu 幂更快消失;有限 mu 时必须显式
计入,不能声称所有 Gaussian 查询都位于局部球。该论证适用于当前有限
样本损失的统一包络/局部界,不自动替代 batch 独立性与有限精度验收。
### 7.5 实验与证明的结论
不需要用户给 L,也不必要求训练算法都计算全局上界。需要区分:
原文给定的 D_H 优化器需要可定义且可查询的 H;未知 H 不能保持原目标同时
被删除。全局 L 可被 (7.1)-(7.3) 的结构证书替代,但本项目的局部证书尚未
建立。当前已获得真实模型的增长包络,而不是完成了实模曲率认证。
因此仍不将已有条件代码的数值验收称为正式实模实验,也不以三点局部曲率
或实测最大值冒充原文上界。此前“实验都必须先知道全局 L”的表述撤回。
核对来源(只用于模型结构/现有方法事实,以上界与反例均为本项目推导):
- MeZO 原文 Assumption 1:https://openreview.net/pdf?id=CcsdvOOzMp
- LayerNorm 公式:https://docs.pytorch.org/docs/stable/generated/torch.nn.modules.normalization.LayerNorm.html
- OPT 官方源码:https://github.com/huggingface/transformers/blob/main/src/transformers/models/opt/modeling_opt.py
## 8. 当前工程实验约定(用户澄清,2026-11-12)
用户明确接受理论公式与工程实现有出入,以理论解释实测现象,允许开始实模实验。
据此启用独立命名的 local_curvature_gradient_v1,不再以全局上界证书为开跑条件。
第 6-7 节保留为严格保证的分析,不再将其中未满足的认证条件作为该工程变体的
启动门槛。历史 sign/固定角度结果仍不能评价当前幅值梯度方案。
当前工程目标明确为 n=1 下的局部二阶下降模型:
J_local(P)=s(P)-eta/2*[2*g'P K P g+s(P)*tr(P K)], K=Hess F(theta).
在理想方向观测下,它等于 E[(g'u)^2*(1-eta*u'Ku/2)];对精确二次目标
等于理想 ZO 的期望下降/eta。对非二次模型只作为局部 Taylor 模型解释,
不将 K 叫作 PSD 上界,也不把实训单边/batch 噪声省略后声称精确等式。
复用第 6 节的三个独立 batch 与联合切空间估计,不添加 2L||u||^2 项。
在ReLU场景仍采用有限查询响应,数值估计质量由真实刷新日志和开发集曲线检验。
实现入口为 `--trainer node --node_update local_curvature`。默认工程试验
rho=1e-5、delta=1e-3、mu=1e-3、r=128;rho/delta 是显式工程参数,
不是从小二次测试推断的 LLM 最优常数。保留差商的幅值,不归一化 Gaussian
切向量,不裁剪或取绝对值处理曲率,不加入新旧基 gate。
数据样本、模板、损失及 HF RandomSampler 保持 MeZO 协议。独立选择 batch
来自训练池自己的 RNG;不用 dev/val 选基。全部 144 个 Linear 输入基联合更新,
每次刷新 13 次主前向,正常训练 2 次。评估单独计数。
执行顺序:300 主查询试跑验证实际刷新;3000 查询比较 eta=[1,1.5,2,3]e-6
且固定其他参数与 constant schedule;仅按开发集末点 loss 选 eta;从原始检查点
重新训练 6000 查询并保存标准 HF 权重。若真实试跑暴露工程问题,先记录并修正,
不得静默改成 sign、固定角度或隐藏额外查询。旧理论未认证不等于该工程研究不可执行。
+152
View File
@@ -0,0 +1,152 @@
# 不依赖历史梯度的当前覆盖梯度估计
本方案的查询 API 为 `OurTrainer.coverage_gradient_probe`,完整更新为 `coverage_step`;显式入口 `--trainer node --node_update history_free`。原默认 node 仍使用回退后的历史构基。本文件的自动微分仅用于独立验证真值。2026-11-12 用户授权按短训选参、随后长训的顺序开展实模实验。
## 1. 固定什么,对什么求导
固定当前实际权重 θ 和当前 batch ξ 的标量损失 fξ。目标层 ℓ 的权重为 Wℓ∈R^(mℓ×pℓ),输入基 dℓ∈R^pℓ、||dℓ||=1,Gℓ=∇Wℓ fξ(θ)。定义
sℓ(dℓ)=||Gℓ dℓ||²,
Πℓ=I-dℓ dℓᵀ,
grad sℓ=2 Πℓ GℓᵀGℓ dℓ. (1)
对多个基的目标为这些覆盖量之和;其他固定基和 dense 部分的覆盖为常数。对 d 求导时 θ 固定,不对整个训练轨迹求导。输入侧 rank-1 基对应参数投影 I_m⊗ddᵀ,其参数子空间维度为 m。
旧方法先将历史系数梯度的 EMA 归一化成 p,再估计 Gᵀp。只有 p 对齐当前 Gd 时,才对应 GᵀG 的幂迭代。这里直接构造式 (1) 的估计,不使用历史梯度。
## 2. 两次普通训练查询提供什么
沿现有训练方向生成独立标准高斯系数 z_j:Linear 权重方向为 z_j d_jᵀ,dense 参数为原形状 Gaussian。把所有系数记为 Z,方向记为 u=UZ;在固定单位基和无重复参数条件下 U 是等距映射。记 a=Uᵀ∇fξ,其第 ℓ 块 aℓ=Gℓdℓ。
f0=fξ(θ),
fW=fξ(θ+μu),
rμ=(fW-f0)/μ. (2)
两次前向后恢复权重。理想线性响应为 r0=aᵀZ。于是 E[r0²]=||a||²,E[r0 zℓ]=Gℓdℓ;但横向的 Gℓᵀ 作用仍未观测。
例如 d=e1、G1=(1,0)、G2=(1,c),训练方向都给出 r0=z,而球面梯度分别为 0 和 (0,2c)。因此仅由这两个函数查询不能一般恢复式 (1)。
## 3. clean 前向中的输入压缩
把目标层所有实际执行位置(包含 batch 行和 token)展开:Xℓ∈R^(Nℓ×pℓ) 为输入,Aℓ∈R^(Nℓ×mℓ) 为标量损失对节点输出的导数,则
Gℓ=AℓᵀXℓ.
每层每个位置独立采样 Rademacher 符号 ηℓ,t∈{-1,+1},与 Z 独立。在式 (2) 的原始 clean 前向中计算并仅保存
vℓ=Xℓᵀηℓ=Σ_t ηℓ,t xℓ,t. (3)
这只保存每层 pℓ 维向量。不能在后面的联合节点扰动前向中重新计算式 (3):下游输入已受到上游扰动。
fξ 是当前训练协议的实际标量 loss。batch/token 的平均已经包含在 Aℓ 内,式 (3) 必须求和,不能再次平均。MeZO SST2 实际有 2N 条候选输入,直接沿用作者标量 loss,不使用旧 residual×margin 近似。所有实际节点位置均取符号;排除 padding 只有在被排除位置的损失导数确实为零时才保持完整 Gℓ。
## 4. 一次联合节点查询
权重恢复到 θ 后,同时在选中的各层输出注入
hℓ,t ← hℓ,t + ε ηℓ,t zℓ,
fN=fξ(带上述节点注入的计算图),
nε=(fN-f0)/ε. (4)
这里 zℓ 必须与式 (2) 的权重查询完全相同;各层 ηℓ 必须独立。η 可按层重放 seed,无需保存整个符号张量。理想节点响应为
n0=Σ_j η_jᵀ A_j z_j.
由 E[ηℓηℓᵀ]=I、不同层符号零相关,
Eη[n0 vℓ | Z]=XℓᵀAℓ zℓ=Gℓᵀzℓ. (5)
定义最终估计
ĝ_dℓ = 2 Πℓ rμ nε vℓ. (6)
理想线性响应下,先对 η 再对 Z 取期望:
E[ĝ_dℓ]=2Πℓ Gℓᵀ E[zℓ Zᵀ] a
=2Πℓ GℓᵀGℓdℓ=grad sℓ.
其他层和 dense 参数在权重响应中的贡献,因 Gaussian 块独立且零均值而消失,但仍增加方差。若节点使用独立 Gaussian z'ℓ,则希望得到的交叉矩消失,理想梯度均值变成零。
## 5. 单边查询的有限差分偏差
令节点注入函数为 φ(εV),V 的各块为 ηℓ zℓᵀ。vℓ 始终来自 clean,和 Z 无关。把所有 η 同时取反,则 V、vℓ 同时取反。因此精确成立
Eη[nε⁺vℓ | Z] = Eη[nεᶜvℓ | Z],
其中 c 表示中心差分。这个条件均值关于全局 Z→-Z 为奇函数,再利用 Gaussian 对称性得到
E[rμ⁺ nε⁺ vℓ] = E[rμᶜ nεᶜ vℓ]. (7)
这是均值恒等式,单个样本仍含单边误差,数值舍入也不会被精确消去。不需要为实现式 (6) 增加负扰动前向。
若权重切片和节点切片满足可积的三阶导数界 MW、MN,则中心差分余项满足
|er|≤MW μ²||u||³/6,
|en|≤MN ε²||V||³/6.
式 (6) 的均值偏差范数上界为
MW μ²/3 E[||u||³ |n0| ||Πℓvℓ||]
+ MN ε²/3 E[|r0| ||V||³ ||Πℓvℓ||]
+ MW MN μ²ε²/18 E[||u||³ ||V||³ ||Πℓvℓ||]. (8)
故偏差为 O(μ²+ε²+μ²ε²)。两个切片都恰为二次函数时,精确算术下均值偏差为零。实际网络的局部光滑区间、Gaussian 尾部、ReLU 拐点及浮点差分误差需要另行评估;小模型结果不建立实模全局光滑假设。
## 6. 联合节点查询省预算,但增加方差
若各层分别查询节点,只需把 n0 换成本层 nℓ=ηℓᵀAℓzℓ,均值仍相同。理想响应下两种估计的每层协方差之差为
Cov(ĝℓ_joint)-Cov(ĝℓ_separate)
=4 Πℓ XℓᵀXℓ Πℓ
×[||a||² Σ_(j≠ℓ)||Aj||F²
+2 Σ_(j≠ℓ)||Aj aj||²] ⪰ 0. (9)
证明:其他层的节点响应均值为零,与本层符号独立,故与本层估计的交叉矩为零;新增二阶矩为 4E[r0² Σ_(j≠ℓ)||Ajzj||²]ΠXᵀXΠ,再用 Gaussian 四阶矩即可。
多组 η 的平均只能降低节点条件方差,不能消除共用 Z 的方向方差。联合查询不必然在相同查询预算下更差或更好,需要比较相同成本下的误差。
## 7. batch 目标
同 batch 复用严格对应当前 batch 的覆盖。若 ξ 随机,其期望目标为
Eξ||Gℓ,ξ dℓ||²=||Gℓ dℓ||²+dℓᵀΓℓdℓ,
Γℓ=E[(Gℓ,ξ-Gℓ)ᵀ(Gℓ,ξ-Gℓ)]. (10)
因此它也偏好梯度噪声能量。若要求总体梯度覆盖,可将权重响应放在独立 batch A,节点响应和输入压缩放在独立 batch B;在两者对当前 θ 均为无偏独立 oracle 的条件下,理想均值恢复 2ΠGℓᵀGℓdℓ。一般相关 A/B 的目标为 E[dᵀG_BᵀG_A d],梯度需要两个交叉项;仅在 A/B 交换对称时,乘 2 的估计才与其梯度对应。HF RandomSampler 的训练历史不自动满足独立 oracle 假设。
## 8. 查询次数与复用时序
设刷新 K 层,每层/每组符号独立;下表包含正常训练查询,未包含初始化校准和评估。
| 流程 | 总前向 | 比普通训练增加 |
|---|---:|---:|
| 普通单边训练 | 2 | 0 |
| 复用响应,逐层一次节点查询 | 2+K | K |
| clean 提前记录压缩量,一次联合节点查询 | 3 | 1 |
| 同一次 clean 记录 q 组压缩量,q 次联合节点查询 | 2+q | q |
| clean 已结束且未记录压缩量,需补 clean | 3+q | 1+q |
| 独立 A/B,B 另有 clean,一次联合节点查询 | 4 | 2 |
| 选基后本步立即按新基训练,复用同点同 batch 的 clean,另查独立新方向 | 4 | 2 |
最低成本的逐步流程为:
1. 固定 θt 和旧基 dt;采样 Z、η,安装 clean 读取 hook。
2. 前向 f0,同时计算 vℓ;删除读取 hook。
3. 按正常训练扰动 θt+μu,查询 fW,原地逆扰动恢复;得到 rμ。
4. 在 θt 做一次联合节点前向 fN;删除注入 hook,得到式 (6)。
5. 保持旧基,用已有 rμ、同一 Z 完成本次正常权重 SGD。
6. 如以后接入选基,以幅值梯度作 d'ℓ=normalize(dℓ+ρ ĝ_dℓ),在第 5 步之后安装供下一步使用。
基梯度在 θt 计算,用于 θt+1 的下一次查询,存在一次权重更新的漂移。不能先换基再用旧 rμ 更新权重,也不能先更新权重再测节点而仍称两者对应同一点的梯度。若要求新基本步生效,须重新查询该新基的独立训练方向;同点同 batch、关闭随机 dropout 时 f0 可复用,所以共 4 次。
有限 ρ 下不保证每次 s 增长;估计方差、半径和基步长仍需研究。式 (6) 未控制曲率代价,不提供式 (2.3) 的下降保证。这里不增加 gate 或虚拟更新测试。
## 9. 数值验收
`tests/test_history_free_coverage.py` 使用实际小模型前向:两层独立 Linear,已知单位基,全局 Gaussian 两维;每维四点 Gauss–Hermite 求积及全部 16 组节点符号,得到 256 组加权估计。每组实际执行 3 次前向。对所用四次多项式目标,该求积精确积分相关多项式矩,剩余误差来自 FP64 算术。
验证线性/二次目标均值、光滑非二次目标 μ/ε 分别减半的偏差阶、式 (9) 的协方差、球面切向性、原有训练响应与 SGD 更新复用、原地恢复、异常 hook 清理及全局 RNG 不变。完整回归命令为 `.venv/bin/python -m pytest -q tests`。结果记录由 `scripts/validate_history_free_coverage.py` 写入共享 E 盘,诊断前向与实模训练查询分开记录。
2026-11-12 验收:自有测试 86 项通过,其中新增 7 项。线性目标均值最大绝对误差 1.11e-16,二次目标为 4.86e-17。非二次目标在固定另一半径为 1e-5 时,μ 从 .08/.04/.02 依次减半,偏差为 4.32534e-5/1.08133e-5/2.70334e-6;ε 分别减半时为 1.59941e-4/3.99853e-5/9.99632e-6,相邻比值均约 4。联合相对逐层节点查询的协方差差值与式 (9) 在 1e-11 绝对容差内一致;深层测试另验证下游 sketch 必须取 clean 输入。
审计结果位于 `E:/Experiments/Assets/results/history_free_coverage_audit_20261112T071429Z/validation.json`。独立审计脚本实际调用小模型诊断前向 6144 次,训练与评估查询均为 0;pytest 的小模型查询另由测试各自计数,不混入该脚本计数。四点求积精确积分四次目标的均值及线性目标的协方差;不宣称四次目标的协方差也由四点求积精确积分。
+236
View File
@@ -0,0 +1,236 @@
# fix / adjust / node
三种方法共用根目录的 uv 环境和一个 MeZO 风格入口,通过 `--trainer fix|adjust|node` 选择算法。
代码全部在 `methods/large_models/`,不再分设方案目录或包装入口。
## 入口与环境
在 WSL 项目根目录运行:
```bash
cd ~/experiments_codebase
source scripts/env.sh
uv sync --locked
uv run --locked python methods/large_models/run.py --trainer fix
uv run --locked python methods/large_models/run.py --trainer adjust --refresh_every 256
uv run --locked python methods/large_models/run.py --trainer node --refresh_every 128
# 模块入口与脚本入口等价
uv run --locked python -m methods.large_models.run --trainer node --help
```
各基线继续使用 `baselines/<方法>/` 内的独立环境,不与根环境混用。
依赖以根 `pyproject.toml` 和 `uv.lock` 为准。默认资源目录:
| 内容 | WSL 路径 |
|---|---|
| 模型 | `/mnt/e/Experiments/Assets/models` |
| 数据 | `/mnt/e/Experiments/Assets/data` |
| 训练输出、日志、检查点 | `/mnt/e/Experiments/Assets/results` |
通过根 `.env` 或 `EXPERIMENT_ASSETS` / `EXPERIMENT_MODELS` / `EXPERIMENT_DATA` / `EXPERIMENT_RESULTS` 覆盖。
输出目录必须位于配置的 results 内,且每次运行使用新目录。写入前检查 E 盘挂载。
## 从哪里读代码
```text
methods/
README.md
__init__.py
large_models/
run.py 参数解析、模型加载、Framework、训练/推理入口
trainer.py fix_step / adjust_step / node_step,预算、日志与保存
_upstream_run.py 复用的 MeZO Framework、OurArguments 与任务数据流
tasks.py MeZO 任务定义、样本与抽样
templates.py 任务模板
utils.py 编码、collator、候选答案 loss wrapper
metrics.py 作者预测评分实现
assets.py 连接共享本地数据
data.py 数据协议适配、随机种子与旧协议 sampler
native_losses.py MeZO loss 与节点探测所需任务分数
losses.py legacy 数据协议的 loss
logging_utils.py 日志、曲线和显存记录
MEZO_REUSE.json 复用来源、文件哈希与兼容修改
LICENSE.MeZO 上游许可证
```
训练循环在 `trainer.py` 中直接分派到三个 step。选基在 `top_basis` / `collect_basis`,
单边差分在 `zo_step`,实际权重更新在 `zo_update`,临时扰动与恢复在 `shifted`。
`subspace.py`、独立的方案入口和 provenance 源码目录均已移除。
## 三种算法
所有方法先用一次校准前向提取各 Linear 输入激活的未中心化主方向。每层基 `D` 的形状为 `[din, 1]`。
普通训练均沿单个高斯方向做两次前向和 SGD:
```python
s = (F_plus - F_zero) / mu
# Linear: z.shape == [dout, 1]
W.add_((s * z) @ D.T, alpha=-lr)
```
Embedding、Norm、bias 等其余参数使用原张量形状的高斯方向;绑定的 embedding/head 只更新一次。
当前只保存实际权重 `W`、输入基和 node 的历史,不维护 `W0/C/B/warm`。
换基只替换 `D`,已学到的更新留在 `W` 中。
| 方法 | 刷新流程 | 默认刷新间隔 | 算法变体 |
|---|---|---:|---|
| fix | 初始化后固定基 | 不刷新 | `fix` |
| adjust | 一个激活候选,一次新旧基虚拟更新比较;新基参考 loss 更低就接受 | 256 次更新 | `adjust_single_probe_v1` |
| node | 历史系数梯度与节点扰动构基;直接替换有效候选,不比较新旧基 | 128 次更新 | `node_unconditional_refresh_control_v1` |
2026-11-12 回退:默认 `--node_update original` 恢复此前无条件刷新版本,作为重新研究覆盖目标的起点。
当前曲率版本仍保留为显式选项;本次回退不启动训练,也未实现新的选基估计器。
回退前源码及测试备份位于 `E:/Experiments/Assets/results/node_coverage_rollback_20261112T065520Z`。
不依赖历史梯度的当前覆盖估计,完整推导和查询时序见 [HISTORY_FREE_COVERAGE.md](HISTORY_FREE_COVERAGE.md)。
`coverage_gradient_probe` 在 clean 前向读取压缩输入,再复用普通权重查询,最后做一次联合节点查询;
合计 3 次前向,返回球面基梯度和待消费的旧基训练响应。
2026-11-12 已接入 `coverage_step`:`--trainer node --node_update history_free --basis_lr 1e-5 --node_epsilon 1e-3 --zo_schedule constant`。
每 128 次更新同时刷新所有 untied Linear 基,先用旧基完成 SGD,再安装 `normalize(d + basis_lr * gradient)`。
保留幅值,不归一化 Gaussian、不取 sign、不使用 EMA、曲率项或新旧基 gate。
一次刷新总步成本 3 次(普通训练 2 次加节点 1 次);预算不足 3 次时继续普通 2 次更新。
数值验证用 `.venv/bin/python scripts/validate_history_free_coverage.py`,相关回归位于 `tests/test_history_free_coverage.py`。
2026-11-12 检查点协议对齐:默认 `select_best_checkpoint=true`,按每次更新后 development 评估的最小 loss
保存 `best_model/`,相同 loss 保留较早检查点;训练初始评估不参与选择。
训练继续沿当前权重进行,结束后将 development 最佳权重逐张量载回原模型,再评估 SST2 官方 validation。
`best_checkpoint.json` 记录所选步数、实际主查询数和 development 指标;最终 `model/` 导出所选权重。
`--no-save-checkpoint` 仅省略最终 `model/` 副本,仍保存选优所需的 `best_model/`。
显式 `--select_best_checkpoint false` 可恢复旧的末点权重评估协议;两种协议的结果应分别标记。
这些 HF 权重仅支持推理和评估,不包含子空间、sampler 或 RNG 的训练续跑状态。
2026-11-12:此前 `descent_gradient_proxy_v1` 未忠实实现约定推导,已撤下活动入口。其历史源码和结果仅作问题追溯,不能用于评价命题 2.1。曲率感知选基的推导、实现前提与验收计划见 [CURVATURE_DESCENT_PLAN.md](CURVATURE_DESCENT_PLAN.md)。
原文的 `H` 是分析用的有效二次上界,不要求所有训练算法显式计算它。
若新选基算法要优化式 (2.3) 的各向异性目标,则仍须说明完整目标的估计方式。
当前已补充单边差分与 batch 噪声的充分误差界,并用小规模数值测试验证;这不等于完成实模选基实现。
[计划第 6 节](CURVATURE_DESCENT_PLAN.md#6-完整条件算法各向异性上界目标的前向选基梯度)
现给出 `n=1` 的完整条件流程:在已知有效全局光滑常数 `L` 时,采用
`H = Hess F(theta) + 2 L I`,用三个独立训练 batch 估计总体下降目标,再做联合切空间基梯度更新。
一次选择需 13 次主前向,连同正常单边训练为 15 次。
`trainer.py` 已实现条件 API `curvature_refresh` / `curvature_step`,包括完整预算预留、
独立选择/训练 seed、分数差幅值更新及日志。调用者须提供三个独立 batch 和经过证明的
`certified_smoothness`;数值为正不代表通过上界认证。
该上界证书尚未针对实模建立,不能把 `L` 当作随意调节的参数;测试通过也不代表实模前提成立。
全局 `L` 并非必要:计划第 7 节已从当前 OPT 的最终 LayerNorm 推导全局损失增长
包络,并给出与局部证书拼接的有效上界构造。当前模型使用 ReLU,需要处理局部
可微范围及 Gaussian 尾部,不能直接使用全局 C4 假设。局部证书尚未建立,包络
系数不能冒充曲率常数。任意未知 `H` 也不能从式 (2.3) 中一般性消除。
2026-11-12 用户进一步明确允许工程近似实验。当前可用
`--trainer node --node_update local_curvature --basis_lr 1e-5 --basis_radius 1e-3`
运行 `local_curvature_gradient_v1`:以局部 Hessian 替代分析上界,不加未经证明的
平移常数;保留完整基梯度幅值、三个独立选择 batch、全部 Linear 的联合基更新。
权重训练继续使用作者 HF RandomSampler 和单边差分,选择 batch 独立抽样但不宣称
整个训练历史满足 iid 条件。该工程目标用于检验覆盖/曲率权衡,不能宣称已验证
命题的全局下降保证,也不复用历史 sign/固定角度代理结果。
此前已完成该变体的短训选参和 6000 主查询长训;所有选择前向计入预算。
以下默认 node 的历史构基与这一曲率变体是不同算法。
adjust 的一次比较使用配对随机方向,在训练池的参考 batch 上比较虚拟 SGD 更新后的 loss。
node 用历史系数梯度方向和节点扰动为三个 `v_proj` 层产生候选;目标层由 `configure_history` 选择,并写入参数清单。
`history_beta=0.9` 仅用于 node 选基,不是 SGD 动量。替换后清空所换层的历史;无有效候选的层保留原基和历史。
令当前单层梯度为 `G`、输入基为 `d`,旧构基的理想线性响应对应:
```python
h = beta * h + (1 - beta) * coefficient_gradient_estimate # 当前目标为 G @ d
p = h / h.norm()
b = node_sketch(p) # 理想条件下估计 G.T @ p
d_new = b / b.norm()
```
每层两次节点扰动用于估计向量 `G.T @ p`,不是直接估计标量 `s(d) = ||G @ d||^2`。
只有当 `p` 对齐当前 `G @ d` 且忽略估计误差时,归一化构基才对应一次 `G.T @ G` 幂迭代。
历史梯度随参数、数据和基变化会失配;纯覆盖构基也没有控制有限学习率下的曲率代价。
这两项是下一阶段需要推导和验证的问题,不能把回退当作已经修复它们。
原来的三点 `descent_probe` 保留为数值参考;默认 node 不再调用它。
当前没有半程插值、重复比较、SEM 门槛或独立复核;旧的 `probe_pairs`、`gate_k`、`gate_margin`、`node_variant` 参数已删除,传入会报错。
## 查询预算和显存
主预算为 `training + calibration`;评估查询独立计数。一次查询指对整个 collated batch 执行一次模型前向。
MeZO SST2 中每个样本有两条候选序列,因此一次查询的耗时不能直接等同于单序列读出协议。
| 操作 | 主前向次数 |
|---|---:|
| 初始校准构基 | 1 |
| 普通参数更新 | 2 |
| adjust 一次刷新检测 | 1 次构基 + 5 次虚拟更新比较 = 6 |
| node 一次刷新 | 默认至多 7 次节点构基,无新旧基检测 |
node 构基上界为 `1 + 目标层数 * node_queries`,默认三层、每层两次;开头的 1 次 clean 由各层共享。
刷新前会预留完整构基预算和下一次更新的 2 次前向,不足时继续普通训练;实际成本写入 `refresh.jsonl`。
`main_forward_budget` 是主要停止条件,`max_steps` 可进一步限制参数更新次数。
对当前训练方向,若已有 `F0/F+`,补 `F-` 只多一次前向。历史三点门控比较旧、新两个基需共享
`F0` 加四次扰动查询,共五次,候选构造另计;回退后的默认 node 不支出这五次查询。
参数表示标记为 `direct_weights_inplace_v2`。扰动原地加到 `W`,随后按同一种子重新生成噪声并反向减回。
不备份完整权重,不保存全模型噪声张量;前向异常时也执行反向恢复。
FP32 加减不保证逐位恢复,误差会影响后续差分;当前没有真实模型峰值显存测量。
## 常用参数
| 参数 | 默认值或用途 |
|---|---|
| `trainer` | `fix`;可选 `adjust`、`node` |
| `model_name` / `task_name` | `facebook/opt-1.3b` / `SST2`;也支持本地模型目录、`Qwen/Qwen3-0.6B` 和 `DROP` |
| `data_protocol` | `mezo` |
| `main_forward_budget` | 6000,含构基和检测 |
| `num_train` / `num_dev` / `num_eval` | 1000 / 500 / 872 |
| `per_device_train_batch_size` / `per_device_eval_batch_size` | 16 / 16 |
| `calibration_samples` / `max_length` | 16 / 128 |
| `learning_rate` / `zo_schedule` | fix、adjust 为 `1e-6` / `constant`;node 为 `1.5e-6` / `cosine` |
| `decay_start` / `lr_min` | 主查询 3000 后开始余弦衰减,默认最低为初始学习率的 0.1 倍 |
| `zo_eps` | 权重扰动幅度,默认 `1e-3` |
| `node_queries` / `node_epsilon` | 每层节点探测次数 2 / 节点扰动幅度 `1e-3` |
| `eval_main_forwards` | 每到约 600 次主前向后评估;不是更新步数 |
短参数 `--method/--model/--task/--budget/--lr/--mu` 仍有对应别名。完整参数以统一入口的 `--help` 为准。
公平比较时显式对齐学习率、调度、刷新层范围、采样和总预算。
```bash
uv run --locked python methods/large_models/run.py --trainer node \
--model_name Qwen/Qwen3-0.6B --task_name DROP \
--per_device_train_batch_size 2 --per_device_eval_batch_size 2 --max_length 512
```
## 数据协议
默认 `mezo` 使用作者的抽样、任务模板、候选编码和目标函数;调用复用的 `Framework.train`,
使用 HF RandomSampler,保留尾批。SST2 比较两个候选答案的似然,DROP 对有效答案 token 计算 batch loss。
预测评分调用作者的 `Framework.evaluate/metrics.py`;其 DROP 文本 F1 不等于 DROP 专用数字/多跨度官方评分。
显式 `legacy` 使用旧数据抽样、PCG batch 顺序、padding 和 loss:SST2 双标签读出 CE,DROP 按样本平均答案 CE,丢弃尾批。
它只切换数据协议,不恢复旧优化器或权重表示。旧的 `.pt` 检查点不受当前入口支持。
比较结果前对齐 seed/train_set_seed、样本量、长度和 batch size,并核对 `data_manifest.json`。
不同数据协议、参数表示或算法变体的缓存不能混用。`reports/` 中早期系数实现的逐值等价结果属于历史记录。
## 输出与推理
每次运行保存有效参数、环境、协议变体、源码和数据指纹,以及:
- `records.jsonl`:训练 loss、响应、更新范数、学习率、累计主查询数。
- `refresh.jsonl`:候选检测结果、是否接受及实际查询成本。
- `curve.json`、曲线图和 `progress.json/md`:评估点、耗时、显存及实际查询计数。
- `query_ledger.json`、`summary.json`:主查询与 evaluation 等分类计数。
- `model/`:默认直接调用 `save_pretrained` 保存标准 HF 模型;无偏移合并步骤。
`--no-save-checkpoint` 可只保存记录;当前检查点用于推理,不支持断点续训。
```bash
uv run --locked python methods/large_models/run.py --trainer node --action evaluate \
--checkpoint /mnt/e/Experiments/Assets/results/RUN/model
uv run --locked python methods/large_models/run.py --trainer node --action generate \
--checkpoint /mnt/e/Experiments/Assets/results/RUN/model --prompt 'Hello'
uv run --locked pytest tests
```
WSL 需正常的 NVIDIA 驱动和 git/curl/ca-certificates/libgomp/libstdc++;普通运行不要求 nvcc。
只支持单设备 FP32、rank=q=1、无 weight decay、裁剪和梯度累积。继承的 HF 参数不代表所有 HF 功能都可用。
MeZO 原版 Trainer 依赖旧私有 API;当前继承受支持的 HF Trainer,保留作者 `zo_forward`,兼容修改见 `MEZO_REUSE.json`。
测试验证数值机制和入口行为,不代表完整 benchmark 或论文性能复现。
+1
View File
@@ -0,0 +1 @@
"""MeZO-style implementation of fix, adjust and node."""
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 Princeton Natural Language Processing
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+96
View File
@@ -0,0 +1,96 @@
{
"commit": "552cb1b710767f9a6e1dc8f9645d7640376f9941",
"files": {
"templates.py": {
"upstream": "baselines/mezo/large_models/templates.py",
"upstream_sha256": "bc80e8f55c4d7cfdd3ca8493131297b6c7687d7ebc714ee5aebe16c6856ec2f6",
"reused_sha256": "bc80e8f55c4d7cfdd3ca8493131297b6c7687d7ebc714ee5aebe16c6856ec2f6",
"changes": []
},
"metrics.py": {
"upstream": "baselines/mezo/large_models/metrics.py",
"upstream_sha256": "a9146177b85b5aa654583ac2ed1f0c6aefb8940bf86aa4964ad02bd46165c94c",
"reused_sha256": "a9146177b85b5aa654583ac2ed1f0c6aefb8940bf86aa4964ad02bd46165c94c",
"changes": []
},
"tasks.py": {
"upstream": "baselines/mezo/large_models/tasks.py",
"upstream_sha256": "693c28ccc7e02997a7dced601f15a89d67a514581f98d1bc642768ef3271ed58",
"reused_sha256": "11f2904364f63f462aebb64adc191dc59fb0e0ad632c474f80c1d8617af45376",
"changes": [
{
"old": "from templates import *",
"new": "from .templates import *"
},
{
"old": "from utils import temp_seed",
"new": "from .utils import temp_seed"
},
{
"old": "from datasets import load_dataset",
"new": "from .assets import load_dataset"
}
]
},
"utils.py": {
"upstream": "baselines/mezo/large_models/utils.py",
"upstream_sha256": "04686e63041fcc9efce7284ead16c8b5a5aa6f6e648ede447b587cad9531b0aa",
"reused_sha256": "2b4df62167638e61f63ab7d90857d0d7114bb656f84b61f8e4f4ff68d0495570",
"changes": [
{
"old": "if tokenizer.add_bos_token:",
"new": "if getattr(tokenizer, \"add_bos_token\", False):"
}
]
},
"_upstream_run.py": {
"upstream": "baselines/mezo/large_models/run.py",
"upstream_sha256": "00b864c0e53c28f02572a510e6d612bfcca38682be843054bc1806354815bd81",
"reused_sha256": "32d6dc17ab9da185912c813b80487ce2db28fd213ac31b03cab6c801e9d742ec",
"changes": [
{
"old": "import tasks",
"new": "from . import tasks"
},
{
"old": "from tasks import get_task",
"new": "from .tasks import get_task"
},
{
"old": "from metrics import calculate_metric",
"new": "from .metrics import calculate_metric"
},
{
"old": "from utils import *",
"new": "from .utils import *"
},
{
"old": "from trainer import OurTrainer",
"new": "from .trainer import OurTrainer"
},
{
"old": "free_in_GB = int(torch.cuda.mem_get_info()[0]/1024**3)",
"new": "free_in_GB = int(torch.cuda.mem_get_info()[0]/1024**3) if torch.cuda.is_available() else 0"
},
{
"old": "config=config,\n )",
"new": "config=config,\n torch_dtype=torch.float32, attn_implementation=\"eager\", local_files_only=True,\n )"
},
{
"old": "tokenizer = AutoTokenizer.from_pretrained(self.args.model_name, use_fast=False)",
"new": "tokenizer = AutoTokenizer.from_pretrained(self.args.model_name, use_fast=\"qwen\" in self.args.model_name.lower(), local_files_only=True)\n if tokenizer.pad_token_id is None:\n tokenizer.pad_token = tokenizer.eos_token"
},
{
"old": "if self.args.save_on_interrupt:\n trainer.add_callback",
"new": "self.trainer = trainer\n if self.args.save_on_interrupt:\n trainer.add_callback"
}
]
}
},
"trainer_reuse": {
"upstream": "baselines/mezo/large_models/trainer.py:OurTrainer.zo_forward",
"ast_identical": true,
"base": "transformers.Trainer (modern supported API)",
"reason": "MeZO 2023 copied Trainer imports removed private APIs; retain original zo_forward and Framework, replace only inner loop with structured branches"
}
}
+1
View File
@@ -0,0 +1 @@
"""MeZO-style shared implementation for our structured optimizers."""
+532
View File
@@ -0,0 +1,532 @@
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
import argparse
import time
from . import tasks
from transformers import AutoConfig, AutoTokenizer, AutoModelForCausalLM, Trainer, HfArgumentParser, Trainer, TrainingArguments, DataCollatorWithPadding, DataCollatorForTokenClassification
from typing import Union, Optional
import torch
from torch.nn.parameter import Parameter
import numpy as np
from dataclasses import dataclass, is_dataclass, asdict
from tqdm import tqdm
from .tasks import get_task
import json
import torch.nn.functional as F
from torch.utils.data import Dataset
from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP
from .metrics import calculate_metric
from .utils import *
from .trainer import OurTrainer
import random
@dataclass
class OurArguments(TrainingArguments):
# dataset and sampling strategy
task_name: str = "SST2" # task name should match the string before Dataset in the Dataset class name. We support the following task_name: SST2, RTE, CB, BoolQ, WSC, WIC, MultiRC, Copa, ReCoRD, SQuAD, DROP
# Number of examples
num_train: int = 0 # ICL mode: number of demonstrations; training mode: number of training samples
num_dev: int = None # (only enabled with training) number of development samples
num_eval: int = None # number of evaluation samples
num_train_sets: int = None # how many sets of training samples/demos to sample; if None and train_set_seed is None, then we will sample one set for each evaluation sample
train_set_seed: int = None # designated seed to sample training samples/demos
result_file: str = None # file name for saving performance; if None, then use the task name, model name, and config
# Model loading
model_name: str = "facebook/opt-125m" # HuggingFace model name
load_float16: bool = False # load model parameters as float16
load_bfloat16: bool = False # load model parameters as bfloat16
load_int8: bool = False # load model parameters as int8
max_length: int = 2048 # max length the model can take
no_auto_device: bool = False # do not load model by auto device; should turn this on when using FSDP
# Calibration
sfc: bool = False # whether to use SFC calibration
icl_sfc: bool = False # whether to use SFC calibration for ICL samples
# Training
trainer: str = "none"
## options
## - none: no training -- for zero-shot or in-context learning (ICL)
## - regular: regular huggingface trainer -- for fine-tuning
## - zo: zeroth-order (MeZO) training
only_train_option: bool = True # whether to only train the option part of the input
train_as_classification: bool = False # take the log likelihood of all options and train as classification
# MeZO
zo_eps: float = 1e-3 # eps in MeZO
# Prefix tuning
prefix_tuning: bool = False # whether to use prefix tuning
num_prefix: int = 5 # number of prefixes to use
no_reparam: bool = True # do not use reparameterization trick
prefix_init_by_real_act: bool = True # initialize prefix by real activations of random words
# LoRA
lora: bool = False # whether to use LoRA
lora_alpha: int = 16 # alpha in LoRA
lora_r: int = 8 # r in LoRA
# Generation
sampling: bool = False # whether to use sampling
temperature: float = 1.0 # temperature for generation
num_beams: int = 1 # number of beams for generation
top_k: int = None # top-k for generation
top_p: float = 0.95 # top-p for generation
max_new_tokens: int = 50 # max number of new tokens to generate
eos_token: str = "\n" # end of sentence token
# Saving
save_model: bool = False # whether to save the model
no_eval: bool = False # whether to skip evaluation
tag: str = "" # saving tag
# Linear probing
linear_probing: bool = False # whether to do linear probing
lp_early_stopping: bool = False # whether to do early stopping in linear probing
head_tuning: bool = False # head tuning: only tune the LM head
# Untie emb/lm_head weights
untie_emb: bool = False # untie the embeddings and LM head
# Display
verbose: bool = False # verbose output
# Non-diff objective
non_diff: bool = False # use non-differentiable objective (only support F1 for SQuAD for now)
# Auto saving when interrupted
save_on_interrupt: bool = False # save model when interrupted (useful for long training)
def parse_args():
parser = argparse.ArgumentParser()
parser = HfArgumentParser(OurArguments)
args = parser.parse_args_into_dataclasses()[0]
print(args)
return args
def set_seed(seed: int):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
class Framework:
def __init__(self, args, task):
self.args = args
self.task = task
self.model, self.tokenizer = self.load_model()
def load_model(self):
"""
Load HuggingFace models
"""
with count_time("Loading model with FP%d" % (16 if self.args.load_float16 else 32)):
free_in_GB = int(torch.cuda.mem_get_info()[0]/1024**3) if torch.cuda.is_available() else 0
config = AutoConfig.from_pretrained(self.args.model_name)
if self.args.untie_emb:
# Untie embeddings/LM head
logger.warn("Untie embeddings and LM head")
config.tie_word_embeddings = False
if self.args.head_tuning:
# Head tuning
from ht_opt import OPTForCausalLM
model = OPTForCausalLM.from_pretrained(
self.args.model_name,
config=config,
torch_dtype=torch.float32, attn_implementation="eager", local_files_only=True,
)
elif self.args.no_auto_device:
# No auto device (use for FSDP)
model = AutoModelForCausalLM.from_pretrained(
self.args.model_name,
config=config,
torch_dtype=torch.float32, attn_implementation="eager", local_files_only=True,
)
else:
# Auto device loading
torch_dtype = torch.float32
if self.args.load_float16:
torch_dtype = torch.float16
elif self.args.load_bfloat16:
torch_dtype = torch.bfloat16
model = AutoModelForCausalLM.from_pretrained(
self.args.model_name,
config=config,
device_map='auto',
torch_dtype=torch_dtype,
max_memory={i: f'{free_in_GB-5}GB' for i in range(torch.cuda.device_count())},
load_in_8bit=self.args.load_int8,
)
model.eval()
# Load tokenizer
tokenizer = AutoTokenizer.from_pretrained(self.args.model_name, use_fast="qwen" in self.args.model_name.lower(), local_files_only=True)
if tokenizer.pad_token_id is None:
tokenizer.pad_token = tokenizer.eos_token
# HF tokenizer bug fix
if "opt" in self.args.model_name:
tokenizer.bos_token_id = 0
if "llama" in self.args.model_name:
# LLaMA padding token
tokenizer.pad_token_id = 0 # technically <unk>
# Prefix tuning/LoRA
if self.args.prefix_tuning:
from prefix import PrefixTuning
PrefixTuning(model, num_prefix=self.args.num_prefix, reparam=not self.args.no_reparam, float16=self.args.load_float16, init_by_real_act=self.args.prefix_init_by_real_act)
if self.args.lora:
from lora import LoRA
LoRA(model, r=self.args.lora_r, alpha=self.args.lora_alpha, float16=self.args.load_float16)
if self.args.head_tuning:
if model.config.model_type == "opt":
head_name = "lm_head" if self.args.untie_emb else "embed_tokens"
else:
raise NotImplementedError
for n, p in model.named_parameters():
if head_name not in n:
p.requires_grad = False
else:
logger.info(f"Only tuning {n}")
return model, tokenizer
def forward(self, input_ids, option_len=None, generation=False):
"""
Given input_ids and the length of the option, return the log-likelihood of each token in the option.
For generation tasks, return the generated text.
This function is only for inference
"""
input_ids = torch.tensor([input_ids]).to(self.model.device)
if generation:
args = self.args
# Autoregressive generation
outputs = self.model.generate(
input_ids, do_sample=args.sampling, temperature=args.temperature,
num_beams=args.num_beams, top_p=args.top_p, top_k=args.top_k, max_new_tokens=min(args.max_new_tokens, args.max_length - input_ids.size(1)),
num_return_sequences=1, eos_token_id=[self.tokenizer.encode(args.eos_token, add_special_tokens=False)[-1], self.tokenizer.eos_token_id],
)
# For generation, directly return the text output
output_text = self.tokenizer.decode(outputs[0][input_ids.size(1):], skip_special_tokens=True).strip()
return output_text
else:
with torch.inference_mode():
self.model.eval()
logits = self.model(input_ids=input_ids).logits
labels = input_ids[0, 1:]
logits = logits[0, :-1]
log_probs = F.log_softmax(logits, dim=-1)
selected_log_probs = log_probs[torch.arange(len(labels)).to(labels.device), labels]
selected_log_probs = selected_log_probs.cpu().detach()
# Only return the option (candidate) part
return selected_log_probs[-option_len:]
def one_step_pred(self, train_samples, eval_sample, verbose=False):
"""
Return the prediction on the eval sample. In ICL, use train_samples as demonstrations
"""
verbose = verbose or self.args.verbose
if verbose:
logger.info("========= Example =========")
logger.info(f"Candidate: {eval_sample.candidates}")
logger.info(f"Correct candidate: {eval_sample.correct_candidate}")
# Encode (add prompt and tokenize) the sample; if multiple-choice/classification, encode all candidates (options)
encoded_candidates, option_lens = encode_prompt(
self.task, self.task.get_template(), train_samples, eval_sample, self.tokenizer, max_length=self.args.max_length,
generation=self.task.generation, max_new_tokens=self.args.max_new_tokens
)
# Calibration
if self.args.sfc or self.args.icl_sfc:
sfc_encoded_candidates, sfc_option_lens = encode_prompt(self.task, self.task.get_template(),
train_samples, eval_sample, self.tokenizer, max_length=self.args.max_length,
sfc=self.args.sfc, icl_sfc=self.args.icl_sfc, generation=self.task.generation,
max_new_tokens=self.args.max_new_tokens
)
outputs = []
if self.task.generation:
# For generation tasks, return the autoregressively-generated text
output_text = self.forward(encoded_candidates[0], generation=True)
if verbose:
logger.info("=== Prompt ===")
logger.info(self.tokenizer.decode(encoded_candidates[0]))
logger.info(f"Output: {output_text}")
return Prediction(correct_candidate=eval_sample.correct_candidate, predicted_candidate=output_text)
else:
# For classification/multiple-choice, calculate the probabilities of all candidates
for candidate_id, encoded_candidate in enumerate(encoded_candidates):
selected_log_probs = self.forward(encoded_candidate, option_len=option_lens[candidate_id])
if verbose:
if candidate_id == 0:
logger.info("=== Candidate %d ===" % candidate_id)
logger.info(self.tokenizer.decode(encoded_candidate))
else:
logger.info("=== Candidate %d (without context)===" % candidate_id)
logger.info(self.tokenizer.decode(encoded_candidate).split(self.task.train_sep)[-1])
logger.info(f"Log probabilities of the option tokens: {selected_log_probs}")
if self.args.sfc or self.args.icl_sfc:
sfc_selected_log_probs = self.forward(sfc_encoded_candidates[candidate_id], option_len=sfc_option_lens[candidate_id])
if verbose:
logger.info("=== Candidate %d (without context) SFC ===" % candidate_id)
logger.info(self.tokenizer.decode(sfc_encoded_candidates[candidate_id]).split(self.task.train_sep)[-1])
logger.info(f"Log probabilities of the option tokens: {sfc_selected_log_probs}")
outputs.append({"log_probs": selected_log_probs, "sfc_log_probs": sfc_selected_log_probs if self.args.sfc or self.args.icl_sfc else None})
if self.args.sfc or self.args.icl_sfc:
# Calibrated probabilities (surface form competition; https://arxiv.org/pdf/2104.08315.pdf)
# log p(candidate | input) = log p_lm(candidate | input) - log p_lm(candidate | sfc prompt)
scores = [x['log_probs'].sum().item() - x['sfc_log_probs'].sum().item() for x in outputs]
else:
# (Default) length-normalized log probabilities
# log p(candidate | input) = log p_lm(candidate | input) / |candidate #tokens|
scores = [x['log_probs'].mean().item() for x in outputs]
if verbose:
logger.info(f"Prediction scores: {scores}")
if isinstance(eval_sample.correct_candidate, list):
# For some datasets there are multiple correct answers
correct_candidate_id = [eval_sample.candidates.index(c) for c in eval_sample.correct_candidate]
else:
correct_candidate_id = eval_sample.candidates.index(eval_sample.correct_candidate)
return Prediction(correct_candidate=correct_candidate_id, predicted_candidate=int(np.argmax(scores)))
def evaluate(self, train_samples, eval_samples, one_train_set_per_eval_sample=False):
"""
Evaluate function. If one_train_set_per_eval_sample is True, then each eval sample has its own training (demonstration) set.
"""
if one_train_set_per_eval_sample:
logger.info(f"There are {len(eval_samples)} validation samples and one train set per eval sample")
else:
logger.info(f"There are {len(train_samples)} training samples and {len(eval_samples)} validation samples")
# Prediction loop
predictions = []
for eval_id, eval_sample in enumerate(tqdm(eval_samples)):
predictions.append(
self.one_step_pred(train_samples[eval_id] if one_train_set_per_eval_sample else train_samples, eval_sample, verbose=(eval_id < 3))
)
# Calculate metrics
metric_name = getattr(self.task, "metric_name", "accuracy")
metrics = {metric_name: calculate_metric(predictions, metric_name)}
return metrics
def train(self, train_samples, eval_samples):
"""
Training function
"""
# Set tokenizer to left padding (so that all the options are right aligned)
self.tokenizer.padding_side = "left"
class HFDataset(Dataset):
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
return self.data[idx]
def _convert(samples):
"""
Convert samples to HF-compatible dataset
"""
data = []
for sample in samples:
encoded_candidates, option_lens = encode_prompt(
self.task, self.task.get_template(), [], sample, self.tokenizer,
max_length=self.args.max_length, generation=self.task.generation, generation_with_gold=True,
max_new_tokens=self.args.max_new_tokens
)
if self.task.generation:
correct_candidate_id = 0
elif isinstance(sample.correct_candidate, list):
correct_candidate_id = sample.candidates.index(sample.correct_candidate[0])
else:
correct_candidate_id = sample.candidates.index(sample.correct_candidate)
if self.args.non_diff:
# For non-differentiable objective, there is no teacher forcing thus the
# current answer part is removed
encoded_candidates[correct_candidate_id] = encoded_candidates[correct_candidate_id][:-option_lens[correct_candidate_id]]
if self.args.train_as_classification:
# For classification, we provide the label as the correct candidate id
data.append([{"input_ids": encoded_candidates[_i], "labels": correct_candidate_id, "option_len": option_lens[_i], "num_options": len(sample.candidates)} for _i in range(len(encoded_candidates))])
elif self.args.only_train_option:
# Otherwise, it is just LM-style teacher forcing
if self.args.non_diff:
# For non-differentiable objective, we need to provide the gold answer to calculate F1/acc
data.append({"input_ids": encoded_candidates[correct_candidate_id], "labels": encoded_candidates[correct_candidate_id], "option_len": option_lens[correct_candidate_id], "gold": sample.correct_candidate})
else:
data.append({"input_ids": encoded_candidates[correct_candidate_id], "labels": encoded_candidates[correct_candidate_id], "option_len": option_lens[correct_candidate_id]})
else:
data.append({"input_ids": encoded_candidates[correct_candidate_id], "labels": encoded_candidates[correct_candidate_id]})
return data
with count_time("Tokenizing training samples"):
train_dataset = HFDataset(_convert(train_samples))
eval_dataset = HFDataset(_convert(eval_samples))
if self.args.only_train_option and not self.args.non_diff:
# If --only_train_option and not with a non-differentiable objective, we wrap the forward function
self.model.original_forward = self.model.forward
self.model.forward = forward_wrap_with_option_len.__get__(self.model, type(self.model))
if self.args.non_diff:
collator = NondiffCollator
else:
collator = DataCollatorForTokenClassification
trainer = OurTrainer(
model=self.model,
args=self.args,
train_dataset=train_dataset,
eval_dataset=eval_dataset,
tokenizer=self.tokenizer,
data_collator=DataCollatorWithPaddingAndNesting(self.tokenizer, pad_to_multiple_of=8) if self.args.train_as_classification else collator(self.tokenizer, pad_to_multiple_of=8),
)
self.trainer = trainer
if self.args.save_on_interrupt:
trainer.add_callback(SIGUSR1Callback())
# Resume training from a last checkpoint
last_checkpoint = None
from transformers.trainer_utils import get_last_checkpoint
if os.path.isdir(self.args.output_dir) and not self.args.overwrite_output_dir:
last_checkpoint = get_last_checkpoint(self.args.output_dir)
if last_checkpoint is not None and self.args.resume_from_checkpoint is None:
logger.info(
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
)
if self.args.resume_from_checkpoint is not None:
last_checkpoint = self.args.resume_from_checkpoint
trainer.train(resume_from_checkpoint=last_checkpoint)
# Explicitly save the model
if self.args.save_model:
logger.warn("Save model..")
trainer.save_model()
# FSDP compatibility
self.model = trainer.model
# Reset the forward function for evaluation
if self.args.only_train_option and not self.args.non_diff:
if type(self.model) == FSDP:
logger.info("This is an FSDP model now. Be careful when assigning back the original forward function")
self.model._fsdp_wrapped_module.forward = self.model._fsdp_wrapped_module.original_forward
else:
self.model.forward = self.model.original_forward
def result_file_tag(args):
"""
Get the result file tag
"""
save_model_name = args.model_name.split("/")[-1]
sfc_tag = "-sfc" if args.sfc else ""
icl_sfc_tag = "-icl_sfc" if args.icl_sfc else ""
sample_eval_tag = "-sampleeval%d" % args.num_eval if args.num_eval is not None else ""
sample_train_tag = "-ntrain%d" % args.num_train if args.num_train > 0 else ""
sample_dev_tag = "-ndev%d" % args.num_dev if args.num_dev is not None else ""
customized_tag = f"-{args.tag}" if len(args.tag) > 0 else ""
return f"{args.task_name}-{save_model_name}" + sfc_tag + icl_sfc_tag + sample_eval_tag + sample_train_tag + sample_dev_tag + customized_tag
def main():
args = parse_args()
set_seed(args.seed)
task = get_task(args.task_name)
train_sets = task.sample_train_sets(num_train=args.num_train, num_dev=args.num_dev, num_eval=args.num_eval, num_train_sets=args.num_train_sets, seed=args.train_set_seed)
# Initialize trainer and load model
framework = Framework(args, task)
if args.train_set_seed is not None or args.num_train_sets is not None:
# Eval samples share one (or multiple) training set(s)
for train_set_id, train_samples in enumerate(train_sets):
train_set_seed = train_set_id if args.train_set_seed is None else args.train_set_seed
# Sample eval samples
if args.num_eval is not None:
eval_samples = task.sample_subset(data_split="valid", seed=train_set_seed, num=args.num_eval)
else:
eval_samples = task.valid_samples
if args.trainer != "none":
if args.num_dev is not None:
# Dev samples
dev_samples = train_samples[-args.num_dev:]
train_samples = train_samples[:-args.num_dev]
else:
dev_samples = None
# Training
framework.train(train_samples, dev_samples if dev_samples is not None else eval_samples)
if not args.no_eval:
metrics = framework.evaluate([], eval_samples) # No in-context learning if there is training
if dev_samples is not None:
dev_metrics = framework.evaluate([], dev_samples)
for m in dev_metrics:
metrics["dev_" + m] = dev_metrics[m]
else:
assert args.num_dev is None
# Zero-shot / in-context learning
metrics = framework.evaluate(train_samples, eval_samples)
if not args.no_eval:
logger.info("===== Train set %d =====" % train_set_seed)
logger.info(metrics)
if args.local_rank <= 0:
write_metrics_to_file(metrics, "result/" + result_file_tag(args) + f"-trainset{train_set_id}.json" if args.result_file is None else args.result_file)
else:
# For each eval sample, there is a training set. no training is allowed
# This is for in-context learning (ICL)
assert args.trainer == "none"
if args.num_eval is not None:
eval_samples = task.sample_subset(data_split="valid", seed=0, num=args.num_eval)
else:
eval_samples = task.valid_samples
metrics = framework.evaluate(train_sets, eval_samples, one_train_set_per_eval_sample=True)
logger.info(metrics)
if args.local_rank <= 0:
write_metrics_to_file(metrics, "result/" + result_file_tag(args) + "-onetrainpereval.json" if args.result_file is None else args.result_file)
if __name__ == "__main__":
main()
+9
View File
@@ -0,0 +1,9 @@
"""MeZO's Dataset API backed by the shared local assets, without global monkeypatching."""
from datasets import load_from_disk
from experiments_codebase.paths import paths
def load_dataset(name,config=None,**kwargs):
alias='sst2' if name in ('glue','nyu-mll/glue') and config=='sst2' else ('drop' if name in ('drop','ucinlp/drop') else None)
if alias is None:raise ValueError('This audited integration supports SST2 and DROP only')
dataset=load_from_disk(str(paths()['data']/alias))
return dataset[kwargs['split']] if 'split' in kwargs else dataset
+69
View File
@@ -0,0 +1,69 @@
"""Legacy protocol compatibility and deterministic HF data loading."""
import math
import numpy as np
import torch
from torch.utils.data import Dataset,Sampler
from datasets import load_from_disk
from experiments_codebase.paths import paths
def seed_for(seed, stream, step=0):
"""由总种子、用途编号和步数隔开数据采样、训练和选基的随机流。"""
return int(np.random.SeedSequence([seed, stream, step]).generate_state(1, dtype=np.uint64)[0] % (2 ** 63 - 1))
class HFDataset(Dataset):
def __init__(self,rows):self.data=rows
def __len__(self):return len(self.data)
def __getitem__(self,index):return self.data[index]
class ProtocolSampler(Sampler):
"""Same independent PCG batch-order stream as the previous implementation."""
def __init__(self,dataset,seed):self.dataset=dataset;self.rng=np.random.default_rng(seed_for(seed,11))
def __iter__(self):return iter(self.rng.permutation(len(self.dataset)).tolist())
def __len__(self):return len(self.dataset)
class LegacyCollator:
def __init__(self,tokenizer):self.tokenizer=tokenizer
def __call__(self,rows):
width=math.ceil(max(len(r['input_ids']) for r in rows)/8)*8
ids=torch.full((len(rows),width),self.tokenizer.pad_token_id,dtype=torch.long)
mask=torch.zeros_like(ids);targets=torch.full_like(ids,-100)
for i,row in enumerate(rows):
size=len(row['input_ids']);ids[i,-size:]=torch.tensor(row['input_ids']);mask[i,-size:]=1
if row.get('answer_length',0):targets[i,-row['answer_length']:]=ids[i,-row['answer_length']:]
labels=torch.tensor([r['label'] for r in rows]) if 'label' in rows[0] else targets
return dict(input_ids=ids,attention_mask=mask,labels=labels)
def legacy_rows(args,tokenizer):
ds=load_from_disk(str(paths()['data']/args.task_name.lower()));rng=np.random.default_rng(args.seed)
n=args.num_train+args.num_dev
if n>len(ds['train']):raise ValueError('Train and development counts exceed available data')
ids=rng.permutation(len(ds['train']))[:n];groups={}
for split,source,indices in [('train','train',ids[:args.num_train]),('development','train',ids[args.num_train:]),('validation','validation',range(min(args.num_eval,len(ds['validation']))))]:
rows=[]
for i in indices:
row=ds[source][int(i)]
if args.task_name=='SST2':
tokens=tokenizer.encode(f"{row['sentence'].strip()} It was",add_special_tokens=True,truncation=True,max_length=args.max_length)
rows.append(dict(input_ids=tokens,label=int(row['label']),source_index=int(i),source_split=source))
else:
answers=[str(v) for v in row['answers_spans']['spans']]
answer=tokenizer.encode(' '+answers[0],add_special_tokens=False)[:min(32,args.max_length//4)]
prompt=f"Passage: {row['passage']}\nQuestion: {row['question']}\nAnswer:"
tokens=tokenizer.encode(prompt,add_special_tokens=True,truncation=True,max_length=args.max_length-len(answer))
if not tokens or not answer:raise ValueError('Empty DROP prompt or answer')
rows.append(dict(input_ids=tokens+answer,prompt_ids=tokens,answer_length=len(answer),answers=answers,source_index=int(i),source_split=source))
groups[split]=rows
return groups
def convert_samples(task,samples,tokenizer,args):
"""MeZO Framework._convert for evaluation; unsupported modes are rejected by CLI."""
from .utils import encode_prompt
data=[]
for sample in samples:
candidates,lengths=encode_prompt(task,task.get_template(),[],sample,tokenizer,max_length=args.max_length,
generation=task.generation,generation_with_gold=True,max_new_tokens=args.max_new_tokens)
correct=0 if task.generation else sample.candidates.index(sample.correct_candidate[0] if isinstance(sample.correct_candidate,list) else sample.correct_candidate)
if args.train_as_classification:
data.append([{'input_ids':candidates[i],'labels':correct,'option_len':lengths[i],'num_options':len(sample.candidates)} for i in range(len(candidates))])
else:data.append({'input_ids':candidates[correct],'labels':candidates[correct],'option_len':lengths[correct]})
return data
+34
View File
@@ -0,0 +1,34 @@
"""Shared output helpers; no model loading or optimizer dependencies."""
from contextlib import contextmanager,redirect_stdout,redirect_stderr
import sys
import torch
def memory():
if not torch.cuda.is_available():return {}
torch.cuda.synchronize();free,total=torch.cuda.mem_get_info();g=2**30
return dict(allocated_GiB=torch.cuda.memory_allocated()/g,reserved_GiB=torch.cuda.memory_reserved()/g,
peak_allocated_GiB=torch.cuda.max_memory_allocated()/g,device_used_GiB=(total-free)/g,device_total_GiB=total/g)
def figures(out,curve):
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
for key,name in [('loss','loss_curve.png'),('accuracy','acc_curve.png')]:
fig,ax=plt.subplots(figsize=(8,4));found=False
for split in ('train_probe','development'):
points=[p for p in curve if key in p[split]]
if points:ax.plot([p['main_forwards'] for p in points],[p[split][key] for p in points],label=split);found=True
if found:
ax.set(xlabel='Cumulative main forwards (including probes)',ylabel=key);ax.grid(alpha=.2);ax.legend();fig.tight_layout();fig.savefig(out/name,dpi=160)
plt.close(fig)
class Tee:
def __init__(self,*streams):self.streams=streams
def write(self,text):
for stream in self.streams:stream.write(text);stream.flush()
def flush(self):
for stream in self.streams:stream.flush()
@staticmethod
@contextmanager
def redirect(log):
with redirect_stdout(Tee(sys.stdout,log)),redirect_stderr(Tee(sys.stderr,log)):yield
+22
View File
@@ -0,0 +1,22 @@
import torch
import torch.nn.functional as F
class LegacyLoss:
"""Keep the previous loss and efficient readout exactly for equivalence testing."""
def __init__(self,model,tokenizer,task):
from types import SimpleNamespace
self.model=model;self.args=SimpleNamespace(task=task.lower())
self.label_ids=[tokenizer.encode(w,add_special_tokens=False)[0] for w in (' terrible',' great')]
def __call__(self,inputs):
hidden=self.model.model(input_ids=inputs['input_ids'],attention_mask=inputs['attention_mask'],use_cache=False).last_hidden_state
if self.args.task=='sst2':
logits=self.model.lm_head(hidden[:,-1])[:,self.label_ids]
losses=F.cross_entropy(logits.float(),inputs['labels'],reduction='none')
else:
shifted=inputs['labels'][:,1:];valid=shifted!=-100
logits=self.model.lm_head(hidden[:,:-1][valid]).float()
token_loss=F.cross_entropy(logits,shifted[valid],reduction='none')
owner=torch.arange(len(hidden),device=hidden.device)[:,None].expand_as(valid)[valid]
losses=torch.zeros(len(hidden),device=hidden.device).scatter_add_(0,owner,token_loss)/valid.sum(1).clamp_min(1)
if not bool(torch.isfinite(losses).all()):raise FloatingPointError('Nonfinite loss')
return losses,logits
+78
View File
@@ -0,0 +1,78 @@
import numpy as np
import collections
import re
import string
from collections import Counter
def normalize_answer(s):
"""Lower text and remove punctuation, articles and extra whitespace."""
def remove_articles(text):
return re.sub(r'\b(a|an|the)\b', ' ', text)
def white_space_fix(text):
return ' '.join(text.split())
def remove_punc(text):
exclude = set(string.punctuation)
return ''.join(ch for ch in text if ch not in exclude)
def lower(text):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(s))))
def calculate_metric(predictions, metric_name):
if metric_name == "accuracy":
if isinstance(predictions[0].correct_candidate, list):
return np.mean([pred.predicted_candidate in pred.correct_candidate for pred in predictions])
else:
return np.mean([pred.correct_candidate == pred.predicted_candidate for pred in predictions])
elif metric_name == "em":
# For question answering
return np.mean([any([normalize_answer(ans) == normalize_answer(pred.predicted_candidate) for ans in pred.correct_candidate]) for pred in predictions])
elif metric_name == "f1":
# For question answering
f1 = []
for pred in predictions:
all_f1s = []
if pred.correct_candidate[0] == "CANNOTANSWER" or pred.correct_candidate[0] == "no answer":
f1.append(int(normalize_answer(pred.correct_candidate[0]) == normalize_answer(pred.predicted_candidate)))
else:
for ans in pred.correct_candidate:
prediction_tokens = normalize_answer(pred.predicted_candidate).split()
ground_truth_tokens = normalize_answer(ans).split()
common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
num_same = sum(common.values())
if num_same == 0:
all_f1s.append(0)
else:
precision = 1.0 * num_same / len(prediction_tokens)
recall = 1.0 * num_same / len(ground_truth_tokens)
all_f1s.append((2 * precision * recall) / (precision + recall))
f1.append(max(all_f1s))
return np.mean(f1)
def f1(pred, gold):
"""
This separate F1 function is used as non-differentiable metric for SQuAD
"""
if gold[0] == "CANNOTANSWER" or gold[0] == "no answer":
return int(normalize_answer(gold[0]) == normalize_answer(pred))
else:
all_f1s = []
for ans in gold:
prediction_tokens = normalize_answer(pred).split()
ground_truth_tokens = normalize_answer(ans).split()
common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
num_same = sum(common.values())
if num_same == 0:
all_f1s.append(0)
else:
precision = 1.0 * num_same / len(prediction_tokens)
recall = 1.0 * num_same / len(ground_truth_tokens)
all_f1s.append((2 * precision * recall) / (precision + recall))
return np.max(all_f1s)
+26
View File
@@ -0,0 +1,26 @@
"""Diagnostics around the unchanged MeZO option-loss wrapper; its scalar loss is authoritative."""
import torch
import torch.nn.functional as F
class MeZOLoss:
def __init__(self,model):self.model=model;self.last_weight=None
def __call__(self,inputs):
output=self.model(**inputs,return_dict=True)
labels=inputs['input_ids'][:,1:].clone();labels[labels==self.model.config.pad_token_id]=-100
for index,length in enumerate(inputs['option_len']):
if int(length)<=0:raise ValueError('Empty MeZO option after encoding/truncation')
labels[index,:-int(length)]=-100
valid=labels!=-100
if 'num_options' in inputs:
options=int(inputs['num_options'][0])
if options!=2 or not bool((inputs['num_options']==2).all()):raise ValueError('Current node/diagnostic integration supports binary SST2 options only')
log_probs=output.logits[:,:-1].log_softmax(-1)
selected=log_probs.gather(-1,labels.masked_fill(~valid,0).unsqueeze(-1)).squeeze(-1)
scores=((selected*valid).sum(-1)/valid.sum(-1)).view(-1,2)
# Repeat per-example scores for the two candidate activation rows.
logits=scores.repeat_interleave(2,dim=0);self.last_weight=len(scores)
else:
logits=output.logits.new_empty((len(labels),0));self.last_weight=int(valid.sum())
# Preserve the author's scalar/token-weighted objective, rather than
# replacing it with a mean of per-example token losses.
return output.loss.expand(len(inputs['input_ids'])),logits
+258
View File
@@ -0,0 +1,258 @@
"""MeZO project structure with fix/adjust/node Trainer branches and explicit data protocols."""
import sys
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
sys.path.insert(0,str(ROOT/'src'))
if __package__ in (None,''):
sys.path.insert(0,str(ROOT))
from methods.large_models.run import main
if __name__=='__main__':main()
raise SystemExit
from dataclasses import dataclass,field,asdict
from datetime import datetime,timezone
import hashlib
import importlib.metadata
import json
from typing import Optional
import torch
from transformers import HfArgumentParser
from experiments_codebase.paths import paths,model_path,save
from ._upstream_run import Framework as MeZOFramework,OurArguments as MeZOArguments,set_seed
from .tasks import get_task
from .trainer import OurTrainer
from .data import HFDataset,LegacyCollator,legacy_rows,convert_samples
from .utils import DataCollatorWithPaddingAndNesting,forward_wrap_with_option_len
from .logging_utils import Tee
@dataclass
class OurArguments(MeZOArguments):
trainer: str='fix'
model_name: str='facebook/opt-1.3b'
data_protocol: str='mezo'
main_forward_budget: int=6000
num_train: int=1000
num_dev: int=500
num_eval: int=872
max_length: int=128
max_new_tokens: int=32
seed: int=2026110791
per_device_train_batch_size: int=16
per_device_eval_batch_size: int=16
calibration_samples: int=16
refresh_every: Optional[int]=None
node_queries: int=2
node_epsilon: float=1e-3
node_update: str='original'
basis_lr: float=1e-5
basis_radius: float=1e-3
history_beta: float=.9
zo_schedule: Optional[str]=None
decay_start: int=3000
lr_min: Optional[float]=None
eval_main_forwards: int=600
rank: int=1
q: int=1
save_final_checkpoint: bool=True
select_best_checkpoint: bool=True
preflight_only: bool=False
action: str='train'
checkpoint: Optional[str]=None
prompt: Optional[str]=None
dtype: str='float32'
resume_from_checkpoint: Optional[str]=None
no_auto_device: bool=True
optim: str='sgd'
weight_decay: float=0.
fp16: bool=False
bf16: Optional[bool]=False
remove_unused_columns: bool=False
dataloader_drop_last: Optional[bool]=None
dataloader_num_workers: int=0
report_to: list[str]=field(default_factory=list)
disable_tqdm: bool=True
ALIASES={'--method':'--trainer','--model':'--model_name','--task':'--task_name','--budget':'--main_forward_budget','--lr':'--learning_rate','--mu':'--zo_eps',
'--batch-size':'--per_device_train_batch_size','--eval-batch-size':'--per_device_eval_batch_size','--train-samples':'--num_train','--dev-samples':'--num_dev','--eval-samples':'--num_eval',
'--calibration-samples':'--calibration_samples','--max-length':'--max_length','--eval-every':'--eval_main_forwards','--refresh-every':'--refresh_every',
'--node-queries':'--node_queries','--node-epsilon':'--node_epsilon','--history-beta':'--history_beta','--schedule':'--zo_schedule',
'--decay-start':'--decay_start','--lr-min':'--lr_min','--max-new-tokens':'--max_new_tokens','--out':'--output_dir','--weight-decay':'--weight_decay','--data-protocol':'--data_protocol'}
def parse_args(argv=None,forced_method=None):
raw=list(sys.argv[1:] if argv is None else argv);normalized=[];i=0
while i<len(raw):
value=raw[i]
if value=='--no-save-checkpoint':normalized+=['--save_final_checkpoint','false']
elif value=='--preflight-only':normalized+=['--preflight_only','true']
elif value=='--device':
raise ValueError('Use HF --use_cpu for CPU diagnostics; the supported training configuration is one CUDA device')
else:
name,separator,parameter=value.partition('=');name=ALIASES.get(name,name)
if name=='--task_name':
if separator:value=name+'='+parameter.upper()
else:
normalized+=[name,raw[i+1].upper()];i+=2;continue
else:value=name+(separator+parameter if separator else '')
normalized.append(value)
i+=1
if forced_method:normalized+=['--trainer',forced_method]
if not any(v.split('=')[0]=='--output_dir' for v in normalized):
normalized+=['--output_dir',str(paths()['results']/('mezo_style_'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')))]
args=HfArgumentParser(OurArguments).parse_args_into_dataclasses(normalized)[0]
if args.trainer not in ('fix','adjust','node'):raise ValueError('Use --trainer fix, adjust or node')
if args.node_update not in ('original','local_curvature','history_free') or (args.trainer!='node' and args.node_update!='original'):
raise ValueError('Use --trainer node --node_update original, local_curvature or history_free')
if args.trainer=='node':
import math
if not math.isfinite(args.node_epsilon) or args.node_epsilon<=0:
raise ValueError('Node requires a positive finite epsilon')
if not all(math.isfinite(x) and x>0 for x in (args.basis_lr,args.basis_radius)):
raise ValueError('Basis learning rate and radius must be positive finite')
if not any(v.split('=')[0]=='--learning_rate' for v in normalized):args.learning_rate=1.5e-6 if args.trainer=='node' else 1e-6
if any(v.split('=')[0]=='--lr_scheduler_type' for v in normalized):
requested=args.lr_scheduler_type.value
if requested not in ('constant','cosine') or args.zo_schedule not in (None,requested):raise ValueError('Use one consistent constant/cosine schedule')
args.zo_schedule=requested
args.zo_schedule=args.zo_schedule or ('cosine' if args.trainer=='node' else 'constant')
from transformers.trainer_utils import SchedulerType
args.lr_scheduler_type=SchedulerType(args.zo_schedule)
args.lr_min=args.lr_min if args.lr_min is not None else args.learning_rate*.1
args.refresh_every=args.refresh_every or (128 if args.trainer=='node' else 256)
args.train_set_seed=args.seed if args.train_set_seed is None else args.train_set_seed
args.overwrite_output_dir=True
if args.data_protocol not in ('legacy','mezo') or args.task_name not in ('SST2','DROP'):raise ValueError('Unknown protocol or task')
if args.dataloader_drop_last is None:args.dataloader_drop_last=args.data_protocol=='legacy'
if args.action not in ('train','evaluate','generate') or args.zo_schedule not in ('constant','cosine'):raise ValueError('Unknown action or schedule')
counts=[args.num_train,args.num_dev,args.num_eval,args.per_device_train_batch_size,args.per_device_eval_batch_size,args.calibration_samples,args.refresh_every,args.eval_main_forwards,args.node_queries]
if min(counts)<=0 or args.num_train<args.per_device_train_batch_size or args.main_forward_budget<3 or args.learning_rate<=0 or args.zo_eps<=0:raise ValueError('Invalid sample counts, budget or learning rate')
if args.gradient_accumulation_steps!=1 or args.rank!=1 or args.q!=1 or args.weight_decay!=0 or args.dtype!='float32' or args.fp16 or args.bf16:raise ValueError('Audited variant: rank=q=1, FP32, no weight decay/gradient accumulation')
unsupported=[n for n in ('prefix_tuning','lora','head_tuning','linear_probing','non_diff','untie_emb','save_on_interrupt','gradient_checkpointing','load_float16','load_bfloat16','load_int8','fp16_full_eval','bf16_full_eval','load_best_model_at_end') if getattr(args,n,False)]
if unsupported or args.world_size!=1 or args.dataloader_num_workers!=0 or (args.data_protocol=='legacy' and not args.dataloader_drop_last) or args.remove_unused_columns:raise ValueError(f'Unsupported mode: {unsupported}; use the documented single-device deterministic configuration')
if str(args.optim) not in ('sgd','OptimizerNames.SGD') or args.resume_from_checkpoint:raise ValueError('This variant uses SGD and supports inference checkpoints, not training resume')
if not args.no_auto_device:raise ValueError('Use the default single-device loader (--no_auto_device true)')
if any(v.split('=')[0]=='--max_grad_norm' for v in normalized) and args.max_grad_norm!=0:raise ValueError('Gradient clipping is not part of the audited zeroth-order update')
args.max_grad_norm=0.
if args.num_train_sets is not None:raise ValueError('Run one training seed per output directory')
# MeZO SST2 uses two option likelihoods; DROP uses gold-answer teacher forcing.
args.train_as_classification=args.task_name=='SST2';args.only_train_option=True
if args.checkpoint:
if args.action=='train':raise ValueError('--checkpoint is for inference, not resume')
if not Path(args.checkpoint).is_dir():raise ValueError('New entry expects a merged HF model directory; old .pt checkpoints are unsupported by this entry')
args.model_name=args.checkpoint
return args
class Framework(MeZOFramework):
def load_model(self):
model,tokenizer=super().load_model()
model.to(self.args.device).eval();model.config.use_cache=False;tokenizer.padding_side='left'
if self.args.load_float16 or self.args.load_bfloat16 or self.args.load_int8:raise ValueError('Only FP32 is audited')
return model,tokenizer
def train(self,train_samples,eval_samples):
if self.args.data_protocol=='mezo':
# Reuse the actual author's training-data conversion, nested collator,
# option-loss wrapper and Trainer construction from Framework.train.
return super().train(train_samples,eval_samples)
groups=self.legacy_groups
self.trainer=OurTrainer(model=self.model,args=self.args,tokenizer=self.tokenizer,
train_dataset=HFDataset(groups['train']),eval_dataset=HFDataset(groups['development']),data_collator=LegacyCollator(self.tokenizer))
self.trainer.train()
@torch.no_grad()
def validation_loss(self,samples):
if self.args.data_protocol=='legacy':return self.trainer.evaluate_dataset(HFDataset(self.legacy_groups['validation']))
previous=self.model.forward
self.model.forward=forward_wrap_with_option_len.__get__(self.model,type(self.model))
try:return self.trainer.evaluate_dataset(HFDataset(convert_samples(self.task,samples,self.tokenizer,self.args)))
finally:self.model.forward=previous
def main(argv=None,forced_method=None):
args=parse_args(argv,forced_method);storage=paths()['results'].resolve();out=Path(args.output_dir).resolve()
if not out.is_relative_to(storage):raise ValueError(f'Output must be under {storage}')
out.mkdir(parents=True,exist_ok=False);args.output_dir=str(out)
identifier=args.model_name;args.model_name=str(model_path(identifier));set_seed(args.seed)
torch.set_num_threads(4);torch.backends.cuda.matmul.allow_tf32=False;torch.backends.cudnn.allow_tf32=False
save(out/'hyperparameters.json',json.loads(json.dumps(args.to_dict(),default=str)))
save(out/'environment.json',dict(python=sys.version,executable=sys.executable,versions={name:importlib.metadata.version(name) for name in ('torch','transformers','datasets','huggingface-hub','numpy')}))
save(out/'protocol.json',dict(data_protocol=args.data_protocol,model_identifier=identifier,entry='MeZO Framework + structured OurTrainer',
algorithm_variant='history_free_coverage_gradient_v1' if args.node_update=='history_free' else ('local_curvature_gradient_v1' if args.node_update=='local_curvature' else {'fix':'fix', 'adjust':'adjust_single_probe_v1', 'node':'node_unconditional_refresh_control_v1'}[args.trainer]),
coverage_objective='Current-batch ||G_l d_l||^2; shared Gaussian response, one joint node probe, all untied Linear bases' if args.node_update=='history_free' else None,
coverage_update_order='Old-basis SGD followed by normalize(d+rho*gradient); no EMA or gate' if args.node_update=='history_free' else None,
curvature_interpretation='Three-point local Hessian; no certified upper-bound guarantee' if args.node_update=='local_curvature' else None,
selection_sampling='Three independent training-subset draws; training retains HF RandomSampler' if args.node_update=='local_curvature' else None,
inherited_mezo_commit=json.loads((ROOT/'upstream.lock.json').read_text())['mezo']['commit'],
batch_order='HF RandomSampler (MeZO author default)' if args.data_protocol=='mezo' else 'Independent PCG sampler (legacy)',dataloader_drop_last=args.dataloader_drop_last,query_unit='One model forward on the collated batch; native SST2 has two candidate rows per example',
parameterization='direct_weights_inplace_v2', optimizer='SGD, no momentum, no clipping',checkpoint='Standard HF weights for inference; resume unsupported',
cache_reuse='Do not reuse results across protocol/data hashes'))
save(out/'checkpoint_protocol.json',dict(select_best=args.select_best_checkpoint,
criterion='minimum development loss at post-update evaluation points',
ties='retain earlier checkpoint', final_evaluation='reload development-best weights' if args.select_best_checkpoint else 'final iterate',
resume_supported=False))
files=list(Path(__file__).parent.glob('*.py'))
save(out/'source_manifest.json',{str(f.relative_to(ROOT)):hashlib.sha256(f.read_bytes()).hexdigest() for f in files})
print(f'Output: {out}',flush=True)
with (out/'run.log').open('w') as stream,Tee.redirect(stream):
framework=None
try:
task=get_task(args.task_name);framework=Framework(args,task)
if args.action=='generate':
if not args.prompt:raise ValueError('--prompt is required')
text=framework.forward(framework.tokenizer.encode(args.prompt),generation=True)
save(out/'generation.json',{'text':text});return
if args.data_protocol=='legacy':
groups=legacy_rows(args,framework.tokenizer);framework.legacy_groups=groups
for split,rows in groups.items():save(out/'data'/f'{split}.json',rows)
train=[task.samples['train'][r['source_index']] for r in groups['train']]
dev=[task.samples['train'][r['source_index']] for r in groups['development']]
valid=[task.samples['valid'][r['source_index']] for r in groups['validation']]
else:
sampled=task.sample_train_sets(num_train=args.num_train,num_dev=args.num_dev,num_eval=args.num_eval,seed=args.train_set_seed)[0]
train,dev=sampled[:-args.num_dev],sampled[-args.num_dev:]
valid=task.sample_subset(data_split='valid',seed=args.train_set_seed,num=args.num_eval)
for split,rows in [('train',train),('development',dev),('validation',valid)]:save(out/'data'/f'{split}.json',[asdict(r) for r in rows])
hashes={p.stem:hashlib.sha256(p.read_bytes()).hexdigest() for p in (out/'data').glob('*.json')}
save(out/'data_manifest.json',dict(protocol=args.data_protocol,sha256=hashes,counts={'train':len(train),'development':len(dev),'validation':len(valid)}))
if args.action=='train':
framework.train(train,dev)
if args.preflight_only:return
framework.trainer.progress('final_validation')
validation=framework.validation_loss(valid)
summary=json.loads((out/'summary.json').read_text());summary['validation']=validation;summary['counts']=framework.trainer.counts;save(out/'summary.json',summary)
# Refresh the ledger after final validation loss (evaluation only).
ledger=json.loads((out/'query_ledger.json').read_text());ledger['counts']=framework.trainer.counts;save(out/'query_ledger.json',ledger)
else:
# Standard merged HF checkpoint: evaluate without installing new bases.
from transformers import DataCollatorForTokenClassification
if args.data_protocol=='legacy':
training=HFDataset(groups['train']);development=HFDataset(groups['development']);collator=LegacyCollator(framework.tokenizer)
else:
training=HFDataset(convert_samples(task,train,framework.tokenizer,args));development=HFDataset(convert_samples(task,dev,framework.tokenizer,args))
collator=DataCollatorWithPaddingAndNesting(framework.tokenizer,pad_to_multiple_of=8) if args.train_as_classification else DataCollatorForTokenClassification(framework.tokenizer,pad_to_multiple_of=8)
framework.model.original_forward=framework.model.forward
framework.trainer=OurTrainer(model=framework.model,args=args,tokenizer=framework.tokenizer,train_dataset=training,eval_dataset=development,data_collator=collator)
validation=framework.validation_loss(valid);save(out/'evaluation.json',validation)
if not args.no_eval:
if args.data_protocol=='mezo':
# The original author's prediction templates/metric implementation.
calls=[0]
framework.trainer.progress('prediction_evaluation')
def count_forward(*unused):
calls[0]+=1;framework.trainer.counts['evaluation']+=1
if calls[0]%20==0:framework.trainer.progress('prediction_evaluation')
handle=framework.model.register_forward_pre_hook(count_forward)
try:metrics=framework.evaluate([],valid)
finally:handle.remove()
save(out/'result.json',{'metrics':metrics,'metric_implementation':'MeZO Framework.evaluate / metrics.py','prediction_model_forwards':calls[0]})
if (out/'query_ledger.json').exists():
ledger=json.loads((out/'query_ledger.json').read_text());ledger['counts']=framework.trainer.counts;ledger['prediction_forwards']=calls[0];save(out/'query_ledger.json',ledger)
else:save(out/'result.json',{'metrics':validation,'metric_implementation':'Preserved legacy batched readout','prediction_model_forwards':0})
if hasattr(framework,'trainer'):
if (out/'summary.json').exists():
summary=json.loads((out/'summary.json').read_text())
summary['counts']=framework.trainer.counts;save(out/'summary.json',summary)
framework.trainer.progress('complete')
except BaseException:
import traceback
save(out/'failure.json',{'traceback':traceback.format_exc()});raise
if __name__=='__main__':main()
+425
View File
@@ -0,0 +1,425 @@
from .templates import *
from .utils import temp_seed
import json
import os
from .assets import load_dataset
from dataclasses import dataclass
from typing import List, Union
import string
import random
import datasets
import sys
import numpy as np
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
def get_task(task_name):
aa = task_name.split("__")
if len(aa) == 2:
task_group, subtask = aa
else:
task_group = aa[0]
subtask = None
class_ = getattr(sys.modules[__name__], f"{task_group}Dataset")
instance = class_(subtask)
return instance
@dataclass
class Sample:
id: int = None
data: dict = None
correct_candidate: Union[str, List[str]] = None
candidates: List[str] = None
class Dataset:
mixed_set = False
train_sep = "\n\n"
generation = False # whether this is a generation task
def __init__(self, subtask=None, **kwargs) -> None:
self.subtask = subtask
def get_task_name(self):
return self.subtask
def load_dataset():
raise NotImplementedError
def get_template(self, template_version=0):
templates = {0: Template}
return templates[template_version]
def build_sample(self, example):
return
def sample_train_sets(self, num_train=32, num_dev=None, num_eval=None, num_train_sets=None, seed=None):
if seed is not None:
# one train/demo set using the designated seed
seeds = [seed]
elif num_train_sets is not None:
# num_train_sets train/demo sets
seeds = list(range(num_train_sets))
else:
# one train/demo set per evaluation sample
assert num_dev is None # not supported
len_valid_samples = len(self.samples["valid"]) if num_eval is None else num_eval
with temp_seed(0):
seeds = np.random.randint(0, 10000, len_valid_samples)
train_samples = []
for i, set_seed in enumerate(seeds):
if self.mixed_set:
raise NotImplementedError
train_samples.append(self.sample_subset(data_split="valid", seed=set_seed, num=num_train, exclude=i))
else:
if num_dev is not None:
train_samples.append(self.sample_subset(data_split="train", seed=set_seed, num=num_train+num_dev)) # dev set is included at the end of train set
if num_train + num_dev > len(self.samples["train"]):
logger.warn("num_train + num_dev > available training examples")
else:
train_samples.append(self.sample_subset(data_split="train", seed=set_seed, num=num_train))
if num_dev is not None:
logger.info(f"Sample train set {len(train_samples[-1])}/{len(self.samples['train'])}")
logger.info(f"... including dev set {num_dev} samples")
return train_samples
def sample_subset(self, data_split="train", seed=0, num=100, exclude=None):
with temp_seed(seed):
samples = self.samples[data_split]
lens = len(samples)
index = np.random.permutation(lens).tolist()[:num if exclude is None else num+1]
if exclude is not None and exclude in index:
index.remove(exclude)
else:
index = index[:num]
return [samples[i] for i in index]
@property
def valid_samples(self):
return self.samples["valid"]
class SST2Dataset(Dataset):
train_sep = "\n\n"
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset('glue', 'sst2')
train_d = d["train"]
validation_d = d["validation"]
train_samples = [self.build_sample(example) for example in train_d]
valid_samples = [self.build_sample(example) for example in validation_d]
self.samples = {"train": train_samples, "valid": valid_samples}
# for generative tasks, candidates are []
def build_sample(self, example):
label = int(example["label"])
return Sample(id=example["idx"], data=example, correct_candidate=label, candidates=[0, 1])
def get_template(self, template_version=0):
return {0: SST2Template}[template_version]()
class CopaDataset(Dataset):
train_sep = "\n\n"
mixed_set = False
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
train_examples = load_dataset('super_glue', "copa")["train"]
valid_examples = load_dataset('super_glue', "copa")["validation"]
train_samples = [self.build_sample(example) for example in train_examples]
valid_samples = [self.build_sample(example) for example in valid_examples]
self.samples = {"train": train_samples, "valid": valid_samples}
# for generative tasks, candidates are []
def build_sample(self, example):
sample = \
Sample(
id=example["idx"],
data=example,
candidates=[example["choice1"], example["choice2"]],
correct_candidate=example[f"choice{example['label'] + 1}"],
)
return sample
def get_template(self, template_version=0):
return {0: CopaTemplate}[template_version]()
class BoolQDataset(Dataset):
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset("boolq")
train_set = d["train"]
valid_set = d["validation"]
train_samples = [self.build_sample(example) for example in train_set]
valid_samples = [self.build_sample(example) for example in valid_set]
self.samples = {"train": train_samples, "valid": valid_samples}
def build_sample(self, example):
sample = \
Sample(
data=example,
candidates=["Yes", "No"],
correct_candidate="Yes" if example["answer"] else "No",
)
return sample
def get_template(self, template_version=2):
return {0: BoolQTemplate, 1: BoolQTemplateV2, 2: BoolQTemplateV3}[template_version]()
class MultiRCDataset(Dataset):
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset("super_glue", "multirc")
train_set = d["train"]
valid_set = d["validation"]
train_samples = [self.build_sample(example) for example in train_set]
valid_samples = [self.build_sample(example) for example in valid_set]
self.samples = {"train": train_samples, "valid": valid_samples}
def build_sample(self, example):
sample = \
Sample(
data=example,
candidates=[0, 1],
correct_candidate=example['label']
)
return sample
def get_template(self, template_version=0):
return {0: MultiRCTemplate}[template_version]()
class CBDataset(Dataset):
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset("super_glue", "cb")
train_set = d["train"]
valid_set = d["validation"]
train_samples = [self.build_sample(example) for example in train_set]
valid_samples = [self.build_sample(example) for example in valid_set]
self.samples = {"train": train_samples, "valid": valid_samples}
def build_sample(self, example):
sample = \
Sample(
data=example,
candidates=[0, 1, 2],
correct_candidate=example['label']
)
return sample
def get_template(self, template_version=0):
return {0: CBTemplate}[template_version]()
class WICDataset(Dataset):
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset("super_glue", "wic")
train_set = d["train"]
valid_set = d["validation"]
train_samples = [self.build_sample(example) for example in train_set]
valid_samples = [self.build_sample(example) for example in valid_set]
self.samples = {"train": train_samples, "valid": valid_samples}
def build_sample(self, example):
sample = \
Sample(
data=example,
candidates=[0, 1],
correct_candidate=example['label']
)
return sample
def get_template(self, template_version=0):
return {0: WICTemplate}[template_version]()
class WSCDataset(Dataset):
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset("super_glue", "wsc.fixed")
train_set = d["train"]
valid_set = d["validation"]
train_samples = [self.build_sample(example) for example in train_set]
valid_samples = [self.build_sample(example) for example in valid_set]
self.samples = {"train": train_samples, "valid": valid_samples}
def build_sample(self, example):
sample = \
Sample(
data=example,
candidates=[0, 1],
correct_candidate=example['label']
)
return sample
def get_template(self, template_version=0):
return {0: WSCTemplate}[template_version]()
class ReCoRDDataset(Dataset):
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset("super_glue", "record")
train_set = d["train"]
valid_set = d["validation"]
train_samples = [self.build_sample(example) for example in train_set]
valid_samples = [self.build_sample(example) for example in valid_set]
self.samples = {"train": train_samples, "valid": valid_samples}
def build_sample(self, example):
sample = \
Sample(
data=example,
candidates=example['entities'],
correct_candidate=example['answers']
)
return sample
def get_template(self, template_version=0):
return {0: ReCoRDTemplateGPT3}[template_version]()
class RTEDataset(Dataset):
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset("super_glue", "rte")
train_set = d["train"]
valid_set = d["validation"]
train_samples = [self.build_sample(example) for example in train_set]
valid_samples = [self.build_sample(example) for example in valid_set]
self.samples = {"train": train_samples, "valid": valid_samples}
def build_sample(self, example):
sample = \
Sample(
data=example,
candidates=[0, 1],
correct_candidate=example['label']
)
return sample
def get_template(self, template_version=0):
return {0: RTETemplate}[template_version]()
class SQuADDataset(Dataset):
metric_name = "f1"
generation = True
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset()
def load_dataset(self):
dataset = load_dataset("squad")
train_examples = dataset["train"]
valid_examples = dataset["validation"]
train_samples = [self.build_sample(example, idx) for idx, example in enumerate(train_examples)]
valid_samples = [self.build_sample(example, idx) for idx, example in enumerate(valid_examples)]
self.samples = {"train": train_samples, "valid": valid_samples}
# for generative tasks, candidates are []
def build_sample(self, example, idx):
answers = example['answers']['text']
assert len(answers) > 0
return Sample(
id=idx,
data={
"title": example['title'],
"context": example['context'],
"question": example['question'],
"answers": answers
},
candidates=None,
correct_candidate=answers
)
def get_template(self, template_version=0):
return {0: SQuADv2Template}[template_version]()
class DROPDataset(Dataset):
metric_name = "f1"
generation = True
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset()
def load_dataset(self):
dataset = load_dataset("drop")
train_examples = dataset["train"]
valid_examples = dataset["validation"]
train_samples = [self.build_sample(example, idx) for idx, example in enumerate(train_examples)]
valid_samples = [self.build_sample(example, idx) for idx, example in enumerate(valid_examples)]
self.samples = {"train": train_samples, "valid": valid_samples}
# for generative tasks, candidates are []
def build_sample(self, example, idx):
answers = example['answers_spans']['spans']
assert len(answers) > 0
return Sample(
id=idx,
data={
"context": example['passage'],
"question": example['question'],
"answers": answers
},
candidates=None,
correct_candidate=answers
)
def get_template(self, template_version=0):
return {0: DROPTemplate}[template_version]()
+379
View File
@@ -0,0 +1,379 @@
class Template:
def encode(self, sample):
"""
Return prompted version of the example (without the answer/candidate)
"""
raise NotImplementedError
def verbalize(self, sample, candidate):
"""
Return the prompted version of the example (with the answer/candidate)
"""
return candidate
def encode_sfc(self, sample):
"""
Same as encode, but for SFC (calibration) -- this usually means the input is not included
"""
return "<mask>"
def verbalize_sfc(self, sample, candidate):
"""
Same as verbalize, but for SFC (calibration) -- this usually means the input is not included
"""
return candidate
class SST2Template(Template):
verbalizer = {0: "terrible", 1: "great"}
def encode(self, sample):
text = sample.data["sentence"].strip()
return f"{text} It was"
def verbalize(self, sample, candidate):
text = sample.data["sentence"].strip()
return f"{text} It was {self.verbalizer[candidate]}"
def encode_sfc(self, sample):
return f" It was"
def verbalize_sfc(self, sample, candidate):
return f" It was {self.verbalizer[candidate]}"
class CopaTemplate(Template):
capitalization: str = "correct"
effect_conj: str = " so "
cause_conj: str = " because "
def get_conjucture(self, sample):
if sample.data["question"] == "effect":
conjunction = self.effect_conj
elif sample.data["question"] == "cause":
conjunction = self.cause_conj
else:
raise NotImplementedError
return conjunction
def get_prompt(self, sample):
premise = sample.data["premise"].rstrip()
if premise.endswith("."): # TODO Add other scripts with different punctuation
premise = premise[:-1]
conjunction = self.get_conjucture(sample)
prompt = premise + conjunction
if self.capitalization == "upper":
prompt = prompt.upper()
elif self.capitalization == "lower":
prompt = prompt.lower()
return prompt
def encode(self, sample):
prompt = self.get_prompt(sample)
return prompt
def capitalize(self, c):
if self.capitalization == "correct":
words = c.split(" ")
if words[0] != "I":
words[0] = words[0].lower()
return " ".join(words)
elif self.capitalization == "bug":
return c
elif self.capitalization == "upper":
return c.upper()
elif self.capitalization == "lower":
return c.lower()
else:
raise NotImplementedError
def verbalize(self, sample, candidate):
prompt = self.get_prompt(sample)
return prompt + self.capitalize(candidate)
def encode_sfc(self, sample):
conjunction = self.get_conjucture(sample)
return conjunction.strip()
def verbalize_sfc(self, sample, candidate):
conjunction = self.get_conjucture(sample)
sfc_prompt = conjunction.strip() + " " + self.capitalize(candidate)
return sfc_prompt
class BoolQTemplate(Template):
def encode(self, sample):
passage = sample.data["passage"]
question = sample.data["question"]
if not question.endswith("?"):
question = question + "?"
question = question[0].upper() + question[1:]
return f"{passage} {question}"
def verbalize(self, sample, candidate):
passage = sample.data["passage"]
question = sample.data["question"]
if not question.endswith("?"):
question = question + "?"
question = question[0].upper() + question[1:]
return f"{passage} {question} {candidate}"
def encode_sfc(self, sample):
return ""
def verbalize_sfc(self, sample, candidate):
return candidate
class BoolQTemplateV2(Template):
def encode(self, sample):
passage = sample.data["passage"]
question = sample.data["question"]
if not question.endswith("?"):
question = question + "?"
question = question[0].upper() + question[1:]
return f"{passage} {question}\\n\\n"
def verbalize(self, sample, candidate):
passage = sample.data["passage"]
question = sample.data["question"]
if not question.endswith("?"):
question = question + "?"
question = question[0].upper() + question[1:]
return f"{passage} {question}\\n\\n{candidate}"
def encode_sfc(self, sample):
return ""
def verbalize_sfc(self, sample, candidate):
return candidate
class BoolQTemplateV3(Template):
def encode(self, sample):
passage = sample.data["passage"]
question = sample.data["question"]
if not question.endswith("?"):
question = question + "?"
question = question[0].upper() + question[1:]
return f"{passage} {question}\n"
def verbalize(self, sample, candidate):
passage = sample.data["passage"]
question = sample.data["question"]
if not question.endswith("?"):
question = question + "?"
question = question[0].upper() + question[1:]
return f"{passage} {question}\n{candidate}"
def encode_sfc(self, sample):
return ""
def verbalize_sfc(self, sample, candidate):
return candidate
class MultiRCTemplate(Template):
# From PromptSource 1
verbalizer = {0: "No", 1: "Yes"}
def encode(self, sample):
paragraph = sample.data["paragraph"]
question = sample.data["question"]
answer = sample.data["answer"]
return f"{paragraph}\nQuestion: {question}\nI found this answer \"{answer}\". Is that correct? Yes or No?\n"
def verbalize(self, sample, candidate):
paragraph = sample.data["paragraph"]
question = sample.data["question"]
answer = sample.data["answer"]
return f"{paragraph}\nQuestion: {question}\nI found this answer \"{answer}\". Is that correct? Yes or No?\n{self.verbalizer[candidate]}"
def encode_sfc(self, sample):
return f""
def verbalize_sfc(self, sample, candidate):
return f"{self.verbalizer[candidate]}"
class CBTemplate(Template):
# From PromptSource 1
verbalizer = {0: "Yes", 1: "No", 2: "Maybe"}
def encode(self, sample):
premise = sample.data["premise"]
hypothesis = sample.data["hypothesis"]
return f"Suppose {premise} Can we infer that \"{hypothesis}\"? Yes, No, or Maybe?\n"
def verbalize(self, sample, candidate):
premise = sample.data["premise"]
hypothesis = sample.data["hypothesis"]
return f"Suppose {premise} Can we infer that \"{hypothesis}\"? Yes, No, or Maybe?\n{self.verbalizer[candidate]}"
def encode_sfc(self, sample):
return f""
def verbalize_sfc(self, sample, candidate):
return f"{self.verbalizer[candidate]}"
class WICTemplate(Template):
# From PromptSource 1
verbalizer = {0: "No", 1: "Yes"}
def encode(self, sample):
sent1 = sample.data["sentence1"]
sent2 = sample.data["sentence2"]
word = sample.data["word"]
return f"Does the word \"{word}\" have the same meaning in these two sentences? Yes, No?\n{sent1}\n{sent2}\n"
def verbalize(self, sample, candidate):
sent1 = sample.data["sentence1"]
sent2 = sample.data["sentence2"]
word = sample.data["word"]
return f"Does the word \"{word}\" have the same meaning in these two sentences? Yes, No?\n{sent1}\n{sent2}\n{self.verbalizer[candidate]}"
def encode_sfc(self, sample):
return f""
def verbalize_sfc(self, sample, candidate):
return f"{self.verbalizer[candidate]}"
class WSCTemplate(Template):
# From PromptSource 1
verbalizer = {0: "No", 1: "Yes"}
def encode(self, sample):
text = sample.data['text']
span1 = sample.data['span1_text']
span2 = sample.data['span2_text']
return f"{text}\nIn the previous sentence, does the pronoun \"{span2.lower()}\" refer to {span1}? Yes or No?\n"
def verbalize(self, sample, candidate):
text = sample.data['text']
span1 = sample.data['span1_text']
span2 = sample.data['span2_text']
return f"{text}\nIn the previous sentence, does the pronoun \"{span2.lower()}\" refer to {span1}? Yes or No?\n{self.verbalizer[candidate]}"
def encode_sfc(self, sample):
return f""
def verbalize_sfc(self, sample, candidate):
return f"{self.verbalizer[candidate]}"
class ReCoRDTemplate(Template):
# From PromptSource 1 but modified
def encode(self, sample):
passage = sample.data['passage']
query = sample.data['query']
return f"{passage}\n{query}\nQuestion: what is the \"@placeholder\"\nAnswer:"
def verbalize(self, sample, candidate):
passage = sample.data['passage']
query = sample.data['query']
return f"{passage}\n{query}\nQuestion: what is the \"@placeholder\"\nAnswer: {candidate}"
def encode_sfc(self, sample):
return f"Answer:"
def verbalize_sfc(self, sample, candidate):
return f"Answer: {candidate}"
class ReCoRDTemplateGPT3(Template):
# From PromptSource 1 but modified
def encode(self, sample):
passage = sample.data['passage'].replace("@highlight\n", "- ")
return f"{passage}\n-"
def verbalize(self, sample, candidate):
passage = sample.data['passage'].replace("@highlight\n", "- ")
query = sample.data['query'].replace("@placeholder", candidate[0] if isinstance(candidate, list) else candidate)
return f"{passage}\n- {query}"
# passage = sample.data['passage']
# query = sample.data['query']
# return f"{passage}\n{query}\nQuestion: what is the \"@placeholder\"\nAnswer: {candidate}"
def encode_sfc(self, sample):
return f"-"
def verbalize_sfc(self, sample, candidate):
query = sample.data['query'].replace("@placeholder", candidate[0] if isinstance(candidate, list) else candidate)
return f"- {query}"
class RTETemplate(Template):
# From PromptSource 1
verbalizer={0: "Yes", 1: "No"}
def encode(self, sample):
premise = sample.data['premise']
hypothesis = sample.data['hypothesis']
return f"{premise}\nDoes this mean that \"{hypothesis}\" is true? Yes or No?\n"
def verbalize(self, sample, candidate):
premise = sample.data['premise']
hypothesis = sample.data['hypothesis']
return f"{premise}\nDoes this mean that \"{hypothesis}\" is true? Yes or No?\n{self.verbalizer[candidate]}"
def encode_sfc(self, sample):
return f""
def verbalize_sfc(self, sample, candidate):
return f"{self.verbalizer[candidate]}"
class SQuADv2Template(Template):
def encode(self, sample):
question = sample.data['question'].strip()
title = sample.data['title']
context = sample.data['context']
answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one
return f"Title: {title}\nContext: {context}\nQuestion: {question}\nAnswer:"
def verbalize(self, sample, candidate):
question = sample.data['question'].strip()
title = sample.data['title']
context = sample.data['context']
answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one
return f"Title: {title}\nContext: {context}\nQuestion: {question}\nAnswer: {answer}\n"
def encode_sfc(self, sample):
raise NotImplementedError
def verbalize_sfc(self, sample, candidate):
raise NotImplementedError
class DROPTemplate(Template):
def encode(self, sample):
question = sample.data['question'].strip()
# title = sample.data['title']
context = sample.data['context']
answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one
return f"Passage: {context}\nQuestion: {question}\nAnswer:"
def verbalize(self, sample, candidate):
question = sample.data['question'].strip()
# title = sample.data['title']
context = sample.data['context']
answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one
return f"Passage: {context}\nQuestion: {question}\nAnswer: {answer}\n"
def encode_sfc(self, sample):
raise NotImplementedError
def verbalize_sfc(self, sample, candidate):
raise NotImplementedError
+701
View File
@@ -0,0 +1,701 @@
"""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))
+355
View File
@@ -0,0 +1,355 @@
import json
import os
import contextlib
from typing import Optional, Union
import numpy as np
from dataclasses import dataclass, is_dataclass, asdict
import logging
import time
from torch.nn import CrossEntropyLoss
import torch.nn.functional as F
from transformers.modeling_outputs import CausalLMOutputWithPast
import torch
from transformers.utils import PaddingStrategy
from transformers import PreTrainedTokenizerBase
from transformers.data.data_collator import DataCollatorMixin
import transformers
from typing import Optional, Union, List, Dict, Any
import signal
from subprocess import call
from collections.abc import Mapping
from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union
InputDataClass = NewType("InputDataClass", Any)
from dataclasses import dataclass
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
logger = logging.getLogger(__name__)
def forward_wrap_with_option_len(self, input_ids=None, labels=None, option_len=None, num_options=None, return_dict=None, **kwargs):
"""
This is to replace the original forward function of Transformer models to enable:
(1) Partial target sequence: loss will only be calculated on part of the sequence
(2) Classification-style training: a classification loss (CE) will be calculated over several options
Input:
- input_ids, labels: same as the original forward function
- option_len: a list of int indicating the option lengths, and loss will be calculated only on the
last option_len tokens
- num_options: a list of int indicating the number of options for each example (this will be #label
words for classification tasks and #choices for multiple choice tasks), and a classification loss
will be calculated.
"""
outputs = self.original_forward(input_ids=input_ids, **kwargs)
if labels is None:
return outputs
logits = outputs.logits
loss = None
# Shift so that tokens < n predict n
shift_logits = logits[..., :-1, :].contiguous()
# Here we use input_ids (which should always = labels) bc sometimes labels are correct candidate IDs
shift_labels = torch.clone(input_ids)[..., 1:].contiguous()
shift_labels[shift_labels == self.config.pad_token_id] = -100
# Apply option len (do not calculate loss on the non-option part)
for _i, _len in enumerate(option_len):
shift_labels[_i, :-_len] = -100
# Calculate the loss
loss_fct = CrossEntropyLoss(ignore_index=-100)
if num_options is not None:
# Train as a classification tasks
log_probs = F.log_softmax(shift_logits, dim=-1)
mask = shift_labels != -100 # Option part
shift_labels[~mask] = 0 # So that it doesn't mess up with indexing
selected_log_probs = torch.gather(log_probs, dim=-1, index=shift_labels.unsqueeze(-1)).squeeze(-1) # (bsz x num_options, len)
selected_log_probs = (selected_log_probs * mask).sum(-1) / mask.sum(-1) # (bsz x num_options)
if any([x != num_options[0] for x in num_options]):
# Multi choice tasks with different number of options
loss = 0
start_id = 0
count = 0
while start_id < len(num_options):
end_id = start_id + num_options[start_id]
_logits = selected_log_probs[start_id:end_id].unsqueeze(0) # (1, num_options)
_labels = labels[start_id:end_id][0].unsqueeze(0) # (1)
loss = loss_fct(_logits, _labels) + loss
count += 1
start_id = end_id
loss = loss / count
else:
num_options = num_options[0]
selected_log_probs = selected_log_probs.view(-1, num_options) # (bsz, num_options)
labels = labels.view(-1, num_options)[:, 0] # Labels repeat so we only take the first one
loss = loss_fct(selected_log_probs, labels)
else:
loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
if not return_dict:
output = (logits,) + outputs[1:]
return (loss,) + output if loss is not None else output
return CausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
def encode_prompt(task, template, train_samples, eval_sample, tokenizer, max_length, sfc=False, icl_sfc=False, generation=False, generation_with_gold=False, max_new_tokens=None):
"""
Encode prompts for eval_sample
Input:
- task, template: task and template class
- train_samples, eval_sample: demonstrations and the actual sample
- tokenizer, max_length: tokenizer and max length
- sfc: generate prompts for calibration (surface form competition; https://arxiv.org/abs/2104.08315)
- icl_sfc: generate prompts for ICL version calibration
- generation: whether it is an generation task
- generation_with_gold: whether to include the generation-task gold answers (for training)
- max_new_tokens: max number of new tokens to generate so that we can save enough space
(only for generation tasks)
Output:
- encodings: a list of N lists of tokens. N is the number of options for classification/multiple-choice.
- option_lens: a list of N integers indicating the number of option tokens.
"""
# Demonstrations for ICL
train_prompts = [template.verbalize(sample, sample.correct_candidate).strip() for sample in train_samples]
train_prompts = task.train_sep.join(train_prompts).strip()
# sfc or icl_sfc indicates that this example is used for calibration
if sfc or icl_sfc:
encode_fn = template.encode_sfc; verbalize_fn = template.verbalize_sfc
else:
encode_fn = template.encode; verbalize_fn = template.verbalize
unverbalized_eval_prompt = encode_fn(eval_sample).strip(' ')
if not generation:
# We generate one prompt for each candidate (different classes in classification)
# or different choices in multiple-choice tasks
verbalized_eval_prompts = [verbalize_fn(eval_sample, cand).strip(' ') for cand in eval_sample.candidates]
unverbalized_eval_prompt_length = len(tokenizer.encode(unverbalized_eval_prompt))
option_lens = [(len(tokenizer.encode(verbalized_eval_prompt)) - unverbalized_eval_prompt_length) for verbalized_eval_prompt in verbalized_eval_prompts]
if sfc:
# Without demonstrations
final_prompts = verbalized_eval_prompts
else:
# With demonstrations
final_prompts = [(train_prompts + task.train_sep + eval_prompt).lstrip().strip(' ') for eval_prompt in verbalized_eval_prompts]
else:
assert not sfc and not icl_sfc, "Generation tasks do not support SFC"
if generation_with_gold:
verbalized_eval_prompts = [verbalize_fn(eval_sample, eval_sample.correct_candidate)]
unverbalized_eval_prompt_length = len(tokenizer.encode(unverbalized_eval_prompt))
option_lens = [(len(tokenizer.encode(verbalized_eval_prompt)) - unverbalized_eval_prompt_length) for verbalized_eval_prompt in verbalized_eval_prompts]
final_prompts = [(train_prompts + task.train_sep + eval_prompt).lstrip().strip(' ') for eval_prompt in verbalized_eval_prompts]
else:
option_lens = [0]
final_prompts = [(train_prompts + task.train_sep + unverbalized_eval_prompt).lstrip().strip(' ')]
# Tokenize
encodings = [tokenizer.encode(final_prompt) for final_prompt in final_prompts]
# Truncate (left truncate as demonstrations are less important)
if generation and max_new_tokens is not None:
max_length = max_length - max_new_tokens
if any([len(encoding) > max_length for encoding in encodings]):
logger.warn("Exceed max length")
if getattr(tokenizer, "add_bos_token", False):
encodings = [encoding[0:1] + encoding[1:][-(max_length-1):] for encoding in encodings]
else:
encodings = [encoding[-max_length:] for encoding in encodings]
return encodings, option_lens
@dataclass
class ICLCollator:
"""
Collator for ICL
"""
tokenizer: PreTrainedTokenizerBase
def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]:
if not isinstance(features[0], Mapping):
features = [vars(f) for f in features]
first = features[0]
batch = {}
pad_id = self.tokenizer.pad_token_id
pad_ids = {"input_ids": pad_id, "attention_mask": 0, "sfc_input_ids": pad_id, "sfc_attention_mask": 0, "labels": pad_id}
for key in first:
pp = pad_ids[key]
lens = [len(f[key]) for f in features]
max_len = max(lens)
feature = np.stack([np.pad(f[key], (0, max_len - lens[i]), "constant", constant_values=(0, pp)) for i, f in enumerate(features)])
padded_feature = torch.from_numpy(feature).long()
batch[key] = padded_feature
return batch
@dataclass
class DataCollatorWithPaddingAndNesting:
"""
Collator for training
"""
tokenizer: PreTrainedTokenizerBase
padding: Union[bool, str, PaddingStrategy] = True
max_length: Optional[int] = None
pad_to_multiple_of: Optional[int] = None
return_tensors: str = "pt"
def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]:
features = [ff for f in features for ff in f]
batch = self.tokenizer.pad(
features,
padding=self.padding,
max_length=self.max_length,
pad_to_multiple_of=self.pad_to_multiple_of,
return_tensors=self.return_tensors,
)
if "label" in batch:
batch["labels"] = batch["label"]
del batch["label"]
if "label_ids" in batch:
batch["labels"] = batch["label_ids"]
del batch["label_ids"]
return batch
@dataclass
class NondiffCollator(DataCollatorMixin):
"""
Collator for non-differentiable objectives
"""
tokenizer: PreTrainedTokenizerBase
padding: Union[bool, str, PaddingStrategy] = True
max_length: Optional[int] = None
pad_to_multiple_of: Optional[int] = None
label_pad_token_id: int = -100
return_tensors: str = "pt"
def torch_call(self, features):
import torch
label_name = "label" if "label" in features[0].keys() else "labels"
labels = [feature[label_name] for feature in features] if label_name in features[0].keys() else None
no_labels_features = [{k: v for k, v in feature.items() if k != label_name and k != "gold"} for feature in features]
batch = self.tokenizer.pad(
no_labels_features,
padding=self.padding,
max_length=self.max_length,
pad_to_multiple_of=self.pad_to_multiple_of,
return_tensors="pt",
)
if labels is None:
return batch
sequence_length = batch["input_ids"].shape[1]
padding_side = self.tokenizer.padding_side
def to_list(tensor_or_iterable):
if isinstance(tensor_or_iterable, torch.Tensor):
return tensor_or_iterable.tolist()
return list(tensor_or_iterable)
if padding_side == "right":
batch[label_name] = [
to_list(label) + [self.label_pad_token_id] * (sequence_length - len(label)) for label in labels
]
else:
batch[label_name] = [
[self.label_pad_token_id] * (sequence_length - len(label)) + to_list(label) for label in labels
]
batch[label_name] = torch.tensor(batch[label_name], dtype=torch.int64)
if "gold" in features[0]:
batch["gold"] = [feature["gold"] for feature in features]
return batch
class SIGUSR1Callback(transformers.TrainerCallback):
"""
This callback is used to save the model when a SIGUSR1 signal is received
(SLURM stop signal or a keyboard interruption signal).
"""
def __init__(self) -> None:
super().__init__()
self.signal_received = False
signal.signal(signal.SIGUSR1, self.handle_signal)
signal.signal(signal.SIGINT, self.handle_signal)
logger.warn("Handler registered")
def handle_signal(self, signum, frame):
self.signal_received = True
logger.warn("Signal received")
def on_step_end(self, args, state, control, **kwargs):
if self.signal_received:
control.should_save = True
control.should_training_stop = True
def on_train_end(self, args, state, control, **kwargs):
if self.signal_received:
exit(0)
@dataclass
class Prediction:
correct_candidate: Union[int, str]
predicted_candidate: Union[int, str]
@contextlib.contextmanager
def count_time(name):
logger.info("%s..." % name)
start_time = time.time()
try:
yield
finally:
logger.info("Done with %.2fs" % (time.time() - start_time))
@contextlib.contextmanager
def temp_seed(seed):
state = np.random.get_state()
np.random.seed(seed)
try:
yield
finally:
np.random.set_state(state)
class EnhancedJSONEncoder(json.JSONEncoder):
def default(self, o):
if is_dataclass(o):
return asdict(o)
return super().default(o)
def write_predictions_to_file(final_preds, output):
with open(output, "w") as f:
for pred in final_preds:
f.write(json.dumps(pred, cls=EnhancedJSONEncoder) + "\n")
def write_metrics_to_file(metrics, output):
json.dump(metrics, open(output, "w"), cls=EnhancedJSONEncoder, indent=4)