diff --git a/docs/advanced/dtype-control.md b/docs/advanced/dtype-control.md index d828db488..3b9411582 100644 --- a/docs/advanced/dtype-control.md +++ b/docs/advanced/dtype-control.md @@ -144,6 +144,7 @@ divergence is pure forward-path difference. Watch these metrics: | `train/model_output_max_abs_diff` | Worst element. | | `train/model_output_rel_max` | The worst element relative to the rollout output's scale. | | `train/log_prob_mean_abs_diff` | The gap that actually feeds the PPO ratio. | +| `train/prev_mean_diff_over_noise_std` | Trainer-vs-rollout SDE transition mean, RMS in units of the step's noise std. | | `train/ratio_abs_minus_1` | How far the ratio sits from 1.0 in a live run. | diff --git a/docs/advanced/sde-backend.md b/docs/advanced/sde-backend.md index a11138306..ffe9cbab1 100644 --- a/docs/advanced/sde-backend.md +++ b/docs/advanced/sde-backend.md @@ -82,7 +82,44 @@ Checklist: 3. Match input dtypes between FSDP forward and the rollout engine for fp32 runs. 4. Watch `train/log_prob_mean_abs_diff` — near zero before the first optimizer step. -## 5. Pairs well with +## 5. Score centering (experimental) + +The flag, its metrics and its requirements may still change. + +Even when the kernels agree, the engine and the trainer rarely compute the exact same +transition mean, and a one-step-stale rollout under `train_diffusion_async.py` never does. +The engine samples `x' ~ N(μ_q, s²)` while the trainer scores it under `N(μ_θ, s²)`, so the +PPO gradient carries a drift term, `E[A] · ∇θ E_q[clip_A(r)]`, that pulls the actor toward +the engine instead of toward reward +([Score Centering Stabilizes Off-policy RL](https://arxiv.org/abs/2609.20807)). + +`--diffusion-score-centering` subtracts that term exactly. Flow-GRPO's per-element mean +log-prob makes `r = (p_θ/q)^(1/D)`, so under the engine `log r` is normal with mean +`−κ/(2D)` and variance `κ/D²`, where `κ = |μ_θ − μ_q|² / s²`. The expected clipped ratio +`E_q[clip_A(r)]` therefore has a closed form in `κ`, and the loss adds +`A · (center − center.detach())`: the logged loss and the clip mask are unchanged, only the +gradient moves, and it is an exact no-op when `μ_q = μ_θ`. The clip is integrated rather than +applied per sample, which is what makes the correction exact for the clipped objective. + +```bash +--diffusion-score-centering --diffusion-debug-mode +``` + +- Requires `--loss-type policy_loss`, `--diffusion-sde-type sde` with the default backend, + `0 < --diffusion-clip-range < 1`, and `--diffusion-debug-mode`: the engine returns `μ_q` + (`rollout_prev_sample_means`) and the step's noise std (`rollout_noise_std_devs`) only there. +- The PPO denominator must be the engine's own log-prob, so `--diffusion-recompute-old-log-prob` + is rejected. The loss also raises if the two sides' transition stds differ or if the stored + log-probs are not the Gaussian density of the recorded means at the sampled latents. +- `train/prev_mean_diff_over_noise_std` reports `|μ_q − μ_θ|` in units of the step's noise std + (RMS over latent elements) whenever debug tensors are present; drift grows with it. +- `train/score_center_expected_clipped_ratio` is the center itself: `1.0` means nothing to + remove, below `1` for positive advantages and above for negative ones under drift. + `train/score_center_density_abs_diff` must stay near `0` (hard limit `5e-5`). + +DiffusionNFT has no SDE log-prob, so score centering does not apply to it. + +## 6. Pairs well with - [Customization](../user-guide/customization.md) — `--diffusion-step-strategy-path` and `--sde-step-backend-path`. - [SD3 model guide](../models/sd3/sd3.md) — Flow-GRPO vs NFT recipe flags. diff --git a/docs/assets/images/krea2/async_grpo_fp8_clipfrac.png b/docs/assets/images/krea2/async_grpo_fp8_clipfrac.png new file mode 100644 index 000000000..a7c4a77ad Binary files /dev/null and b/docs/assets/images/krea2/async_grpo_fp8_clipfrac.png differ diff --git a/docs/assets/images/krea2/async_grpo_fp8_reward_mean.png b/docs/assets/images/krea2/async_grpo_fp8_reward_mean.png new file mode 100644 index 000000000..ed4529a0f Binary files /dev/null and b/docs/assets/images/krea2/async_grpo_fp8_reward_mean.png differ diff --git a/docs/assets/images/krea2/async_grpo_fp8_sc_600_eval.png b/docs/assets/images/krea2/async_grpo_fp8_sc_600_eval.png new file mode 100644 index 000000000..86ce1bc73 Binary files /dev/null and b/docs/assets/images/krea2/async_grpo_fp8_sc_600_eval.png differ diff --git a/docs/assets/images/krea2/async_grpo_fp8_sc_600_reward_mean.png b/docs/assets/images/krea2/async_grpo_fp8_sc_600_reward_mean.png new file mode 100644 index 000000000..7feea4895 Binary files /dev/null and b/docs/assets/images/krea2/async_grpo_fp8_sc_600_reward_mean.png differ diff --git a/docs/models/krea/krea2.md b/docs/models/krea/krea2.md index 497418343..fb7e06660 100644 --- a/docs/models/krea/krea2.md +++ b/docs/models/krea/krea2.md @@ -1,6 +1,6 @@ --- title: Krea-2 -description: Krea-2-Raw DiffusionNFT with OCR, synchronous on 2 or 8 colocated GPUs and asynchronous on 6 + 2 GPUs. +description: Krea-2-Raw DiffusionNFT with OCR, synchronous on 2 or 8 colocated GPUs and asynchronous on 6 + 2 GPUs; async Flow-GRPO with experimental score centering and an fp8 rollout on 4 + 4 GPUs. --- ## 1. Model introduction @@ -28,10 +28,10 @@ From `miles/backends/fsdp_utils/configs/krea2.py`: ## 4. Launch -All recipes train DiffusionNFT with the OCR reward (no reward GPU), LoRA rank 32, an EMA rollout policy and -deterministic ODE rollouts (10 steps, no CFG). +§4.1–4.3 train DiffusionNFT with the OCR reward (no reward GPU), LoRA rank 32, an EMA rollout policy and +deterministic ODE rollouts (10 steps, no CFG). §4.4 trains Flow-GRPO on the same data and LoRA with SDE rollouts. -### 4.1 Synchronous, 2 GPUs colocated +### 4.1 DiffusionNFT, synchronous, 2 GPUs colocated `scripts/run_diffusion_nft_krea2.py` — FSDP DP=2 sharing the GPUs with two sglang engines; LoRA adapters sync over CUDA IPC. 8 prompts × 8 samples per step, micro-batch 2 with gradient checkpointing. @@ -42,7 +42,7 @@ CUDA IPC. 8 prompts × 8 samples per step, micro-batch 2 with gradient checkpoin python3 scripts/run_diffusion_nft_krea2.py ``` -### 4.2 Synchronous, 8 GPUs colocated +### 4.2 DiffusionNFT, synchronous, 8 GPUs colocated `scripts/run_diffusion_nft_krea2_8gpu.py` — runs `train_diffusion.py`: FSDP DP=8 shares the GPUs with eight sglang engines, and the LoRA adapters sync over CUDA IPC. 6 prompts × 8 samples per step, micro-batch 2 with gradient @@ -54,7 +54,7 @@ checkpointing, since the engines take part of every GPU. python3 scripts/run_diffusion_nft_krea2_8gpu.py ``` -### 4.3 Asynchronous, 6 training + 2 rollout GPUs +### 4.3 DiffusionNFT, asynchronous, 6 training + 2 rollout GPUs `scripts/run_diffusion_nft_krea2_async.py` — runs `train_diffusion_async.py`: each batch is sampled under the EMA while the previous batch trains, on separate pools; LoRA adapters sync to the rollout engines over NCCL. Same batch as §4.2 @@ -68,19 +68,39 @@ the batch (3 training + 1 rollout GPUs, 3 × 8 per step), so every training GPU python3 scripts/run_diffusion_nft_krea2_async.py ``` +### 4.4 Flow-GRPO + score centering (experimental), asynchronous, 4 training + 4 rollout GPUs, fp8 rollout + +`scripts/run_diffusion_grpo_krea2_async.py` — the Flow-GRPO loss with SDE rollouts (noise level 0.7, no CFG), two SDE +steps per sample (steps 3–4 of 10), 30 prompts × 8 samples per step, PPO clip `1e-4`, no KL, no EMA, micro-batch 2, +300 rollouts. The rollout engines run the DiT in fp8 (`--sglang-quantization fp8`) and apply the LoRA adapters on the +fly (`--sglang-lora-merge-mode dynamic`), since adapters cannot be merged into fp8 weights; training stays bf16. Rollout +tensors reach the trainer through the output store (`--use-output-store`; the launcher starts the Mooncake master). + +The engines sample each batch with the previous step's actor weights, so the trainer re-scores transitions drawn around +a mean it no longer owns, and the fp8 engine moves that mean further. The experimental `--diffusion-score-centering` (with +`--diffusion-debug-mode`) removes the drift this puts into the PPO gradient, see +[SDE Step Backend §5 (experimental)](../../advanced/sde-backend.md#5-score-centering-experimental). `--no-score-centering` runs the plain +one-step-async baseline with everything else unchanged. + +**Status:** [📈 V — Verified](../../user-guide/recipe-verification.md#v), see §5.3 and §5.4. + +```bash +python3 scripts/run_diffusion_grpo_krea2_async.py +``` + ## 5. Reference results -Both runs use the default seed (1234) and 100 rollouts. `eval/ocr_test` is the held-out OCR accuracy over 1018 prompts -at 52 denoising steps, measured after the last rollout. +§5.1 and §5.2 use the default seed (1234) and 100 rollouts. `eval/ocr_test` is the held-out OCR accuracy over 1018 +prompts at 52 denoising steps, measured after the last rollout. -### 5.1 Synchronous, 8 GPUs colocated +### 5.1 DiffusionNFT, synchronous, 8 GPUs colocated The OCR reward (`rollout/reward/raw_mean`) rises from ~0.28 (mean of the first 10 rollouts) to ~0.94 (mean of the last 10), at ~94 s per rollout; `eval/ocr_test` ends at 0.923: ![Krea-2 8-GPU sync DiffusionNFT OCR reward mean](../../assets/images/krea2/sync8_ocr_reward_mean.png) -### 5.2 Asynchronous, 6 training + 2 rollout GPUs +### 5.2 DiffusionNFT, asynchronous, 6 training + 2 rollout GPUs The OCR reward rises from ~0.29 to ~0.88, at ~79 s per rollout; `eval/ocr_test` ends at 0.875: @@ -89,6 +109,35 @@ The OCR reward rises from ~0.29 to ~0.88, at ~79 s per rollout; `eval/ocr_test` NFT varies a lot from seed to seed. Over seeds 1234, 4321 and 2026, the mean OCR reward of the last 10 rollouts is 0.942, 0.905 and 0.907 for §5.1 and 0.885, 0.827 and 0.940 for §5.2. +### 5.3 Flow-GRPO, asynchronous, with and without score centering (experimental) + +The §4.4 recipe as is and with `--no-score-centering`, two seeds each. Seed 1 uses the defaults +(`--seed 1234 --rollout-seed 42`) and was resumed once from its rollout-200 checkpoint; seed 2 adds +`--extra-args "--seed 2026 --rollout-seed 2026"`. These runs predate the switch to the output store and used the +§5.4 eval; neither changes training. + +The fp8 engine puts the trainer-vs-rollout log-prob gap (`train/log_prob_mean_abs_diff`) at ~3e-5, about four times +the bf16 gap and a third of the `1e-4` clip range. Without score centering the reward rises faster at first, but both +seeds go through bursts in which most transitions are clipped, and the reward then falls to 0: seed 1 near rollout 270, +seed 2 near rollout 200 (stopped at rollout 235, when every sample scored 0). With score centering the clip fraction +stays below 1.7% and the reward keeps rising; the mean of the last 10 rollouts is 0.902 for seed 1 and 0.842 for seed 2. + +![Krea-2 async Flow-GRPO fp8 rollout OCR reward mean, score centering on and off](../../assets/images/krea2/async_grpo_fp8_reward_mean.png) + +![Krea-2 async Flow-GRPO fp8 rollout clip fraction, score centering on and off](../../assets/images/krea2/async_grpo_fp8_clipfrac.png) + +### 5.4 Flow-GRPO + score centering (experimental) over 600 rollouts + +Seed 1 with score centering, continued to `--num-rollout 600`. The OCR reward rises from ~0.23 (mean of the first 10 +rollouts) to ~0.95 (mean of the last 10), and the clip fraction falls from 0.52% on average over rollouts 200–299 to +0.15% over rollouts 500–599. `eval/ocr_fixed32` scores 32 fixed prompts from the OCR test split at 40 denoising steps +every 10 rollouts (`--eval-prompt-data ocr_fixed32 --eval-interval 10 --diffusion-eval-num-steps 40` in place of +the recipe's eval); it ends at 0.958: + +![Krea-2 async Flow-GRPO fp8 rollout with score centering, 600 rollouts, OCR reward mean](../../assets/images/krea2/async_grpo_fp8_sc_600_reward_mean.png) + +![Krea-2 async Flow-GRPO fp8 rollout with score centering, 600 rollouts, eval on 32 fixed prompts](../../assets/images/krea2/async_grpo_fp8_sc_600_eval.png) + ## 6. Pairs well with - [LoRA Training and Weight Sync](../../advanced/lora.md) — IPC and NCCL adapter sync. diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index 655440a70..b4c439e23 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -268,6 +268,7 @@ See [Dtype Control](../advanced/dtype-control.md). | `--diffusion-clip-range` | float | `1e-4` | | | `--diffusion-adv-clip-max` | float | `5.0` | Under `nft` this also sets the advantage-to-`r` slope. | | `--diffusion-recompute-old-log-prob` | flag | off | Recompute old log-probs with the trainer forward instead of trusting the rollout's. `policy_loss` only. | +| `--diffusion-score-centering` | flag | off | Experimental: cancels the train/rollout drift in the PPO gradient with a closed-form centering term ([SDE Step Backend §5](../advanced/sde-backend.md#5-score-centering-experimental)); needs `--diffusion-sde-type sde` and `--diffusion-debug-mode`, not with `--diffusion-recompute-old-log-prob`. | | `--diffusion-kl-beta` | float | `0.0` | KL to the `--ref-mode` model; under `nft` adds `kl_beta * mean((v_θ − v_ref)²)` per pair. | | `--ref-mode` | enum | – | KL reference: `none` / `lora_base` (actor with adapters disabled) / `ref` (the model from `--ref-load`). Auto: `lora_base` when KL > 0. | | `--ref-load` | str | – | HF pipeline checkpoint of an independent frozen reference model. Requires `--ref-mode ref`. | @@ -403,7 +404,7 @@ Every one takes a dotted path. | `--load-debug-rollout-data-subsample` | float | – | | | `--save-debug-train-data` | path template | – | Fills `{rollout_id}` and `{rank}`. | | `--dump-details` | dir | – | Sets the debug dump paths for post-hoc analysis. | -| `--diffusion-debug-mode` | flag | off | Engine returns per-step debug tensors; enables the `model_output_*_abs_diff` metrics. | +| `--diffusion-debug-mode` | flag | off | Engine returns per-step debug tensors; enables the `model_output_*_abs_diff` and `prev_mean_diff_over_noise_std` metrics. | `--debug-skip-optimizer-step` + `--diffusion-debug-mode` is the standard train/rollout alignment probe: frozen weights, and the metrics report exactly how far the two forwards drift. diff --git a/docs/user-guide/recipe-verification.md b/docs/user-guide/recipe-verification.md index 8ccd12878..6e571b932 100644 --- a/docs/user-guide/recipe-verification.md +++ b/docs/user-guide/recipe-verification.md @@ -56,6 +56,7 @@ count as verification. - `run_diffusion_sft_h3_t2va.py` — MiniMax H3 8-GPU t2va LoRA SFT. - `run_diffusion_grpo_sd3_hps_sglang.py` — SD3.5 Flow-GRPO + HPSv2.1. - `run_diffusion_grpo_sd3_ocr_pickscore_sglang.py` — SD3.5 Flow-GRPO + 0.8 OCR + 0.2 PickScore. + - `run_diffusion_grpo_krea2_async.py` — Krea-2 8-GPU async Flow-GRPO + score centering (experimental) + OCR, fp8 rollout. - **○ NV** - `run_diffusion_grpo_wan22_pickscore_5gpu.py` — Wan2.2 5-GPU LoRA Flow-GRPO + PickScore. diff --git a/miles/backends/fsdp_utils/loss_hub/flow_grpo.py b/miles/backends/fsdp_utils/loss_hub/flow_grpo.py index 3a17cb46a..c33a495bc 100644 --- a/miles/backends/fsdp_utils/loss_hub/flow_grpo.py +++ b/miles/backends/fsdp_utils/loss_hub/flow_grpo.py @@ -4,8 +4,9 @@ import torch +from miles.backends.fsdp_utils.loss_hub.score_centering import score_centering_term from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext, PreparedBatch -from miles.backends.fsdp_utils.metrics import record_rollout_train_abs_diff +from miles.backends.fsdp_utils.metrics import record_prev_mean_diff_over_noise_std, record_rollout_train_abs_diff from miles.utils.metric_buffer import MetricBuffer from miles.utils.train_data_utils import stack_train_pair_rollout_debug @@ -131,13 +132,14 @@ def flow_grpo_loss_formula( "sigma_max": prepared.extras["sigma_max"], } - _, log_prob_new, prev_sample_mean_new, std_dev_t_new = ctx.sde_backend.sde_step_logprob( + step_out = ctx.sde_backend.sde_step_logprob( new_pred["visual"].float(), prepared.latents["visual"].float(), prev_sample=next_latents.float(), noise_level=noise_level, **sde_step_sigmas, ) + log_prob_new = step_out.log_prob if write_old_log_prob: for pair, log_prob in zip(batch, log_prob_new, strict=True): @@ -149,6 +151,22 @@ def flow_grpo_loss_formula( unclipped = -prepared.advantage * ratio clipped = -prepared.advantage * torch.clamp(ratio, 1.0 - clip_range, 1.0 + clip_range) per_pair_loss = torch.maximum(unclipped, clipped) + + rollout_prev_mean = stack_train_pair_rollout_debug(batch, "rollout_step_prev_sample_mean") + if rollout_prev_mean is not None: + rollout_prev_mean = rollout_prev_mean.to(device=step_out.prev_mean.device, dtype=torch.float32) + if args.diffusion_score_centering: + per_pair_loss = per_pair_loss + score_centering_term( + batch, + step_out, + rollout_prev_mean, + next_latents=next_latents, + log_ratio=log_prob_new - log_prob_old, + advantage=prepared.advantage, + clip_range=clip_range, + loss_dtype=per_pair_loss.dtype, + metrics=metrics, + ) loss_sum = per_pair_loss.sum() bsz = len(batch) @@ -156,17 +174,17 @@ def flow_grpo_loss_formula( if kl_beta > 0: if ref_pred is None: raise ValueError("Flow-GRPO KL requires a reference DiT forward; set --ref-mode lora_base or ref") - _, _, prev_sample_mean_ref, _ = ctx.sde_backend.sde_step_logprob( + ref_step_out = ctx.sde_backend.sde_step_logprob( ref_pred["visual"].float(), prepared.latents["visual"].float(), prev_sample=next_latents.float(), noise_level=noise_level, **sde_step_sigmas, ) - kl_per_pair = ((prev_sample_mean_new - prev_sample_mean_ref) ** 2).mean( - dim=tuple(range(1, prev_sample_mean_new.ndim)), + kl_per_pair = ((step_out.prev_mean - ref_step_out.prev_mean) ** 2).mean( + dim=tuple(range(1, step_out.prev_mean.ndim)), keepdim=True, - ) / (2 * std_dev_t_new**2) + ) / (2 * step_out.std_dev_t**2) loss_sum = loss_sum + kl_beta * kl_per_pair.sum() kl_sum = kl_per_pair.sum() @@ -190,6 +208,9 @@ def flow_grpo_loss_formula( count=bsz, ) + if rollout_prev_mean is not None: + record_prev_mean_diff_over_noise_std(metrics, rollout_prev_mean, step_out.prev_mean, step_out.noise_std) + rollout_model_output = stack_train_pair_rollout_debug(batch, "rollout_step_model_output") if rollout_model_output is not None: record_rollout_train_abs_diff( diff --git a/miles/backends/fsdp_utils/loss_hub/score_centering.py b/miles/backends/fsdp_utils/loss_hub/score_centering.py new file mode 100644 index 000000000..2a919200c --- /dev/null +++ b/miles/backends/fsdp_utils/loss_hub/score_centering.py @@ -0,0 +1,220 @@ +"""Closed-form center of the clipped Flow-GRPO ratio under the rollout Gaussian. + +Rollout and trainer transitions are q = N(mu_q, Sigma) and p = N(mu, Sigma) with +the same fixed diagonal covariance. Flow-GRPO's per-element mean log-density +makes the PPO ratio r = (p/q)^(1/D); under q, log r is normal with mean +-kappa/(2D) and variance kappa/D^2, where kappa = |mu - mu_q|^2 / sigma^2. +E_q[clip_A(r)] therefore has a closed form, and adding A * (center - center.detach()) +to the clipped PPO loss subtracts the expected weighted score from its gradient. +Only first derivatives are implemented; scalar work is done in float64. +""" + +from __future__ import annotations + +import math +from typing import TYPE_CHECKING + +import torch + +from miles.utils.metric_buffer import MetricBuffer +from miles.utils.train_data_utils import stack_train_pair_rollout_debug + +if TYPE_CHECKING: + from miles.backends.fsdp_utils.sde_step_backend import SdeStepOutput + + +def _exp_difference(log_left: torch.Tensor, log_right: torch.Tensor) -> torch.Tensor: + """exp(log_left) - exp(log_right), keeping accuracy when the two nearly cancel.""" + left_larger = log_left >= log_right + large = torch.maximum(log_left, log_right) + small = torch.minimum(log_left, log_right) + # Both can be -inf in Gaussian tails; avoid the indeterminate inf - inf. + delta = torch.where(torch.isfinite(large), small - large, torch.zeros_like(large)) + magnitude = torch.exp(large) * (-torch.expm1(delta)) + return torch.where(left_larger, magnitude, -magnitude) + + +class _ClippedRatioCenter(torch.autograd.Function): + """E_q[clip_A(r)] with an exact d/dkappa, since autograd through sqrt(kappa) gives 0 * inf at kappa == 0.""" + + @staticmethod + def forward(ctx, kappa, advantage, dimension, clip_range): + ctx.input_dtype = kappa.dtype + kappa = kappa.to(dtype=torch.float64) + alpha = 1.0 / dimension + log_overlap = -0.5 * alpha * (1.0 - alpha) * kappa + at_zero = kappa == 0 + + # The safe branch is evaluated at 1, then replaced by the exact kappa == 0 limit. + safe_kappa = torch.where(at_zero, torch.ones_like(kappa), kappa) + sqrt_kappa = torch.sqrt(safe_kappa) + positive = torch.broadcast_to(advantage.detach().to(device=kappa.device) >= 0, kappa.shape) + log_clip = torch.where( + positive, + torch.full_like(kappa, math.log1p(clip_range)), + torch.full_like(kappa, math.log1p(-clip_range)), + ) + # Under q: log r ~ N(-alpha * kappa / 2, alpha^2 * kappa). Direct formulas avoid + # subtracting two close standardized values. + clip_z = log_clip / (alpha * sqrt_kappa) + 0.5 * sqrt_kappa + tilted_clip_z = log_clip / (alpha * sqrt_kappa) + (0.5 - alpha) * sqrt_kappa + log_cdf_below_tilted = torch.special.log_ndtr(tilted_clip_z) + log_cdf_above_tilted = torch.special.log_ndtr(-tilted_clip_z) + log_unclipped_term = log_overlap + torch.where(positive, log_cdf_below_tilted, log_cdf_above_tilted) + log_clipped_term = log_clip + torch.special.log_ndtr(torch.where(positive, -clip_z, clip_z)) + value = torch.exp(torch.logaddexp(log_unclipped_term, log_clipped_term)) + + log_pdf_over_sqrt_kappa = ( + log_overlap - 0.5 * tilted_clip_z.square() - 0.5 * math.log(2.0 * math.pi) - 0.5 * torch.log(safe_kappa) + ) + if alpha == 1.0: + log_bulk = torch.full_like(kappa, -math.inf) + else: + log_bulk = ( + log_overlap + math.log1p(-alpha) + torch.where(positive, log_cdf_below_tilted, log_cdf_above_tilted) + ) + upper_derivative = -0.5 * alpha * torch.exp(torch.logaddexp(log_bulk, log_pdf_over_sqrt_kappa)) + lower_derivative = 0.5 * alpha * _exp_difference(log_pdf_over_sqrt_kappa, log_bulk) + derivative = torch.where(positive, upper_derivative, lower_derivative) + value = torch.where(at_zero, torch.ones_like(value), value) + derivative = torch.where(at_zero, torch.full_like(derivative, -0.5 * alpha * (1.0 - alpha)), derivative) + + ctx.save_for_backward(derivative) + return value + + @staticmethod + def backward(ctx, grad_output): + (derivative,) = ctx.saved_tensors + grad_kappa = (grad_output.to(torch.float64) * derivative).to(ctx.input_dtype) + return grad_kappa, None, None, None + + +def clipped_ratio_center( + kappa: torch.Tensor, + dimension: int, + advantage: torch.Tensor, + clip_range: float, +) -> torch.Tensor: + """E_q[clip_A((p/q)^(1/D))] per batch item, differentiable in ``kappa``. + + ``kappa`` is the full squared mean displacement over the Gaussian variance (not + its per-dimension mean); ``advantage`` only contributes its detached sign, which + picks the clip side (``1 + clip_range`` for A >= 0, ``1 - clip_range`` below). + """ + return _ClippedRatioCenter.apply(kappa, advantage, dimension, clip_range) + + +def gaussian_kappa(prev_mean: torch.Tensor, rollout_prev_mean: torch.Tensor, variance: torch.Tensor) -> torch.Tensor: + """|prev_mean - rollout_prev_mean|^2 / variance per batch item; only ``prev_mean`` carries gradient.""" + delta = prev_mean.to(torch.float64) - rollout_prev_mean.detach().to(torch.float64) + return (delta.square() / variance.detach()).flatten(1).sum(1) + + +def gaussian_mean_log_ratio( + next_latents: torch.Tensor, + prev_mean: torch.Tensor, + rollout_prev_mean: torch.Tensor, + variance: torch.Tensor, +) -> torch.Tensor: + """(log p - log q) / D at ``next_latents``, computed without subtracting two large log-densities.""" + delta = prev_mean.to(torch.float64) - rollout_prev_mean.detach().to(torch.float64) + residual = next_latents.detach().to(torch.float64) - rollout_prev_mean.detach().to(torch.float64) + return ((delta * residual - 0.5 * delta.square()) / variance.detach()).flatten(1).mean(1) + + +def gaussian_score_center( + *, + prev_mean: torch.Tensor, + rollout_prev_mean: torch.Tensor, + noise_std: torch.Tensor, + rollout_noise_std: torch.Tensor, + next_latents: torch.Tensor, + log_ratio: torch.Tensor, + advantage: torch.Tensor, + clip_range: float, +) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + """Center for one micro-batch of SDE transitions, plus the diagnostics it was computed from. + + Args: + prev_mean: trainer transition mean, ``[B, ...]``, carries the gradient. + rollout_prev_mean: the engine's transition mean for the same step, same shape. + noise_std: trainer transition std, broadcastable to ``prev_mean``. + rollout_noise_std: the engine's transition std, one value per batch item. + next_latents: the latent the engine actually sampled, same shape as ``prev_mean``. + log_ratio: the loss's ``log_prob_new - log_prob_old`` per batch item. + advantage: per-item advantage; only its sign is used. + clip_range: the PPO clip range. + + Returns: + ``(center, metrics)``: the float64 ``[B]`` center and per-item diagnostic tensors. + """ + if rollout_prev_mean.shape != prev_mean.shape: + raise ValueError( + f"Rollout prev-sample means {tuple(rollout_prev_mean.shape)} are laid out unlike the trainer's " + f"{tuple(prev_mean.shape)}; score centering does not support this model family" + ) + batch_size = prev_mean.shape[0] + rollout_noise_std = rollout_noise_std.float().reshape(batch_size, *([1] * (prev_mean.ndim - 1))) + if not torch.allclose(noise_std.float(), rollout_noise_std, rtol=2e-5, atol=1e-8): + raise ValueError( + "Score centering needs the trainer and rollout SDE steps to share one transition covariance; " + "their noise stds differ (different --diffusion-noise-level or sigma schedule?)" + ) + variance = rollout_noise_std.double().square() + dimension = prev_mean[0].numel() + kappa = gaussian_kappa(prev_mean, rollout_prev_mean, variance) + center = clipped_ratio_center(kappa, dimension, advantage, clip_range) + # log_prob_old must be q's density at next_latents; no-const log-probs or misaligned + # debug tensors would otherwise center the wrong objective silently. + analytic_log_ratio = gaussian_mean_log_ratio(next_latents, prev_mean, rollout_prev_mean, variance) + density_abs_diff = (analytic_log_ratio.detach() - log_ratio.detach().double()).abs() + if not torch.isfinite(density_abs_diff).all() or density_abs_diff.max() > 5e-5: + raise ValueError( + "Rollout log-probs are not the Gaussian density of the rollout prev-sample means at the sampled " + f"latents (max |diff| {density_abs_diff.max().item():.3e}); score centering cannot use them" + ) + metrics = { + "score_center_expected_clipped_ratio": center.detach(), + "score_center_density_abs_diff": density_abs_diff, + } + return center, metrics + + +def score_centering_term( + batch: list[dict], + step_out: SdeStepOutput, + rollout_prev_mean: torch.Tensor | None, + *, + next_latents: torch.Tensor, + log_ratio: torch.Tensor, + advantage: torch.Tensor, + clip_range: float, + loss_dtype: torch.dtype, + metrics: MetricBuffer, +) -> torch.Tensor: + """Per-pair term to add to the clipped PPO loss for --diffusion-score-centering. + + It is zero-valued, so the logged loss and the clip mask are unchanged; only the gradient moves. + ``rollout_prev_mean`` is the stacked ``rollout_step_prev_sample_mean``, already on ``step_out``'s + device in float32. + """ + rollout_noise_std = stack_train_pair_rollout_debug(batch, "rollout_step_noise_std_dev") + if rollout_prev_mean is None or rollout_noise_std is None: + raise ValueError( + "--diffusion-score-centering needs the rollout's per-step prev-sample means and noise stds; " + "these rollouts carry none (run with --diffusion-debug-mode)" + ) + center, centering_metrics = gaussian_score_center( + prev_mean=step_out.prev_mean, + rollout_prev_mean=rollout_prev_mean, + noise_std=step_out.noise_std, + rollout_noise_std=rollout_noise_std.to(step_out.prev_mean.device), + next_latents=next_latents, + log_ratio=log_ratio, + advantage=advantage, + clip_range=clip_range, + ) + with torch.no_grad(): + for key, values in centering_metrics.items(): + metrics.emit_mean(key, total=values.sum(), count=len(batch)) + return advantage * (center - center.detach()).to(loss_dtype) diff --git a/miles/backends/fsdp_utils/metrics.py b/miles/backends/fsdp_utils/metrics.py index 32b419398..5de2fe4d1 100644 --- a/miles/backends/fsdp_utils/metrics.py +++ b/miles/backends/fsdp_utils/metrics.py @@ -24,6 +24,9 @@ "model_output_mean_abs_diff": MetricReduce.MEAN, "model_output_max_abs_diff": MetricReduce.MAX, "model_output_rel_max": MetricReduce.MAX, + "prev_mean_diff_over_noise_std": MetricReduce.MEAN, + "score_center_expected_clipped_ratio": MetricReduce.MEAN, + "score_center_density_abs_diff": MetricReduce.MEAN, "grad_norm": MetricReduce.REPLICATED, "nft_loss": MetricReduce.MEAN, "nft_loss_per_pair": MetricReduce.MEAN, @@ -61,6 +64,24 @@ def new_metric_buffer( return MetricBuffer(group=group, device=device, schema=schema) +def record_prev_mean_diff_over_noise_std( + metrics: MetricBuffer, + rollout_prev_mean: torch.Tensor, + prev_mean: torch.Tensor, + noise_std: torch.Tensor, +) -> None: + """Record the trainer-vs-rollout SDE transition-mean gap per pair, RMS in units of the step's noise std.""" + bsz = prev_mean.shape[0] + with torch.no_grad(): + # flattened per pair like model_output, so logging never depends on the debug layout + noise_std = noise_std.reshape(bsz, -1) + mean_diff = rollout_prev_mean.reshape(bsz, -1) - prev_mean.reshape(bsz, -1) + diff_over_std = torch.where(noise_std > 0, mean_diff / noise_std, 0.0) + metrics.emit_mean( + "prev_mean_diff_over_noise_std", total=diff_over_std.pow(2).mean(dim=1).sqrt().sum(), count=bsz + ) + + def record_rollout_train_abs_diff( metrics: MetricBuffer, prefix: str, diff --git a/miles/backends/fsdp_utils/sde_step_backend.py b/miles/backends/fsdp_utils/sde_step_backend.py index 97304f977..b7fe31b82 100644 --- a/miles/backends/fsdp_utils/sde_step_backend.py +++ b/miles/backends/fsdp_utils/sde_step_backend.py @@ -20,10 +20,25 @@ import abc import math +from typing import NamedTuple import torch +class SdeStepOutput(NamedTuple): + """One SDE step: the sampled latent, its log-prob and the transition's mean and stds. + + The first four fields keep ``sde_step_with_logprob``'s order. + """ + + prev_sample: torch.Tensor + log_prob: torch.Tensor + prev_mean: torch.Tensor + std_dev_t: torch.Tensor + # the std log_prob scored against; flow-SDE keeps it distinct from std_dev_t + noise_std: torch.Tensor + + class SdeStepBackend(abc.ABC): @abc.abstractmethod def prev_sample_mean_and_std( @@ -67,7 +82,7 @@ def sde_step_logprob( sigmas: torch.Tensor, next_sigmas: torch.Tensor, sigma_max: torch.Tensor, - ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + ) -> SdeStepOutput: model_output = model_output.float() sample = sample.float() prev_sample = prev_sample.float() @@ -80,7 +95,13 @@ def sde_step_logprob( sigma_max=sigma_max.view(view), noise_level=noise_level, ) - return prev_sample, self.log_prob(prev_sample, prev_mean, noise_std), prev_mean, std_dev_t + return SdeStepOutput( + prev_sample=prev_sample, + log_prob=self.log_prob(prev_sample, prev_mean, noise_std), + prev_mean=prev_mean, + std_dev_t=std_dev_t, + noise_std=noise_std, + ) class FlowSdeStepBackend(SdeStepBackend): diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index 698642165..a80ca1688 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -1058,6 +1058,15 @@ def add_algo_arguments(parser): "pass and reuses its training forward's log-prob (ratio == 1)." ), ) + parser.add_argument( + "--diffusion-score-centering", + action="store_true", + help=( + "Experimental. Flow-GRPO only: subtract the expected clipped-ratio score under the rollout step's " + "Gaussian from the PPO gradient, so train/rollout drift stops acting as a reward. " + "Needs --diffusion-debug-mode for the rollout's per-step means and noise stds." + ), + ) parser.add_argument( "--diffusion-kl-beta", type=float, @@ -1809,6 +1818,30 @@ def rollout_merges_lora(args) -> bool: return args.use_lora and not args.train_only and (args.lora_ipc_weight_sync or not args.colocate) +def validate_score_centering_args(args) -> None: + """Score centering closes the Gaussian integral the stock flow-SDE step and its recorded log-probs define.""" + if not args.diffusion_score_centering: + return + if args.loss_type != "policy_loss": + raise ValueError("--diffusion-score-centering is only supported for policy_loss / Flow-GRPO") + if args.diffusion_sde_type != "sde" or args.sde_step_backend_path is not None: + raise ValueError( + "--diffusion-score-centering requires --diffusion-sde-type sde with the default SDE step backend" + ) + if not args.diffusion_debug_mode: + raise ValueError( + "--diffusion-score-centering requires --diffusion-debug-mode (rollout prev-sample means and noise stds)" + ) + if args.diffusion_recompute_old_log_prob: + raise ValueError( + "--diffusion-score-centering centers against the rollout's own log-probs; drop --diffusion-recompute-old-log-prob" + ) + if not 0.0 < args.diffusion_clip_range < 1.0: + raise ValueError( + f"--diffusion-score-centering requires 0 < --diffusion-clip-range < 1, got {args.diffusion_clip_range}" + ) + + def validate_actor_lora_adapter(args) -> None: if args.lora_adapter_paths is None: return @@ -1923,6 +1956,7 @@ def miles_validate_args(args): raise ValueError(f"--update-weight-target-module has duplicates: {args.update_weight_target_module!r}") validate_reference_model_args(args) validate_actor_lora_adapter(args) + validate_score_centering_args(args) if args.wandb_log_image_interval < 1: raise ValueError(f"wandb_log_image_interval must be >= 1, got {args.wandb_log_image_interval}") diff --git a/scripts/run_diffusion_grpo_krea2_async.py b/scripts/run_diffusion_grpo_krea2_async.py new file mode 100644 index 000000000..4a7b225db --- /dev/null +++ b/scripts/run_diffusion_grpo_krea2_async.py @@ -0,0 +1,148 @@ +"""Async Krea-2-Raw Flow-GRPO with score centering (experimental) and OCR on 4 training + 4 rollout GPUs. + +Run through train_diffusion_async.py: each batch is sampled by engines holding the previous +step's actor weights while the current batch trains, and the LoRA adapters sync to the rollout +GPUs over NCCL. The engines run the DiT in fp8 and apply the adapters on the fly, since they +cannot be merged into fp8 weights; training stays bf16. The one-step-stale, fp8 rollout means +the trainer re-scores SDE transitions drawn around a mean it no longer owns; +--diffusion-score-centering removes the drift that puts into the PPO gradient (see +docs/advanced/sde-backend.md §5). Rollout tensors travel through the output store. 30 prompts +x 8 samples per step, two SDE steps per sample (steps 3-4 of 10), micro-batch 2, no gradient +checkpointing. + +Usage: + python3 scripts/run_diffusion_grpo_krea2_async.py + python3 scripts/run_diffusion_grpo_krea2_async.py --no-score-centering # plain async baseline + python3 scripts/run_diffusion_grpo_krea2_async.py --four-gpu-ci +""" + +import os +from dataclasses import dataclass + +import typer + +import miles.utils.external_utils.command_utils as U + +MODEL = "krea/Krea-2-Raw" +DATASET = "rockdu/miles-diffusion-datasets" +SUBSET = "flowgrpo_ocr" +WANDB_PROJECT = "miles-diffusion-grpo" + + +@dataclass +class ScriptArgs(U.ExecuteTrainConfig): + num_rollout: int = 300 + data_dir: str = "/root/datasets" + extra_args: str = "" + score_centering: bool = True + # CI cap: 3 training + 1 rollout GPUs with 3 prompts per step + four_gpu_ci: bool = False + + +def prepare(args: ScriptArgs) -> str: + local_dir = U.hf_download_dataset(DATASET, include=f"{SUBSET}/**", data_dir=args.data_dir) + return f"{local_dir}/{SUBSET}" + + +def execute(args: ScriptArgs, data_dir: str) -> None: + run_name = f"diffusion_grpo_krea2_ocr_async_{U.create_run_id()}" + num_train_gpus, num_rollout_gpus = (3, 1) if args.four_gpu_ci else (4, 4) + # 30 x 8 = 240 samples per step, the nearest to 32 x 8 that both 4 and 6 trainer ranks divide + num_prompts = 3 if args.four_gpu_ci else 30 + num_gpus = num_train_gpus + num_rollout_gpus + + ckpt_args = ( + f"--hf-checkpoint {MODEL} --diffusion-task t2i --save {args.output_dir}/{run_name}/ckpt --save-interval 20 " + ) + + rollout_args = ( + "--rollout-function-path miles.rollout.sglang_diffusion_rollout.generate_rollout " + f"--prompt-data {data_dir}/train.jsonl " + "--input-key input " + f"--num-rollout {args.num_rollout} " + "--num-steps-per-rollout 1 " + "--diffusion-num-steps 10 " + "--diffusion-guidance-scale 1.0 " + "--diffusion-noise-level 0.7 " + "--diffusion-sde-type sde " + "--diffusion-height 1024 " + "--diffusion-width 1024 " + "--diffusion-step-strategy-path miles.rollout.step_strategy_hub.sde_window " + "--diffusion-num-sde-steps 2 " + "--diffusion-sde-window-range 3,5 " + # score centering reads the rollout's per-step means and noise stds from the debug tensors + "--diffusion-debug-mode " + "--rollout-microgroup-size 1 " + f"--rollout-batch-size {num_prompts} --n-samples-per-prompt 8 " + ) + + eval_args = ( + "--diffusion-eval-num-steps 52 --skip-eval-before-train " + # the 1018-prompt OCR eval is slow, so it runs every 100 rollouts + f"--eval-prompt-data ocr_test {data_dir}/test.jsonl --eval-interval 100 " + ) + + grpo_args = ( + "--loss-type policy_loss " + "--advantage-estimator grpo " + "--globalize-reward-std " + "--diffusion-clip-range 1e-4 " + "--diffusion-kl-beta 0.0 " + ) + ("--diffusion-score-centering " if args.score_centering else "") + + optimizer_args = "--lr 3e-4 --adam-beta2 0.999 --weight-decay 1e-4 --clip-grad 1.0 " + + # without --colocate the adapters sync over NCCL + lora_args = "--use-lora --lora-rank 32 --lora-alpha 64 --lora-init-weights gaussian " + + wandb_args = U.get_default_wandb_args( + __file__, run_id=run_name, project=WANDB_PROJECT, wandb_log_num_images=8, wandb_log_image_interval=10 + ) + + sglang_args = ( + "--use-miles-router " + "--sglang-server-concurrency 8 " + "--sglang-lora-merge-mode dynamic " + "--sglang-quantization fp8 " + "--sglang-dit-precision bf16 " + "--sglang-vae-slicing " + "--update-weight-buffer-size 2147483648 " + # the launcher starts the Mooncake master on this port; debug mode stores every step's debug tensors, + # ~12 GB per 240-sample rollout with two rollouts in flight, beyond the 16gb default segment + "--use-output-store --output-store-mooncake-master 127.0.0.1:50070 --output-store-global-segment-size 64gb " + ) + + train_backend_args = "--train-backend fsdp --diffusion-forward-dtype bf16 --micro-batch-size 2 " + + misc_args = ( + f"--actor-num-gpus-per-node {num_train_gpus} " + f"--rollout-num-gpus {num_rollout_gpus} " + "--rollout-num-gpus-per-engine 1 " + f"--num-gpus-per-node {num_gpus} " + "--deterministic-mode " + ) + + U.execute_train( + train_args=( + f"{ckpt_args} {rollout_args} {eval_args} {grpo_args} " + f"{optimizer_args} {lora_args} --rm-type ocr {wandb_args} {sglang_args} " + f"{train_backend_args} {misc_args} {args.extra_args}" + ), + num_gpus_per_node=num_gpus, + train_script="train_diffusion_async.py", + config=args, + extra_env_vars={ + "PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True", + "HF_TOKEN": os.environ.get("HF_TOKEN", ""), + }, + ) + + +@U.dataclass_cli +def main(args: ScriptArgs) -> None: + data_dir = prepare(args) + execute(args, data_dir) + + +if __name__ == "__main__": + typer.run(main) diff --git a/tests/fast/backends/fsdp_utils/test_loss_hub_flow_grpo.py b/tests/fast/backends/fsdp_utils/test_loss_hub_flow_grpo.py new file mode 100644 index 000000000..5a4417497 --- /dev/null +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_flow_grpo.py @@ -0,0 +1,188 @@ +"""Gaussian score centering inside the production Flow-GRPO loss. + + engine: x' ~ N(mu_q, s^2) --rollout debug tensors--> trainer: r = exp(log N(x'|mu, s^2) - log_prob_old) + loss = max(-A r, -A clip(r)) + --diffusion-score-centering: loss += A * (center - center.detach()), center = E_q[clip_A(r)] + + production gradient == float64 oracle: autograd through -A * (clip(r) - center) (closed form) + logged loss == plain PPO loss (the added term is zero-valued) + clip-masked pairs --> zero gradient without centering, non-zero with it + mu_q == mu --> gradient bit-identical to plain PPO + no debug tensors / stds differ / log_prob_old is not q's density --> ValueError +""" + +from tests.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="stage-a-cpu", labels=[]) + +from types import SimpleNamespace + +import pytest +import torch + +from miles.backends.fsdp_utils.loss_hub.flow_grpo import flow_grpo_loss_formula +from miles.backends.fsdp_utils.sde_step_backend import FlowSdeStepBackend + +NOISE_LEVEL = 0.7 +CLIP_RANGE = 0.2 +VIEW = (-1, 1, 1, 1) + + +class _MetricSink: + def emit_mean(self, key, *, total, count): + pass + + def emit_max(self, key, value): + pass + + +@pytest.fixture +def transition(): + """Four 2x2 transitions whose trainer mean sits 1.2 noise stds from the rollout mean along one coordinate. + + The sampled latents are placed so the PPO ratios are (1.6, 1.0, 0.6, 1.1) under advantages + (+1, +2, -1, -2): pairs 0 and 2 are clip-masked, pairs 1 and 3 are not. + """ + backend = FlowSdeStepBackend() + args = SimpleNamespace( + diffusion_clip_range=CLIP_RANGE, + diffusion_noise_level=NOISE_LEVEL, + diffusion_kl_beta=0.0, + diffusion_score_centering=True, + ) + ctx = SimpleNamespace(args=args, sde_backend=backend, models={"dit": object()}, device=torch.device("cpu")) + latent = torch.zeros((4, 1, 2, 2), dtype=torch.float32) + sigmas = torch.tensor([0.8, 0.55, 0.8, 0.55]) + next_sigmas = torch.tensor([0.55, 0.25, 0.55, 0.25]) + sigma_max = torch.full((4,), 0.8) + sigma, sigma_next = sigmas.view(VIEW), next_sigmas.view(VIEW) + rollout_prev_mean, noise_std, std_dev_t = backend.prev_sample_mean_and_std( + torch.zeros_like(latent), latent, sigma, sigma_next, sigma_max=sigma_max.view(VIEW), noise_level=NOISE_LEVEL + ) + displacement = torch.zeros_like(latent) + displacement[:, 0, 0, 0] = 1.2 * noise_std.flatten() + pred_coefficient = (1 + std_dev_t.square() * (1 - sigma) / (2 * sigma)) * (sigma_next - sigma) + new_pred = (displacement / pred_coefficient).detach().requires_grad_(True) + target_ratio = torch.tensor([1.6, 1.0, 0.6, 1.1]) + z = torch.tensor([[0.0, 0.3, -0.7, 0.2], [0.0, -0.2, 0.1, 0.5], [0.0, 0.8, -0.4, 0.3], [0.0, -0.1, 0.4, -0.2]]) + z[:, 0] = (4 * target_ratio.log() + 0.5 * 1.2**2) / 1.2 + next_latents = rollout_prev_mean + noise_std * z.reshape_as(latent) + batch = [ + { + "rollout_debug_tensors": { + "rollout_step_prev_sample_mean": rollout_prev_mean[i].clone(), + "rollout_step_noise_std_dev": noise_std[i].flatten().clone(), + } + } + for i in range(4) + ] + prepared = SimpleNamespace( + latents={"visual": latent}, + advantage=torch.tensor([1.0, 2.0, -1.0, -2.0]), + component_name="dit", + extras={ + "next_latents": next_latents, + "sigmas": sigmas, + "next_sigmas": next_sigmas, + "sigma_max": sigma_max, + "log_prob_old": backend.log_prob(next_latents, rollout_prev_mean, noise_std).detach(), + }, + ) + return SimpleNamespace( + ctx=ctx, + batch=batch, + prepared=prepared, + new_pred=new_pred, + rollout_prev_mean=rollout_prev_mean, + noise_std=noise_std, + ) + + +def _loss(t, new_pred): + return flow_grpo_loss_formula( + t.ctx, t.batch, t.prepared, new_pred={"visual": new_pred}, old_pred=None, ref_pred=None, metrics=_MetricSink() + ) + + +def _grad(t, new_pred, *, score_centering): + t.ctx.args.diffusion_score_centering = score_centering + pred = new_pred.detach().clone().requires_grad_(True) + loss = _loss(t, pred) + (grad,) = torch.autograd.grad(loss, pred) + return loss.item(), grad + + +def test_gradient_matches_the_closed_form_oracle_and_the_loss_value_is_unchanged(transition): + """A sign, side, scale or detach mistake in the correction term, or a changed logged loss, fails here.""" + t = transition + production_loss, production_grad = _grad(t, t.new_pred, score_centering=True) + + # Independent float64 objective -A * (clip(r) - center), with ordinary autograd + # through the closed-form lognormal expectation (every kappa is strictly > 0). + oracle_pred = t.new_pred.detach().clone().requires_grad_(True) + prev_mean, _, _ = t.ctx.sde_backend.prev_sample_mean_and_std( + oracle_pred, + t.prepared.latents["visual"], + t.prepared.extras["sigmas"].view(VIEW), + t.prepared.extras["next_sigmas"].view(VIEW), + sigma_max=t.prepared.extras["sigma_max"].view(VIEW), + noise_level=NOISE_LEVEL, + ) + delta = prev_mean.double() - t.rollout_prev_mean.double() + variance = t.noise_std.double().square() + residual = t.prepared.extras["next_latents"].double() - t.rollout_prev_mean.double() + alpha = 1 / prev_mean[0].numel() + ratio = ((delta * residual - 0.5 * delta.square()) / variance).flatten(1).mean(1).exp() + kappa = (delta.square() / variance).flatten(1).sum(1) + root = kappa.sqrt() + overlap = (-0.5 * alpha * (1 - alpha) * kappa).exp() + advantage = t.prepared.advantage.double() + upper, lower = 1 + CLIP_RANGE, 1 - CLIP_RANGE + clip = torch.where(advantage >= 0, upper, lower) + clip_z = clip.log() / (alpha * root) + 0.5 * root + tilted_clip_z = clip.log() / (alpha * root) + (0.5 - alpha) * root + center_positive = overlap * torch.special.ndtr(tilted_clip_z) + clip * torch.special.ndtr(-clip_z) + center_negative = overlap * torch.special.ndtr(-tilted_clip_z) + clip * torch.special.ndtr(clip_z) + center = torch.where(advantage >= 0, center_positive, center_negative) + clipped = torch.where(advantage >= 0, ratio.clamp(max=upper), ratio.clamp(min=lower)) + oracle_loss = (-advantage * (clipped - center)).sum() + (oracle_grad,) = torch.autograd.grad(oracle_loss, oracle_pred) + torch.testing.assert_close(production_grad, oracle_grad, rtol=4e-5, atol=2e-6) + + baseline_loss, baseline_grad = _grad(t, t.new_pred, score_centering=False) + assert production_loss == baseline_loss + assert (production_grad - baseline_grad).abs().max().item() > 1e-3 + # Clip-masked pairs (0 and 2) move only through the center. + assert baseline_grad[0].abs().sum().item() == 0.0 and baseline_grad[2].abs().sum().item() == 0.0 + assert production_grad[0].abs().sum().item() > 0.0 and production_grad[2].abs().sum().item() > 0.0 + + +def test_identical_means_leave_the_gradient_bit_identical(transition): + """At kappa == 0 the center must be an exact no-op, not a NaN or a rounding-sized perturbation.""" + t = transition + aligned_pred = torch.zeros_like(t.new_pred) + _, centered_grad = _grad(t, aligned_pred, score_centering=True) + _, baseline_grad = _grad(t, aligned_pred, score_centering=False) + assert torch.isfinite(centered_grad).all() + torch.testing.assert_close(centered_grad, baseline_grad, rtol=0, atol=0) + + +def test_rollouts_without_debug_tensors_are_rejected(transition): + """Without the check, a missing debug field would surface as an AttributeError on None.""" + del transition.batch[0]["rollout_debug_tensors"]["rollout_step_prev_sample_mean"] + with pytest.raises(ValueError, match="these rollouts carry none"): + _loss(transition, transition.new_pred) + + +def test_differing_transition_stds_are_rejected(transition): + """A rollout std off by 10% breaks the equal-covariance closed form; it must raise, not center silently.""" + transition.batch[0]["rollout_debug_tensors"]["rollout_step_noise_std_dev"] *= 1.1 + with pytest.raises(ValueError, match="share one transition covariance"): + _loss(transition, transition.new_pred) + + +def test_log_prob_old_that_is_not_the_rollout_density_is_rejected(transition): + """A log_prob_old shifted by 0.01 (no-const or misaligned log-probs) fails the density rebuild check.""" + transition.prepared.extras["log_prob_old"] = transition.prepared.extras["log_prob_old"] + 0.01 + with pytest.raises(ValueError, match="not the Gaussian density"): + _loss(transition, transition.new_pred) diff --git a/tests/fast/backends/fsdp_utils/test_score_centering.py b/tests/fast/backends/fsdp_utils/test_score_centering.py new file mode 100644 index 000000000..2129289d4 --- /dev/null +++ b/tests/fast/backends/fsdp_utils/test_score_centering.py @@ -0,0 +1,103 @@ +"""The closed-form center E_q[clip_A(r)] and its exact derivative. + + q = N(mu_q, s^2 I), p = N(mu, s^2 I), r = (p/q)^(1/D) alpha = 1/D, kappa = |mu - mu_q|^2 / s^2 + under q: log r ~ N(-alpha * kappa / 2, alpha^2 * kappa) --> center(kappa) = E_q[clip_A(r)] in closed form + + center(kappa) --gradcheck--> finite differences (both clip sides, D from 1 to 65536) + kappa in [0, 1e6] --> finite value and gradient, exact kappa == 0 limit (center 1) + z ~ N(0, 1) samples --> E[clip(r)] and E[1{unclipped} r score] match center, dcenter/dmu + gaussian_mean_log_ratio / gaussian_kappa == the same quantities from torch Normal log-densities +""" + +from tests.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=20, suite="stage-a-cpu", labels=[]) + +import math + +import pytest +import torch + +from miles.backends.fsdp_utils.loss_hub.score_centering import ( + clipped_ratio_center, + gaussian_kappa, + gaussian_mean_log_ratio, +) + + +@pytest.mark.parametrize("dimension", [1, 2, 8, 65536]) +@pytest.mark.parametrize("sign", [1.0, -1.0]) +def test_center_gradient_matches_finite_differences(dimension, sign): + """A wrong hand-written d/dkappa (the custom backward) fails here on at least one clip side.""" + kappa_value = 0.7 if dimension < 100 else 2.0 * dimension # tiny alpha with realistic log-ratio spread + kappa = torch.tensor(kappa_value, dtype=torch.float64, requires_grad=True) + advantage = torch.tensor(sign) + + def center(value): + return clipped_ratio_center(value, dimension, advantage, 0.15) + + assert torch.autograd.gradcheck(center, (kappa,), eps=1e-4, atol=1e-8, rtol=3e-5) + + +@pytest.mark.parametrize("dimension", [1, 4, 65536]) +@pytest.mark.parametrize("sign", [1.0, -1.0]) +def test_center_is_finite_from_zero_kappa_to_far_tails(dimension, sign): + """Autograd through sqrt(kappa) at 0, or exp of a far tail, would give NaN or inf here.""" + kappa = torch.tensor([0.0, 1e-300, 1e-16, 1e-8, 1.0, 1e6], dtype=torch.float64, requires_grad=True) + center = clipped_ratio_center(kappa, dimension, torch.full_like(kappa, sign), 1e-4) + (grad,) = torch.autograd.grad(center.sum(), kappa) + assert torch.isfinite(center).all() and torch.isfinite(grad).all() + alpha = 1 / dimension + assert center[0].item() == 1.0 + assert grad[0].item() == -0.5 * alpha * (1 - alpha) + + +@pytest.mark.parametrize("sign", [1.0, -1.0]) +def test_center_and_its_gradient_match_monte_carlo(sign): + """The closed form (clip side, tilt, truncation) is checked against sampling on both advantage signs.""" + # All dependence is along the mean displacement, so this 1-D projection is an + # exact reduction of any equal-covariance D-dimensional pair. + generator = torch.Generator().manual_seed(173) + z_half = torch.randn(200000, generator=generator, dtype=torch.float64) + z = torch.cat((z_half, -z_half)) + dimension, displacement, clip_range = 2, 1.6, 0.2 + alpha = 1 / dimension + ratio = torch.exp(alpha * (displacement * z - 0.5 * displacement**2)) + score = alpha * (z - displacement) + + kappa = torch.tensor(displacement**2, dtype=torch.float64, requires_grad=True) + center = clipped_ratio_center(kappa, dimension, torch.tensor(sign), clip_range) + center_grad = 2 * displacement * torch.autograd.grad(center, kappa)[0] + if sign > 0: + transformed = ratio.clamp(max=1 + clip_range) + effective_score = ratio * score * (ratio < 1 + clip_range) + else: + transformed = ratio.clamp(min=1 - clip_range) + effective_score = ratio * score * (ratio > 1 - clip_range) + tolerance = 6 / math.sqrt(z.numel()) + assert abs(transformed.mean().item() - center.item()) < tolerance * transformed.std().item() + 1e-4 + assert abs(effective_score.mean().item() - center_grad.item()) < tolerance * effective_score.std().item() + 1e-4 + # The uncentered weighted score drifts; subtracting the analytic center removes it. + assert abs(effective_score.mean().item()) > 0.015 + centered = effective_score - center_grad + assert abs(centered.mean().item()) < tolerance * centered.std().item() + 1e-4 + + +def test_mean_log_ratio_and_kappa_match_the_gaussian_densities(): + """An algebra slip in the cancellation-free log ratio or in kappa shows up against torch's Normal.""" + generator = torch.Generator().manual_seed(29) + rollout_prev_mean = torch.randn((4, 2, 3), generator=generator, dtype=torch.float64) + prev_mean = rollout_prev_mean + 0.3 * torch.randn( + rollout_prev_mean.shape, generator=generator, dtype=torch.float64 + ) + variance = torch.tensor([0.1, 0.2, 0.7, 1.4], dtype=torch.float64).reshape(4, 1, 1) + next_latents = rollout_prev_mean + variance.sqrt() * torch.randn( + rollout_prev_mean.shape, generator=generator, dtype=torch.float64 + ) + p = torch.distributions.Normal(prev_mean, variance.sqrt()) + q = torch.distributions.Normal(rollout_prev_mean, variance.sqrt()) + expected = (p.log_prob(next_latents) - q.log_prob(next_latents)).flatten(1).mean(1) + actual = gaussian_mean_log_ratio(next_latents, prev_mean, rollout_prev_mean, variance) + torch.testing.assert_close(actual, expected, rtol=1e-12, atol=1e-12) + expected_kappa = ((prev_mean - rollout_prev_mean).square() / variance).flatten(1).sum(1) + torch.testing.assert_close(gaussian_kappa(prev_mean, rollout_prev_mean, variance), expected_kappa) diff --git a/tests/fast/backends/fsdp_utils/test_sde_step_backend.py b/tests/fast/backends/fsdp_utils/test_sde_step_backend.py index 600c7862f..705288812 100644 --- a/tests/fast/backends/fsdp_utils/test_sde_step_backend.py +++ b/tests/fast/backends/fsdp_utils/test_sde_step_backend.py @@ -56,23 +56,31 @@ def test_carried_sigmas_match_scheduler_lookup_bitwise(self): want = sde_step_with_logprob( _DiffusersFlowScheduler(timesteps, sigmas), v, timesteps[step], x, prev_sample=nxt, noise_level=0.7 ) - for g, w in zip(got, want, strict=True): + for g, w in zip((got.prev_sample, got.log_prob, got.prev_mean, got.std_dev_t), want, strict=True): torch.testing.assert_close(g, w, rtol=0.0, atol=0.0) - assert got[1].shape == (3,) + assert got.log_prob.shape == (3,) + # noise_std is the std log_prob scored against, not the reported std_dev_t + torch.testing.assert_close( + FlowSdeStepBackend().log_prob(nxt, got.prev_mean, got.noise_std), got.log_prob, rtol=0.0, atol=0.0 + ) def test_sigma_just_below_one_takes_sigma_max_like_the_engine(self): # FlowUniPC at shift 12 starts at 0.999993, not 1.0; sgl-d's isclose still swaps in # sigma_max there, where an exact == would leave sigma / (1 - sigma) ~ 1.4e5. sigmas = torch.tensor([0.999993, 0.990818, 0.0]) x = torch.zeros(1, 4) - _, _, _, std_dev_t = FlowSdeStepBackend().sde_step_logprob( - torch.zeros(1, 4), - x, - prev_sample=x, - noise_level=0.7, - sigmas=sigmas[:1], - next_sigmas=sigmas[1:2], - sigma_max=sigmas[1:2], + std_dev_t = ( + FlowSdeStepBackend() + .sde_step_logprob( + torch.zeros(1, 4), + x, + prev_sample=x, + noise_level=0.7, + sigmas=sigmas[:1], + next_sigmas=sigmas[1:2], + sigma_max=sigmas[1:2], + ) + .std_dev_t ) expected = torch.sqrt(sigmas[0] / (1 - sigmas[1])) * 0.7 torch.testing.assert_close(std_dev_t.view(()), expected, rtol=0.0, atol=0.0) @@ -84,7 +92,7 @@ def test_cps_kernel_matches_reference(self): sigmas = torch.tensor([0.7, 0.3]) next_sigmas = torch.tensor([0.6, 0.0]) # terminal σ_next = 0 x, v, nxt = (torch.randn(2, 128, 8) for _ in range(3)) - _, log_prob, mean, std = CpsSdeStepBackend().sde_step_logprob( + step_out = CpsSdeStepBackend().sde_step_logprob( v, x, prev_sample=nxt, @@ -93,6 +101,7 @@ def test_cps_kernel_matches_reference(self): next_sigmas=next_sigmas, sigma_max=torch.full((2,), float("nan")), # CPS has no sigma == 1 special case ) + log_prob, mean = step_out.log_prob, step_out.prev_mean sigma, sigma_next = sigmas.view(-1, 1, 1), next_sigmas.view(-1, 1, 1) std_t = sigma_next * math.sin(0.8 * math.pi / 2) diff --git a/tests/fast/rollout/test_async_training.py b/tests/fast/rollout/test_async_training.py index abf2995b9..6400e5424 100644 --- a/tests/fast/rollout/test_async_training.py +++ b/tests/fast/rollout/test_async_training.py @@ -275,7 +275,7 @@ def test_empty_and_single_rollout(tmp_path, monkeypatch, count): [ (dict(colocate=True), "separate resident"), (dict(offload_rollout=True), "separate resident"), - (dict(loss_type="policy_loss"), "only --loss-type nft"), + (dict(loss_type="sft_loss"), "supports NFT and Flow-GRPO policy_loss"), ], ) def test_train_rejects_unsupported_setups(overrides, message): diff --git a/tests/fast/utils/test_score_centering_args.py b/tests/fast/utils/test_score_centering_args.py new file mode 100644 index 000000000..b13611601 --- /dev/null +++ b/tests/fast/utils/test_score_centering_args.py @@ -0,0 +1,56 @@ +"""--diffusion-score-centering only closes the integral its Gaussian assumptions define. + + policy_loss + sde (stock backend) + debug mode + rollout log-probs + clip in (0, 1) --> allowed + nft / cps / custom backend / no debug mode / recompute old log-prob / clip >= 1 --> rejected + flag off --> anything goes +""" + +from tests.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="stage-a-cpu", labels=[]) + +from argparse import Namespace + +import pytest + +from miles.utils.arguments import validate_score_centering_args + + +def _args(**overrides): + values = dict( + diffusion_score_centering=True, + loss_type="policy_loss", + diffusion_sde_type="sde", + sde_step_backend_path=None, + diffusion_debug_mode=True, + diffusion_recompute_old_log_prob=False, + diffusion_clip_range=1e-4, + ) + values.update(overrides) + return Namespace(**values) + + +@pytest.mark.parametrize( + "overrides, match", + [ + (dict(loss_type="nft"), "policy_loss"), + (dict(loss_type="sft_loss"), "policy_loss"), + (dict(loss_type="custom_loss"), "policy_loss"), + (dict(diffusion_sde_type="cps"), "--diffusion-sde-type sde"), + (dict(sde_step_backend_path="my.Backend"), "default SDE step backend"), + (dict(diffusion_debug_mode=False), "--diffusion-debug-mode"), + (dict(diffusion_recompute_old_log_prob=True), "--diffusion-recompute-old-log-prob"), + (dict(diffusion_clip_range=1.0), "--diffusion-clip-range"), + ], +) +def test_rejects_setups_outside_the_gaussian_closed_form(overrides, match): + with pytest.raises(ValueError, match=match): + validate_score_centering_args(_args(**overrides)) + + +def test_accepts_the_flow_grpo_sde_setup(): + validate_score_centering_args(_args()) + + +def test_flag_off_validates_nothing(): + validate_score_centering_args(_args(diffusion_score_centering=False, loss_type="nft", diffusion_debug_mode=False)) diff --git a/train_diffusion_async.py b/train_diffusion_async.py index a0113d296..59639fb52 100644 --- a/train_diffusion_async.py +++ b/train_diffusion_async.py @@ -1,9 +1,9 @@ """One-rollout overlap. -Each batch is sampled while the previous one trains, so it comes from the EMA before the latest step -(NFT samples with --rollout-weights ema). Resume discards the prefetch. With --async-exact-resume it -resamples its first batch from the checkpointed previous EMA, matching an uninterrupted run; otherwise -it samples that batch from the loaded EMA. +Each batch is sampled while the previous one trains, so it comes from the rollout weights before the +latest step: the EMA under NFT (--rollout-weights ema), the actor under Flow-GRPO policy_loss. Resume +discards the prefetch. With --async-exact-resume it resamples its first batch from the checkpointed +previous EMA, matching an uninterrupted run; otherwise it samples that batch from the loaded EMA. """ import sys @@ -69,8 +69,8 @@ def train(args): configure_logger() if args.colocate or args.offload_train or args.offload_rollout: raise ValueError("async training requires separate resident train/rollout GPU pools") - if args.loss_type != "nft": - raise ValueError("async training supports only --loss-type nft") + if args.loss_type not in ("nft", "policy_loss"): + raise ValueError("async training supports NFT and Flow-GRPO policy_loss") pgs = create_placement_groups(args) init_tracking(args)