Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
dea6b36
refactor(fsdp): return a typed SdeStepScore from sde_step_logprob
HJSang Oct 6, 2026
0282444
feat(fsdp): score centering for Flow-GRPO under train/rollout mismatch
HJSang Oct 6, 2026
bfb1ee4
test(e2e): run the SD3.5 OCR GRPO recipe with score centering
HJSang Oct 6, 2026
1143db0
Center the clipped PPO ratio exactly instead of the raw score
Rockdu Nov 4, 2026
5f61822
test(e2e): run score centering against the rollout's own log-probs, w…
Rockdu Nov 4, 2026
0d8bea9
docs: describe the clipped-ratio center and its requirements on the S…
Rockdu Nov 4, 2026
6eea713
Inline _stack_rollout_prev_mean: one caller, same shape as the rollou…
Rockdu Nov 4, 2026
3f573ae
feat(async): allow Flow-GRPO policy_loss in train_diffusion_async.py
Rockdu Nov 4, 2026
686b54d
feat(recipe): add the Krea-2 async Flow-GRPO + score centering OCR re…
Rockdu Nov 4, 2026
ce801e0
Merge remote-tracking branch 'origin/main' into pr298
Rockdu Nov 4, 2026
55ea5ba
test(e2e): drop the SD3 score-centering e2e until it has a recorded s…
Rockdu Nov 4, 2026
9cc43fd
test(async): reject sft_loss now that async training accepts policy_loss
Rockdu Nov 4, 2026
b29d062
Merge branch 'main' into feat/flow-grpo-score-centering
Rockdu Nov 11, 2026
f465134
feat(scripts): run the Krea-2 async Flow-GRPO recipe on 4+4 GPUs with…
Rockdu Nov 11, 2026
3110180
docs: sync the Krea-2 async Flow-GRPO recipe, add its fp8 reference c…
Rockdu Nov 11, 2026
077baac
refactor(fsdp): rename SdeStepScore to SdeStepOutput
Rockdu Nov 11, 2026
23d9a3f
refactor(fsdp): move score centering and its mean-gap metric out of t…
Rockdu Nov 11, 2026
e40854e
fix(scripts): give the Krea-2 async Flow-GRPO recipe a 64gb output st…
Rockdu Nov 11, 2026
2e207a2
docs: mark score centering experimental in its section headings
Rockdu Nov 11, 2026
b3a8597
docs: name the algorithm in the Krea-2 headings and shorten the score…
Rockdu Nov 11, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/advanced/dtype-control.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |


Expand Down
39 changes: 38 additions & 1 deletion docs/advanced/sde-backend.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
69 changes: 59 additions & 10 deletions docs/models/krea/krea2.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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:

Expand All @@ -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 <file> --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.
Expand Down
3 changes: 2 additions & 1 deletion docs/user-guide/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`. |
Expand Down Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions docs/user-guide/recipe-verification.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
33 changes: 27 additions & 6 deletions miles/backends/fsdp_utils/loss_hub/flow_grpo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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):
Expand All @@ -149,24 +151,40 @@ 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)

kl_sum = loss_sum.new_zeros(())
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()

Expand All @@ -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(
Expand Down
Loading
Loading