From 2ed50d051ec2dcf515cf3f641e15ae3773169594 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:03:32 +0000 Subject: [PATCH 1/2] feat(fsdp): add a train-input hook that preprocesses train pairs before micro-batching --- docs/user-guide/cli-reference.md | 1 + docs/user-guide/customization.md | 14 ++ miles/backends/fsdp_utils/actor.py | 35 +++-- miles/utils/arguments.py | 10 ++ .../fsdp_utils/test_train_input_hook.py | 120 ++++++++++++++++++ 5 files changed, 166 insertions(+), 14 deletions(-) create mode 100644 tests/fast/backends/fsdp_utils/test_train_input_hook.py diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index c57bf3ae7..d1b65472b 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -279,6 +279,7 @@ See [Dtype Control](../advanced/dtype-control.md). | `--teacher-cpu-offload` | flag | off | Keep the teacher shards in pinned CPU memory between forwards. | | `--custom-prepare-train-batch-path` | str | – | Builds DiT inputs. | | `--custom-loss-function-path` | str | – | Loss **formula** only — the DiT forward stays in the actor. | +| `--custom-train-input-function-path` | str | – | Preprocesses a rank's train pairs (the converted rollout output) before they are split into micro-batches, and returns the pairs to train on. `ctx.external_data` holds earlier trainer groups' outputs. | | `--custom-train-output-function-path` | str | – | Runs without grad after a rollout's train steps; its return value reaches the paired rank of each later trainer group as `ctx.external_data[]`. | | `--diffusion-nft-beta` | float | `1.0` | | | `--diffusion-nft-timestep-strategy-path` | str | `…nft.drop_random_steps` | `(args, num_steps, generator) -> list[int]` returning the denoising steps each sample trains on, in training order; `generator` is seeded per sample. Built in: `drop_random_steps` (random order), `drop_final_steps` (schedule order, noisiest first). The final clean output (σ = 0) is never a training step. | diff --git a/docs/user-guide/customization.md b/docs/user-guide/customization.md index 88fa86b64..c467c7cc9 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -25,6 +25,7 @@ signatures they expect, and the defaults they replace — in the same spirit as | | `--custom-convert-samples-to-train-data-path` | Full sample → train_data | | | `--custom-prepare-train-batch-path` | DiT batch preparation | | | `--custom-loss-function-path` | Loss formula only | +| | `--custom-train-input-function-path` | Train-pair preprocessing before micro-batching | | | `--custom-train-output-function-path` | Output handed to later trainer groups | | | `--sde-step-backend-path` | Train-side SDE dynamics | | **Logging** | `--custom-rollout-log-function-path` | Train-rollout logging | @@ -283,6 +284,19 @@ def loss_formula(ctx, batch, prepared, *, new_pred, old_pred, ref_pred, metrics, `new_pred`, `old_pred` and `ref_pred` are keyed by the same stream names as `prepared.latents`. `old_pred` is `None` unless `--loss-type nft`; `ref_pred` is `None` with `--ref-mode none`. +### `--custom-train-input-function-path` + +```python +def train_input(ctx, train_pairs) -> list: + ... +``` + +Preprocesses this rank's train pairs, the rollout output after conversion, before they are split into +micro-batches and optimizer steps. It may filter, reorder or rewrite them, and returns the pairs to +train on. `ctx` is the context the prepare, loss and train-output hooks get, so earlier trainer +groups' outputs are already in `ctx.external_data`. The micro-batch schedule, the training forwards +and the train-output hook see the returned pairs. + ### `--custom-train-output-function-path` ```python diff --git a/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index 55858aba7..18f7ebc65 100644 --- a/miles/backends/fsdp_utils/actor.py +++ b/miles/backends/fsdp_utils/actor.py @@ -177,6 +177,11 @@ def init(self, args: Namespace, role: str, with_ref: bool = False) -> int: # ty self.custom_loss_formula_func = ( load_function(args.custom_loss_function_path) if args.custom_loss_function_path is not None else None ) + self.custom_train_input_func = ( + load_function(args.custom_train_input_function_path) + if args.custom_train_input_function_path is not None + else None + ) self.custom_train_output_func = ( load_function(args.custom_train_output_function_path) if args.custom_train_output_function_path is not None @@ -364,6 +369,22 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An if not train_pairs: raise ValueError("rollout_data['train_data'] is empty") + loss_ctx = DiffusionLossContext( + models=self.models, + reference_models=self.reference_models, + teacher_models=self.teacher_models, + train_pipeline_config=self.train_pipeline_config, + sde_backend=self.sde_backend, + args=self.args, + forward_dtype=self._forward_dtype, + device=device, + rollout_id=rollout_id, + dp_rank=self.parallel_state.dp_rank, + external_data=external_data, + ) + if self.custom_train_input_func is not None: + train_pairs = self.custom_train_input_func(loss_ctx, train_pairs) + num_pairs = len(train_pairs) # ------------- Micro-batch schedule ------------- @@ -391,20 +412,6 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An microbatch_schedule=microbatch_schedule, ) - loss_ctx = DiffusionLossContext( - models=self.models, - reference_models=self.reference_models, - teacher_models=self.teacher_models, - train_pipeline_config=self.train_pipeline_config, - sde_backend=self.sde_backend, - args=self.args, - forward_dtype=self._forward_dtype, - device=device, - rollout_id=rollout_id, - dp_rank=self.parallel_state.dp_rank, - external_data=external_data, - ) - # ------------- Recompute old log-probs (impl-consistent PPO ratio) ------------- if self.args.diffusion_recompute_old_log_prob: with timer("recompute_old_log_prob"), torch.no_grad(): diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index 953eb472d..b57cfdc4f 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -971,6 +971,16 @@ def add_algo_arguments(parser): "DiT forward is owned by the actor; this hook only computes the objective." ), ) + parser.add_argument( + "--custom-train-input-function-path", + type=str, + default=None, + help=( + "Dotted path to `fn(ctx, train_pairs) -> list` that preprocesses this rank's train pairs (the " + "converted rollout output) before they are split into micro-batches and optimizer steps. It " + "returns the pairs to train on; `ctx.external_data` holds earlier trainer groups' outputs." + ), + ) parser.add_argument( "--custom-train-output-function-path", type=str, diff --git a/tests/fast/backends/fsdp_utils/test_train_input_hook.py b/tests/fast/backends/fsdp_utils/test_train_input_hook.py new file mode 100644 index 000000000..86df537bc --- /dev/null +++ b/tests/fast/backends/fsdp_utils/test_train_input_hook.py @@ -0,0 +1,120 @@ +"""The train-input hook preprocesses a rank's train pairs before they are split into micro-batches. + + train pairs (the converted rollout output) + ctx (external_data from earlier groups) + --train-input hook (filter / reorder / rewrite)--> preprocessed pairs + preprocessed pairs --> micro-batch schedule --> training forwards, in order + preprocessed pairs --> train-output hook (the same ctx) + no hook --> the converted train pairs, as before + +The production _train_core runs on CPU with the forward, metrics and rank checks replaced; the +optimizer step is skipped, so only the pairs and ctx each stage receives are observed. +""" + +from tests.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="stage-a-cpu", labels=["fsdp"]) + +import ast +from argparse import Namespace +from contextlib import nullcontext +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import pytest +import torch + +from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext +from miles.utils.train_data_utils import build_microbatch_schedule + + +def _load_train_core(): + path = Path(__file__).resolve().parents[4] / "miles/backends/fsdp_utils/actor.py" + actor_class = next( + node + for node in ast.parse(path.read_text()).body + if isinstance(node, ast.ClassDef) and node.name == "FSDPTrainRayActor" + ) + method = next( + node for node in actor_class.body if isinstance(node, ast.FunctionDef) and node.name == "_train_core" + ) + namespace = dict( + Any=Any, + torch=torch, + DiffusionLossContext=DiffusionLossContext, + build_microbatch_schedule=build_microbatch_schedule, + validate_same_microbatch_counts_across_train_ranks=lambda **kwargs: None, + timer=lambda name: nullcontext(), + new_metric_buffer=lambda *args, **kwargs: SimpleNamespace(reduce=lambda: {}), + ) + exec(compile(ast.Module(body=[method], type_ignores=[]), str(path), "exec"), namespace) + return namespace["_train_core"] + + +def _actor(train_input, train_output, forwarded): + return SimpleNamespace( + models={}, + reference_models={}, + teacher_models={}, + train_pipeline_config=None, + sde_backend=None, + args=Namespace( + num_steps_per_rollout=2, + micro_batch_size=1, + loss_type="policy_loss", + diffusion_recompute_old_log_prob=False, + debug_skip_optimizer_step=True, + log_loss_sigma_bucket=0, + ), + _forward_dtype=torch.float32, + parallel_state=SimpleNamespace(dp_rank=0, dp_group=None), + custom_train_input_func=train_input, + custom_train_output_func=train_output, + optimizer=SimpleNamespace(zero_grad=lambda set_to_none: None), + global_step=0, + _maybe_legacy_window_pad_len=lambda train_pairs, microbatch_ranges: None, + _forward_train_pair_batch=lambda ctx, chunk, **kwargs: forwarded.append((ctx.microbatch_id, chunk)), + _log_metrics=lambda rollout_id, metrics, step: None, + ) + + +@pytest.fixture(autouse=True) +def _cpu_device(monkeypatch): + monkeypatch.setattr(torch.cuda, "current_device", lambda: 0) + + +def test_later_stages_see_the_preprocessed_pairs(): + pairs = [{"sample_index": index} for index in range(6)] + scores = {1: 0.1, 2: 0.2, 4: 0.4, 5: 0.5} + seen_by_input = [] + + def train_input(ctx, train_pairs): + seen_by_input.append((ctx, list(train_pairs))) + critic = ctx.external_data["critic"] + return [ + {**pair, "score": critic[pair["sample_index"]]} for pair in train_pairs if pair["sample_index"] in critic + ] + + forwarded = [] + actor = _actor(train_input, lambda ctx, train_pairs: (ctx, train_pairs), forwarded) + ctx, output_pairs = _load_train_core()( + actor, rollout_id=3, rollout_data={"train_data": pairs}, external_data={"critic": scores} + ) + + preprocessed = [{"sample_index": index, "score": scores[index]} for index in (1, 2, 4, 5)] + assert seen_by_input == [(ctx, pairs)] + assert (ctx.rollout_id, ctx.external_data) == (3, {"critic": scores}) + assert forwarded == [(microbatch_id, [pair]) for microbatch_id, pair in enumerate(preprocessed)] + assert output_pairs == preprocessed + assert actor.global_step == 2 + + +def test_without_the_hook_the_converted_pairs_train(): + pairs = [{"sample_index": index} for index in range(4)] + forwarded = [] + actor = _actor(None, lambda ctx, train_pairs: train_pairs, forwarded) + + output_pairs = _load_train_core()(actor, rollout_id=0, rollout_data={"train_data": pairs}, external_data={}) + + assert forwarded == [(index, [pair]) for index, pair in enumerate(pairs)] + assert output_pairs == pairs From d8e53e52edbceaa9fa98ff319bef53cf8342ce8b Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Mon, 9 Nov 2026 22:41:02 +0000 Subject: [PATCH 2/2] refactor(fsdp): rename the train-input hook to custom_train_input_postprocess Review on #338: `custom_train_input_postprocess_func` says what the hook does, a post-processing step on the converted train pairs. The flag follows the prepare hook's pattern: `--custom-train-input-postprocess-path` sets `args.custom_train_input_postprocess_path`, loaded into `self.custom_train_input_postprocess_func`. Docs and the hook test follow. Co-Authored-By: Claude Mythos 5.1 --- docs/user-guide/cli-reference.md | 2 +- docs/user-guide/customization.md | 4 ++-- miles/backends/fsdp_utils/actor.py | 10 +++++----- miles/utils/arguments.py | 2 +- .../fast/backends/fsdp_utils/test_train_input_hook.py | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index d1b65472b..af4d7b527 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -279,7 +279,7 @@ See [Dtype Control](../advanced/dtype-control.md). | `--teacher-cpu-offload` | flag | off | Keep the teacher shards in pinned CPU memory between forwards. | | `--custom-prepare-train-batch-path` | str | – | Builds DiT inputs. | | `--custom-loss-function-path` | str | – | Loss **formula** only — the DiT forward stays in the actor. | -| `--custom-train-input-function-path` | str | – | Preprocesses a rank's train pairs (the converted rollout output) before they are split into micro-batches, and returns the pairs to train on. `ctx.external_data` holds earlier trainer groups' outputs. | +| `--custom-train-input-postprocess-path` | str | – | Preprocesses a rank's train pairs (the converted rollout output) before they are split into micro-batches, and returns the pairs to train on. `ctx.external_data` holds earlier trainer groups' outputs. | | `--custom-train-output-function-path` | str | – | Runs without grad after a rollout's train steps; its return value reaches the paired rank of each later trainer group as `ctx.external_data[]`. | | `--diffusion-nft-beta` | float | `1.0` | | | `--diffusion-nft-timestep-strategy-path` | str | `…nft.drop_random_steps` | `(args, num_steps, generator) -> list[int]` returning the denoising steps each sample trains on, in training order; `generator` is seeded per sample. Built in: `drop_random_steps` (random order), `drop_final_steps` (schedule order, noisiest first). The final clean output (σ = 0) is never a training step. | diff --git a/docs/user-guide/customization.md b/docs/user-guide/customization.md index c467c7cc9..872576f71 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -25,7 +25,7 @@ signatures they expect, and the defaults they replace — in the same spirit as | | `--custom-convert-samples-to-train-data-path` | Full sample → train_data | | | `--custom-prepare-train-batch-path` | DiT batch preparation | | | `--custom-loss-function-path` | Loss formula only | -| | `--custom-train-input-function-path` | Train-pair preprocessing before micro-batching | +| | `--custom-train-input-postprocess-path` | Train-pair preprocessing before micro-batching | | | `--custom-train-output-function-path` | Output handed to later trainer groups | | | `--sde-step-backend-path` | Train-side SDE dynamics | | **Logging** | `--custom-rollout-log-function-path` | Train-rollout logging | @@ -284,7 +284,7 @@ def loss_formula(ctx, batch, prepared, *, new_pred, old_pred, ref_pred, metrics, `new_pred`, `old_pred` and `ref_pred` are keyed by the same stream names as `prepared.latents`. `old_pred` is `None` unless `--loss-type nft`; `ref_pred` is `None` with `--ref-mode none`. -### `--custom-train-input-function-path` +### `--custom-train-input-postprocess-path` ```python def train_input(ctx, train_pairs) -> list: diff --git a/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index 18f7ebc65..dcfbb7dd4 100644 --- a/miles/backends/fsdp_utils/actor.py +++ b/miles/backends/fsdp_utils/actor.py @@ -177,9 +177,9 @@ def init(self, args: Namespace, role: str, with_ref: bool = False) -> int: # ty self.custom_loss_formula_func = ( load_function(args.custom_loss_function_path) if args.custom_loss_function_path is not None else None ) - self.custom_train_input_func = ( - load_function(args.custom_train_input_function_path) - if args.custom_train_input_function_path is not None + self.custom_train_input_postprocess_func = ( + load_function(args.custom_train_input_postprocess_path) + if args.custom_train_input_postprocess_path is not None else None ) self.custom_train_output_func = ( @@ -382,8 +382,8 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An dp_rank=self.parallel_state.dp_rank, external_data=external_data, ) - if self.custom_train_input_func is not None: - train_pairs = self.custom_train_input_func(loss_ctx, train_pairs) + if self.custom_train_input_postprocess_func is not None: + train_pairs = self.custom_train_input_postprocess_func(loss_ctx, train_pairs) num_pairs = len(train_pairs) diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index b57cfdc4f..111d5397c 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -972,7 +972,7 @@ def add_algo_arguments(parser): ), ) parser.add_argument( - "--custom-train-input-function-path", + "--custom-train-input-postprocess-path", type=str, default=None, help=( diff --git a/tests/fast/backends/fsdp_utils/test_train_input_hook.py b/tests/fast/backends/fsdp_utils/test_train_input_hook.py index 86df537bc..b6525ac0d 100644 --- a/tests/fast/backends/fsdp_utils/test_train_input_hook.py +++ b/tests/fast/backends/fsdp_utils/test_train_input_hook.py @@ -68,7 +68,7 @@ def _actor(train_input, train_output, forwarded): ), _forward_dtype=torch.float32, parallel_state=SimpleNamespace(dp_rank=0, dp_group=None), - custom_train_input_func=train_input, + custom_train_input_postprocess_func=train_input, custom_train_output_func=train_output, optimizer=SimpleNamespace(zero_grad=lambda set_to_none: None), global_step=0,