Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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/user-guide/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-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[<role>]`. |
| `--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. |
Expand Down
14 changes: 14 additions & 0 deletions docs/user-guide/customization.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-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 |
Expand Down Expand Up @@ -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-postprocess-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
Expand Down
35 changes: 21 additions & 14 deletions miles/backends/fsdp_utils/actor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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_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 = (
load_function(args.custom_train_output_function_path)
if args.custom_train_output_function_path is not None
Expand Down Expand Up @@ -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_postprocess_func is not None:
train_pairs = self.custom_train_input_postprocess_func(loss_ctx, train_pairs)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CC cmt

[P2] Still open from the last round: the empty check at L359 runs on the raw list, so a hook that returns [] passes 0 % num_steps_per_rollout and build_microbatch_schedule (n empty steps) and the loop then does optimizer.step / lr step / global_step / EMA step / train-output hook with no forward at all. Only fp16 and nft fail loudly; bf16 GRPO/DMD2 log a zero-loss step and move on.
select_scored_pairs can't return [] today, hence P2, but the hook is documented as a filter, so please re-check if not train_pairs: raise after the hook and add the [] case to the test.


num_pairs = len(train_pairs)

# ------------- Micro-batch schedule -------------
Expand Down Expand Up @@ -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():
Expand Down
10 changes: 10 additions & 0 deletions miles/utils/arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -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-postprocess-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,
Expand Down
120 changes: 120 additions & 0 deletions tests/fast/backends/fsdp_utils/test_train_input_hook.py
Original file line number Diff line number Diff line change
@@ -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_postprocess_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
Loading