data_transfer / bbflow_base /docs /cmfm_failure_localization.md
hanghang214's picture
Add files using upload-large-folder tool
24599ef verified
|
Raw History Blame Contribute Delete
7.53 kB

CMFM gradient collapse: localization and fixes

Two things live here: the instrumentation that names the first non-finite operator, and the fixes to the two operators that could produce one. Nothing clips gradients, skips a sample, adds jitter, or lowers a loss weight — the fixes change the operators themselves so their backwards are bounded.

The instrumentation stays on. The fixes are argued from the code, not yet confirmed against the failing microbatch, so the replay is still worth running.

The fixes

what where change
covariance normalizer collective.py per-mode denominator std_i * std_j replaced by the single scalar trace(group_target_cov) / rank. The element-wise form was not invariant under a rotation of the collective basis (which is only defined up to one) and gave the least-observed direction a 1/var**2 weight. collective_variance_rel_floor existed only to cap that amplification and is removed.
mode gauge latent.py torch.linalg.qr replaced by ridge-regularised Cholesky-QR (latent.mode_gauge_ridge, default 1e-6), which yields the same positive-diagonal factor but bounds ‖L⁻¹‖ at 1/sqrt(ridge) instead of 1/r_ii
orthogonality pressure bbflow_module.py mode_orth_loss and the Gram diagnostics moved from the post-gauge u_global (orthonormal by construction, so ~0 always) onto the pre-gauge raw_modes_global

Two consequences worth expecting:

  • mode_orth_loss was effectively zero and is now a real term. With LAMBDA_MODE_ORTH=1.0 the latent regularizer's scale will change.
  • mode_max_cosine_abs / mode_gram_condition now describe the raw mode head, so they will no longer read as perfectly conditioned. That is the point.

What the failure looks like today

Training dies at rank=1, epoch=0, global_step=170. The forward train_loss is finite; ~600 parameter gradients are non-finite at the optimizer step, spanning the BBFlow embedder, the backbone, the condition adapters, the latent prior and the collective controller. So a finite forward objective produced a non-finite backward.

Two operators could do that while passing every forward guard:

  1. Empirical covariance normalization, collective.py. covariance_scale = (target_std ⊗ target_std).clamp_min(1e-6) with target_std = sqrt(observed target variance). The guard only rejected target_variance <= 1e-6, so a variance of, say, 1.4e-6 was accepted and d loss / d pred_trans picked up a factor of 1 / covariance_scale² ≈ 1e12. The loss itself stays small — only the gradient explodes. The collective basis comes from the q-implied physical covariance and is under no obligation to align with what 8 sampled MD frames actually do, so a retained mode having near-zero observed variance is expected, not exotic. The target_var=[...] field in the old log is the q-implied physical variance from physical_low_rank_target, not this denominator; the real suspect was never logged.
  2. Differentiable masked QR, latent.py _masked_orthonormalize_modes. QR backward scales like 1/r_ii while the guard only rejected |r_ii| / scale <= 1e-6. Worse, mode_orth_loss ran on the QR output, which is orthonormal by construction, so it reported ~0 and could not constrain a collapsing raw mode head — nothing kept the QR input away from rank deficiency.

tests/test_cmfm_failure_localization.py pins both the fixed behaviour and, with the bound disabled, the original explosion.

Step 1-3: capture the failing microbatch

These are on by default whenever latent.collective_enable=true:

flag (experiment.training.*) default effect
cmfm_numerics_log_interval 50 console cadence for the numerics line
cmfm_grad_guard true check grads after every microbatch on every rank
cmfm_capture_failure true keep a CPU copy of the current microbatch
cmfm_dump_state_dict true include pre-step weights in the dump

Every rank now appends one row per microbatch to <default_root_dir>/cmfm_numerics_rank{r}.csv, carrying the quantities that were missing before:

  • collective_observed_target_variance_min / _max (how degenerate the group really was), collective_covariance_scale_min (the scalar normalizer actually used), collective_covariance_inverse_scale_max
  • collective_target_cov_rate_absmax, collective_predicted_cov_rate_absmax, collective_covariance_error_absmax
  • prior_qr_diag_abs_min, prior_qr_rel_diag_min, prior_qr_condition_max
  • collective_update_abs, collective_update_absmax
  • batch identity: rank, epoch, global_step, microbatch, pdb_name, num_res, num_particles, t_min, t_max, num_groups

_cmfm_grad_guard runs in on_after_backward, i.e. before accumulation can smear the first bad microbatch across the window. When it trips it writes

<default_root_dir>/cmfm_failure_dumps/rank{r}_epoch{e}_step{s}_micro{m}.pt
<default_root_dir>/cmfm_failure_dumps/rank{r}_epoch{e}_step{s}_micro{m}.json

The .json is readable immediately: protein name, N, the shared t, the per-particle trajectory_idx/conformation_idx (the 8 MD frames), the group ids, the per-group collective diagnostics, and a per-parameter gradient summary. The .pt additionally holds the full corrupted batch (including trans_sc) and the pre-step weights, which is what makes the replay exact — the group sampler uses unseeded np.random.choice, so the frame indices alone cannot reproduce it.

Note: the guard raises on whichever rank fails, which will take down the other ranks. That is the same behaviour as the existing optimizer-step guard.

Step 4: attribute the component, then compare bf16 against fp32

python scripts/cmfm_replay_failure.py \
  --dump  outputs/.../cmfm_failure_dumps/rank1_epoch0_step170_micro3.pt \
  --config outputs/ckpt/.../config.yaml \
  --precision both

The script rebuilds BBFlowModule from the config, loads the pre-step weights, runs one forward on the captured microbatch, and backpropagates official, latent and collective separately with torch.autograd.grad, so the buffers never mix. For each it reports the loss, the norm and max of the finite part of the gradient, and the parameters that came back non-finite. It then repeats the whole thing in pure fp32.

Read the verdict as:

  • only collective non-finite, in both precisions → the covariance target is mathematically singular on this microbatch;
  • only collective non-finite in bf16, finite in fp32 → bf16 amplification of an already-huge but representable gradient;
  • latent non-finite → the QR/prior path, not the covariance normalizer;
  • official non-finite → the failure is not CMFM-specific at all.

Run the replay on a single GPU. Component-wise autograd.grad under DDP would fire the reducer hooks more than once.

Step 5: what still must not be done

Do not add gradient clipping, sample skipping, jitter, or a lower lambda_collective_measure. Each of those turns a reproducible failure into a silent one. The two fixes above are not of that kind: they replace an unbounded operator with a bounded one and leave the forward value unchanged wherever the input is well conditioned.

If training still dies, the dump plus the replay verdict is the evidence to act on — not a new bound.