diff --git a/README.md b/README.md index 3fd9b2236..86ab323b5 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,7 @@ Each model links to its recipe page; every documented recipe is labeled with a [ | **[LTX-2.3](https://miles.radixark.com/docs/diffusion/models/ltx/ltx2)** | T2V | Flow-GRPO + PickScore | | **[Cosmos3 (Edge / Nano / Super)](https://miles.radixark.com/docs/diffusion/models/cosmos/cosmos3)** | T2I | Flow-GRPO + PickScore | | **[MiniMax H3](https://miles.radixark.com/docs/diffusion/models/h3/h3)** | T2VA | Flow-GRPO + PickScore, LoRA SFT | +| **[MiniMax H3 Image](docs/models/h3/h3-image.md)** | T2I | Flow-GRPO + OCR (LoRA) | --- diff --git a/docs/assets/images/h3/h3_image_ocr_eval.png b/docs/assets/images/h3/h3_image_ocr_eval.png new file mode 100644 index 000000000..0abc80718 Binary files /dev/null and b/docs/assets/images/h3/h3_image_ocr_eval.png differ diff --git a/docs/assets/images/h3/h3_image_ocr_vs_frozen.png b/docs/assets/images/h3/h3_image_ocr_vs_frozen.png new file mode 100644 index 000000000..347ea2da5 Binary files /dev/null and b/docs/assets/images/h3/h3_image_ocr_vs_frozen.png differ diff --git a/docs/index.md b/docs/index.md index 96d8f404f..79674eda4 100644 --- a/docs/index.md +++ b/docs/index.md @@ -11,8 +11,8 @@ pipeline, or from a native package when a family brings its own modeling. Shippe ## Core features - **Verified Recipes for Latest Diffusion Models.** Launchers for Wan2.2-T2V-A14B, Qwen-Image, - LTX-2.3, Cosmos3-Nano, SD3.5, Krea-2, FLUX 3 Image Klein, and MiniMax H3. `TrainPipelineConfig` allows for easy - model support. + LTX-2.3, Cosmos3-Nano, SD3.5, Krea-2, FLUX 3 Image Klein, MiniMax H3, and MiniMax H3 Image. `TrainPipelineConfig` + allows for easy model support. - **Quality control on three fronts.** Deterministic mode supports bit-for-bit comparisons for recipes covered by committed E2E standards; sglang-side monkey patches reduce train/rollout mismatches; and an FSDP2 param-dtype patch provides per-parameter fp32 control under the mixed-precision policy. See [Deterministic @@ -52,6 +52,7 @@ LTX-2.3, Cosmos3-Nano, and MiniMax H3 also appear in the | [Krea-2](models/krea/krea2.md) | T2I | DiffusionNFT + OCR (2- and 8-GPU sync, 6 + 2 async) | | [FLUX 3 Image Klein](models/flux3/flux3-image.md) | T2I | DiffusionNFT + PickScore (LoRA), Flow-GRPO + HPSv2.1 (full finetune) | | [MiniMax H3](models/h3/h3.md) | T2VA | Flow-GRPO + PickScore (t2va, video branch, 2 GPUs), LoRA SFT (t2va, 8 GPUs) | +| [MiniMax H3 Image](models/h3/h3-image.md) | T2I | Flow-GRPO + OCR (LoRA, 8 GPUs) | diff --git a/docs/models/h3/h3-image.md b/docs/models/h3/h3-image.md new file mode 100644 index 000000000..ffa3872df --- /dev/null +++ b/docs/models/h3/h3-image.md @@ -0,0 +1,185 @@ +--- +title: MiniMax H3 Image +description: Text-to-image Flow-GRPO + OCR on MiniMax H3 Image with LoRA — the 8-GPU recipe. +--- + +## 1. Model introduction + +[MiniMax-H3-Image](https://huggingface.co/MiniMaxAI/MiniMax-H3-Image) is the image release of the H3 family: the H3 +DiT (about 33B parameters) without the audio rows, serving text-to-image and image editing. The release is +step-distilled to **6 steps**: the DiT has one output head per denoising step and the checkpoint fixes the sigma +grid, so the step count and the flow shift are not knobs. CFG is distilled in as well, so the recipe is unguided +(`--diffusion-guidance-scale 1.0`). + +miles-diffusion trains the **t2i** path with **LoRA**. Editing is served by the rollout engine but has no recipe, and +full-weight training is not supported yet (§ 5). + +## 2. Supported variants + +| Model | HF ID | Notes | +|---|---|---| +| MiniMax-H3-Image | [`MiniMaxAI/MiniMax-H3-Image`](https://huggingface.co/MiniMaxAI/MiniMax-H3-Image) | Family key `h3_image`; t2i Flow-GRPO with LoRA | + +A name containing `minimax-h3-image` or `minimax_h3_image`, or a local path containing `/h3-image` or `/h3_image`, +resolves to this family. Matching keeps the longest pattern, so the id does not resolve to `h3`. A local path such +as `/data/minimax-h3/h3-image` does, since its longest match is `minimax-h3`: pass `--diffusion-model-family +h3_image` for it. + +The repo ships the same weights in two layouts. The rollout engine loads the native one (`transformer/`, named by +`model_index.json`); the trainer loads the Diffusers one (`transformer_diffusers/`, named by +`modular_model_index.json`), which the loader reads first when a checkpoint ships it. Both sides are addressed as +`transformer`. + +## 3. Family config + +From `miles/backends/fsdp_utils/configs/h3_image.py`, a subclass of the [H3](h3.md) family: + +| Property | Value | Why | +|---|---|---| +| Tasks | `t2i` | The forward rejects a layout with reference rows | +| Loss | `policy_loss` only (asserted) | The forward picks the output head by the pair's rollout step, which only the Flow-GRPO prepare hook sets | +| Steps | 6 for rollout and eval (asserted) | One output head per step of the release's grid | +| Weight sync | LoRA adapters only (asserted) | The engine keeps the per-step heads outside its parameters and cannot receive them | +| LoRA targets | `attn.to_{q,k,v}`, `attn.to_out.0`, `ff.net.0.proj`, `ff.net.2` | H3's; the engine's LoRA update (`lora_merge`) maps them onto its fused layers | +| Forward | `t = 1 - sigma`, `pdd_step_index` = the pair's step, output negated | H3 predicts clean − noise; the shared objective predicts noise − clean | +| Micro-batch | one pair per forward (asserted) | One packed sequence per forward | +| Forced sampling params | `min_generation_area = width × height` | By default the engine generates a small request on a 2048² canvas and resizes it back | +| CFG training | Off (asserted) | CFG is distilled into the checkpoint | + +## 4. Launch + +Canonical recipe: `scripts/run_diffusion_grpo_h3_image_ocr_8gpu.py` — FSDP DP=8 colocated with four TP2 rollout +engines on 8 GPUs, 512×512, OCR reward, LoRA synced over CUDA IPC. + +**Status:** [📈 V — Verified](../../user-guide/recipe-verification.md#v), see § 6.1. + +```bash +python3 scripts/run_diffusion_grpo_h3_image_ocr_8gpu.py + +# alignment diagnostic: freeze the weights, so the debug metrics measure +# train-vs-rollout deviation rather than parameter drift +python3 scripts/run_diffusion_grpo_h3_image_ocr_8gpu.py \ + --num-rollout 2 --eval-interval 0 --extra-args "--debug-skip-optimizer-step" + +# frozen-weights control: rollouts only, the reference a run's rollout reward is read against (§ 5) +python3 scripts/run_diffusion_grpo_h3_image_ocr_8gpu.py \ + --num-rollout 60 --eval-interval 0 --extra-args "--debug-rollout-only" + +# local checkpoint +python3 scripts/run_diffusion_grpo_h3_image_ocr_8gpu.py \ + --extra-args "--hf-checkpoint /path/to/MiniMax-H3-Image" +``` + +What to watch: + +| Signal | Where | Reading | +|---|---|---| +| Reward | `eval/ocr_test`, `rollout/reward/raw_mean` | Eval is the 1018-prompt test split, sampled without noise, so two evals differ only by the weights. The rollout reward follows the 8 prompts of its rollout (0.46 to 0.84 on the base model) | +| Images | `eval_media`, `rollout_media` | The OCR score cannot tell text in a scene from text on an empty background, nor a clean image from a textured one. Look at the images at full size: from about 140 rollouts this recipe's carry a repeating texture, and past 200 it erases the scene (§ 6.1) | +| Rollout vs train | `train/model_output_mean_abs_diff`, `train/prev_mean_diff_over_noise_std` | The trainer's forward and transition mean against the engine's own (`--diffusion-debug-mode`); about 0.02 and 0.018 on a rollout's first optimizer step of the base model. They should not grow much: over the recipe's 200 rollouts the first stays between 0.020 and 0.025 (20-rollout means) and the second near 0.017. Both fall afterwards, as the scene fades, to 0.010 and 0.007 by 1000 rollouts | +| PPO ratio | `train/clipfrac`, `train/log_prob_mean_abs_diff` | 0 on a rollout's first optimizer step (the old log-prob is recomputed by the trainer), then how far that step moved the policy | +| Memory | `nvidia-smi`, `train/device_memory_used_gb` | A GPU peaks near 70 GB, during a rollout (its TP2 engine rank). While training, the engine is offloaded and about 26 GB are in use | + +## 5. Recipe notes + +- **`cps`, not flow-`sde`.** On the release's 6-step grid, flow-SDE noise costs image quality in proportion to its + level: against the noise-free rollout of the same prompt and seed, PickScore drops by 0.004 at noise level 0.3, 0.016 + at 0.5 and about 0.04 at 0.7, with visible grain. `cps` at 0.8 costs none, on any window (sgl-project/sglang#51113). +- **Every step but the last is noisy and trained** (`--diffusion-num-sde-steps 5 --diffusion-sde-window-range 0,5`). + The last step ends at sigma 0, where `cps` adds no noise. With a 2-step window, the reward of 8 fixed prompts rose + half as fast per rollout (§ 6). +- **The engine applies the adapters at forward time** (`--sglang-lora-merge-mode dynamic`). Merged into the bf16 + weights, the engine drifts from the trainer as the adapters grow: on a rollout's first optimizer step, + `train/model_output_mean_abs_diff` went from 0.021 on rollout 0 to 0.030 on rollout 24. With `dynamic` it stays at + 0.020, and a sync takes 1.2 s instead of 11.5 s; a rollout takes 14 s instead of 8 s. +- **The trainer recomputes the old log-probs** (`--diffusion-recompute-old-log-prob`). On the base model the engine's + and the trainer's log-probs differ by 0.7e-4 to 1.7e-4, the size of the clip range (`1e-4`): scored against the + engine's, 20-38% of the pairs are clipped on a rollout's first optimizer step. +- **lr 1e-4, 2 optimizer steps per rollout.** The learning rate decides whether the adapters generalize. At 2e-4 the + recipe fits 8 fixed prompts 1.5 times as fast as at 1e-4, and on the full dataset gets worse on every prompt it has + not trained on: `eval/ocr_test` falls from 0.600 to 0.550 in 20 rollouts. At 1e-4 it rises to 0.621, and to 0.830 + after 200 (§ 6). lr 3e-4 with a 3e-4 clip range and 4 optimizer steps took it to 0.37 in 10 rollouts. +- **200 rollouts, and no further.** The reward is OCR alone, and `--diffusion-kl-beta 0` leaves nothing that holds + the policy near the base model. Up to 180 rollouts the eval rises with the scene still there, though from about 140 + the images carry a repeating texture; after 200 it rises because the scene is erased, and by 800 the images are + text on an empty background (§ 6.1). Training longer + needs a term that keeps the image: a KL to the base model (`--diffusion-kl-beta`, 0.04 in the SD3.5 OCR recipe) + or a second reward such as PickScore (`weighted_mixture_rm`). Neither has been measured on this model. +- **Tune on `eval/ocr_test` together with the eval images, not on the reward of a fixed prompt set**, which rises + fastest for the settings that generalize worst. The eval alone is the number this recipe hacks (§ 6.1). For a + reading before the next eval, run the frozen-weights control of § 4 once: the fixed `--rollout-seed` and the + unshuffled prompt order give rollout k the same prompts and noise in every run (`--deterministic-mode` makes the + trained run itself repeatable), so a run's `rollout/reward/raw_mean` minus the control's is its gain on prompts it + has not seen. Rollout 0 differs by exactly 0. +- **No gradient checkpointing.** One pair per forward peaks at 16 GB on the trainer, and checkpointing made the + training phase a third longer (64 s against 47 s). +- **Cost.** About 73 s per rollout on 8 H200: 14 s to generate and score 128 images, 47 s to train on their 640 + pairs, the rest to move the engines and the trainer on and off the GPUs. With the evals, the recipe's 200 rollouts + take 4.4 hours. +- **Engine.** MiniMax-H3-Image rollouts need sgl-project/sglang#51113 in `sglang-miles`. The checkpoint must ship both + layouts (§ 2). +- **LoRA only.** The engine keeps the DiT's per-step output heads outside its parameters and cannot receive them, so + the family refuses a run that trains without `--use-lora`. + +## 6. Reference results + +### 6.1 The recipe on the full dataset + +One run of the recipe's settings on 8 H200, 1000 rollouts in 22 hours. The recipe stops at 200 (25,600 images, 4.4 +hours); the learning rate is constant, so its run is the first 200 rollouts of this one. The second row is the detail +left in the 8 eval images wandb logs, always for the same 8 prompts: the mean luminance step between neighbouring +pixels. + +| Rollouts trained | 0 | 100 | 180 | 200 | 240 | 280 | 320 | 400 | 600 | 800 | 1000 | +|---|---|---|---|---|---|---|---|---|---|---|---| +| `eval/ocr_test` | 0.6003 | 0.6795 | 0.8181 | 0.8303 | 0.8813 | 0.8101 | 0.9141 | 0.7991 | 0.9475 | 0.9650 | 0.9565 | +| Image detail | 0.061 | 0.066 | 0.060 | 0.054 | 0.035 | 0.025 | 0.013 | 0.022 | 0.013 | 0.015 | 0.016 | + +![MiniMax H3 Image eval OCR and image detail](../../assets/images/h3/h3_image_ocr_eval.png) + +- **Up to 180 rollouts the scene stays, but the images are not clean.** The eval goes from 0.600 to 0.818 and the + text is larger and better spelled. From about 140 rollouts, smooth regions (skin, paper, a sign's background) carry + a fine repeating texture, plain at full size by 160. The detail measure does not see it: it detects an erased + scene, not a textured one. +- **At 200, where the recipe stops, the scene is still there** and the detail measure reads 0.054, its first value + below the 0.059 to 0.066 of the ten evals before it. +- **After 200 the reward is hacked.** Between 200 and 320 rollouts the eval goes from 0.83 to 0.91 while the image + detail falls to a quarter: the scene fades, and from 800 on the images are the quoted text on an empty background. + The OCR score of those images is higher, and it is the only thing the recipe rewards. +- **The drop at 400 is the scene coming back.** The eval is 0.115 below its value at 320 and the image detail is up + from 0.013 to 0.022. Not every drop is: from 240 to 280 the eval and the detail fall together. +- **The trainer stays aligned with the engine.** `train/model_output_mean_abs_diff` on a rollout's first optimizer + step, averaged over 100 rollouts, is 0.021 and 0.023 over the recipe's 200 rollouts and falls to 0.010 by 1000. + `train/clipfrac` on the second optimizer step, averaged over 20 rollouts, stays below 0.32. +- **The run is reproducible.** A second launch reproduced the first 20 rollouts' rewards and the eval after them + exactly. + +### 6.2 The first rollouts, by learning rate + +The last column is `rollout/reward/raw_mean` over rollouts 10-19 minus the same rollouts of a `--debug-rollout-only` +run (same prompts, same noise, frozen weights): + +| lr | `eval/ocr_test` at rollout 0 | After 20 rollouts | Rollout reward against frozen weights | +|---|---|---|---| +| 1e-4 (recipe) | 0.6003 | 0.6213 | +0.013 ± 0.007 | +| 2e-4 | 0.6003 | 0.5500 | −0.061 ± 0.013 | + +![MiniMax H3 Image rollout reward against frozen weights](../../assets/images/h3/h3_image_ocr_vs_frozen.png) + +### 6.3 Fitting 8 fixed prompts + +The same 8 train prompts every rollout, 25 rollouts, slope of `rollout/reward/raw_mean` per rollout. This measures +how fast a setting fits its prompts, not whether it generalizes (§ 5): + +| Noisy steps | lr | Engine LoRA | Reward per rollout | First-step `train/model_output_mean_abs_diff`, mean of the first 5 rollouts → of the last 5 | +|---|---|---|---|---| +| 2-step window | 1e-4 | merged | +0.0018 ± 0.0007 | 0.024 → 0.032 | +| 5 | 1e-4 | merged | +0.0038 ± 0.0008 | 0.022 → 0.031 | +| 5 | 2e-4 | merged | +0.0058 ± 0.0008 | 0.026 → 0.030 | +| 5 | 2e-4 | dynamic | +0.0051 ± 0.0010 | 0.020 → 0.020 | + +## 7. Pairs well with + +- [MiniMax H3](h3.md) — the video family this one subclasses. +- [SDE Step Backend](../../advanced/sde-backend.md) — `cps` and flow-`sde`, and the alignment checklist. +- [LoRA Training and Weight Sync](../../advanced/lora.md) — the IPC adapter sync (`--lora-ipc-weight-sync` with `--colocate`) the recipe uses. diff --git a/docs/user-guide/recipe-verification.md b/docs/user-guide/recipe-verification.md index 2492eea7c..098c68499 100644 --- a/docs/user-guide/recipe-verification.md +++ b/docs/user-guide/recipe-verification.md @@ -57,6 +57,7 @@ count as verification. - `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. + - `run_diffusion_grpo_h3_image_ocr_8gpu.py` — MiniMax H3 Image 8-GPU colocated LoRA Flow-GRPO + OCR. - **○ NV** - `run_diffusion_grpo_wan22_pickscore_5gpu.py` — Wan2.2 5-GPU LoRA Flow-GRPO + PickScore. diff --git a/docs/user-guide/rewards.md b/docs/user-guide/rewards.md index 04a35f576..9ae4a6910 100644 --- a/docs/user-guide/rewards.md +++ b/docs/user-guide/rewards.md @@ -206,8 +206,8 @@ substring hit as perfect (`dist=0`), and caps `dist` at `len(target)` — see `miles/rollout/rm_hub/ocr.py`. OCR runs on **CPU** Ray actors (`--ocr-num-workers`, default 4). Used by the -SD3 Flow-GRPO OCR and OCR & PickScore recipes, the three Krea-2 DiffusionNFT recipes, and the -smoke mode of the SD3 DiffusionNFT recipe. +SD3 Flow-GRPO OCR and OCR & PickScore recipes, the MiniMax H3 Image Flow-GRPO recipe, the three +Krea-2 DiffusionNFT recipes, and the smoke mode of the SD3 DiffusionNFT recipe. ### API rewards (`--rm-type openai_api` / `custom_api`) @@ -287,7 +287,7 @@ Dataset repo: [`rockdu/miles-diffusion-datasets`](https://huggingface.co/dataset |---|---| | `hpdv2/` | SD3 HPS Flow-GRPO | | `flowgrpo_pickscore/` | PickScore recipes (SD3 NFT, Qwen-Image, Wan2.2, LTX, Cosmos3, Krea-2, MiniMax H3) | -| `flowgrpo_ocr/` | SD3 OCR and OCR & PickScore Flow-GRPO, Krea-2 OCR NFT, NFT smoke test | +| `flowgrpo_ocr/` | SD3 OCR and OCR & PickScore Flow-GRPO, MiniMax H3 Image OCR Flow-GRPO, Krea-2 OCR NFT, NFT smoke test | ### Per-sample rm_type override diff --git a/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index 4c2c6e290..a99edcca3 100644 --- a/miles/backends/fsdp_utils/actor.py +++ b/miles/backends/fsdp_utils/actor.py @@ -266,7 +266,8 @@ def wake_up(self) -> None: print_memory("after wake_up DiT") def save_model(self, rollout_id: int, force_sync: bool = False) -> None: # type: ignore[override] - if self.args.save is None: + # a rollout-only actor loads no model + if self.args.save is None or self.args.debug_rollout_only: return checkpoint.save(self, iteration=rollout_id) diff --git a/scripts/run_diffusion_grpo_h3_image_ocr_8gpu.py b/scripts/run_diffusion_grpo_h3_image_ocr_8gpu.py new file mode 100644 index 000000000..a668b3659 --- /dev/null +++ b/scripts/run_diffusion_grpo_h3_image_ocr_8gpu.py @@ -0,0 +1,174 @@ +"""MiniMax H3 Image t2i OCR Flow-GRPO with LoRA on 8 colocated GPUs. + +FSDP DP=8 shares the GPUs with four TP2 sglang engines; the LoRA adapters sync over CUDA IPC. + +H3 Image is a 6-step distilled model: its DiT has one output head per denoising step and the +release fixes the sigma grid, so the step count, the flow shift and the guidance are not knobs. +What the recipe chooses, each from a measurement (docs/models/h3/h3-image.md): + * cps, not sde: on this grid flow-SDE noise costs image quality in proportion to its level, + cps at 0.8 costs none. + * Every step but the last is noisy and trained; the last ends at sigma 0, where cps has no + noise. With a 2-step window a prompt's samples still differ by their initial noise, which no + trained step explains, and the reward of 8 fixed prompts rose half as fast per rollout. + * The engine applies the adapters at forward time (dynamic) instead of merging them: merged + into bf16 weights, part of each small update is rounded away and the engine drifts from the + trainer as the adapter grows. + * The trainer recomputes the old log-probs: the engine's and the trainer's differ by about + 1e-4 on the base model, the size of the clip range. + * lr 1e-4: at 2e-4 the recipe fits its train prompts faster and gets worse on every other one + (eval OCR 0.60 -> 0.55 in 20 rollouts); at 1e-4 the eval rises. + * No gradient checkpointing: one pair per forward peaks at 16 GB on the trainer, and + checkpointing made the training phase a third longer. + +The reward is OCR alone and nothing holds the policy near the base model (kl 0). Past about 200 +rollouts the reward keeps rising because the scene is erased, until only the text is left: the +recipe stops there. Its images are not clean before that either, with a repeating texture from +about 140 rollouts (docs/models/h3/h3-image.md, reference results). + +Usage: + python3 scripts/run_diffusion_grpo_h3_image_ocr_8gpu.py + + # train/rollout alignment diagnostic: freeze the weights so the debug metrics measure + # pure train-vs-rollout deviation rather than parameter drift + python3 scripts/run_diffusion_grpo_h3_image_ocr_8gpu.py --num-rollout 2 \ + --eval-interval 0 --extra-args "--debug-skip-optimizer-step" +""" + +from dataclasses import dataclass + +import typer + +import miles.utils.external_utils.command_utils as U + +MODEL = "MiniMaxAI/MiniMax-H3-Image" +DATASET = "rockdu/miles-diffusion-datasets" +DATASET_SUBSET = "flowgrpo_ocr" +WANDB_PROJECT = "miles-diffusion-grpo" + + +@dataclass +class ScriptArgs(U.ExecuteTrainConfig): + num_rollout: int = 200 + rollout_batch_size: int = 8 + n_samples_per_prompt: int = 16 + num_steps_per_rollout: int = 2 + eval_interval: int = 20 + save_interval: int = 20 + data_dir: str = "/root/datasets" + extra_args: str = "" + + +def prepare(args: ScriptArgs) -> str: + local_dir = U.hf_download_dataset(DATASET, include=f"{DATASET_SUBSET}/**", data_dir=args.data_dir) + return f"{local_dir}/{DATASET_SUBSET}" + + +def execute(args: ScriptArgs, prompt_dir: str) -> None: + run_name = f"diffusion_grpo_h3_image_ocr_8gpu_{U.create_run_id()}" + + ckpt_args = ( + f"--hf-checkpoint {MODEL} --diffusion-task t2i " + f"--save {args.output_dir}/{run_name}/ckpt --save-interval {args.save_interval} " + ) + + rollout_args = ( + "--rollout-function-path miles.rollout.sglang_diffusion_rollout.generate_rollout " + f"--prompt-data {prompt_dir}/train.jsonl " + "--input-key input " + f"--rollout-batch-size {args.rollout_batch_size} " + f"--n-samples-per-prompt {args.n_samples_per_prompt} " + f"--num-steps-per-rollout {args.num_steps_per_rollout} " + f"--num-rollout {args.num_rollout} " + # the H3 Image forward takes one sample and one step at a time + "--rollout-microgroup-size 1 " + "--micro-batch-size-sample 1 " + "--micro-batch-size-tstep 1 " + "--diffusion-train-iter-order sample_major " + ) + + diffusion_args = ( + "--diffusion-num-steps 6 " + "--diffusion-guidance-scale 1.0 " + "--diffusion-height 512 " + "--diffusion-width 512 " + "--diffusion-sde-type cps " + "--diffusion-noise-level 0.8 " + "--diffusion-step-strategy-path miles.rollout.step_strategy_hub.sde_window " + "--diffusion-num-sde-steps 5 " + "--diffusion-sde-window-range 0,5 " + # the engine returns its own model output and transition mean for the trainer to compare with + "--diffusion-debug-mode " + ) + + eval_args = "" + if args.eval_interval: + eval_args = ( + f"--eval-interval {args.eval_interval} " + f"--eval-prompt-data ocr_test {prompt_dir}/test.jsonl " + "--n-samples-per-eval-prompt 1 " + ) + + grpo_args = ( + "--advantage-estimator grpo --globalize-reward-std --diffusion-clip-range 1e-4 --diffusion-kl-beta 0.0 " + "--diffusion-recompute-old-log-prob " + ) + + optimizer_args = "--lr 1e-4 --adam-beta2 0.999 --weight-decay 1e-4 " + + lora_args = "--use-lora --lora-ipc-weight-sync --lora-rank 64 --lora-alpha 128 --lora-init-weights gaussian " + + reward_args = "--rm-type ocr --ocr-num-workers 16 --rollout-parser-num-workers 8 " + + 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 4 " + "--sglang-lora-merge-mode dynamic " + "--sglang-tp-size 2 " + "--sglang-sp-degree 1 " + "--sglang-ulysses-degree 1 " + "--sglang-ring-degree 1 " + "--sglang-dit-precision bf16 " + "--update-weight-buffer-size 2147483648 " + ) + + train_backend_args = ( + "--train-backend fsdp " + "--fsdp-master-dtype bf16 " + "--fsdp-reduce-dtype bf16 " + "--diffusion-forward-dtype bf16 " + ) + + misc_args = ( + "--actor-num-nodes 1 " + "--actor-num-gpus-per-node 8 " + "--rollout-num-gpus 8 " + "--rollout-num-gpus-per-engine 2 " + "--num-gpus-per-node 8 " + "--colocate " + "--deterministic-mode " + ) + + U.execute_train( + train_args=( + f"{ckpt_args} {rollout_args} {diffusion_args} {eval_args} {grpo_args} {optimizer_args} " + f"{lora_args} {reward_args} {wandb_args} {sglang_args} {train_backend_args} " + f"{misc_args} {args.extra_args}" + ), + num_gpus_per_node=8, + config=args, + extra_env_vars={"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True"}, + ) + + +@U.dataclass_cli +def main(args: ScriptArgs) -> None: + prompt_dir = prepare(args) + execute(args, prompt_dir) + + +if __name__ == "__main__": + typer.run(main)