Skip to content

feat(training): cost-aware scheduling (online + offline) and DSpark step-level loss normalization - #955

Closed
yushengsu-thu wants to merge 11 commits into
sgl-project:mainfrom
yushengsu-thu:dspark-loss-normalization
Closed

yushengsu-thu wants to merge 11 commits into
sgl-project:mainfrom
yushengsu-thu:dspark-loss-normalization

Conversation

@yushengsu-thu

@yushengsu-thu yushengsu-thu commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Cost-Aware Scheduling (key = length | anchors)

 AUTO key:
   anchors → DFlash / DFlash2 / DSpark / Domino   (anchors = min(num_anchors, valid anchors))
   length  → EAGLE3 / P-EAGLE / MTP

 DSpark example: sort by effective anchors
 Entry = anchors / sequence length; batch_size = 2 per rank
 Round = one micro-batch forward + backward per rank (FSDP syncs after every round)
 gradient_accumulation_steps = 2 → 2 rounds = 1 optimizer step

 BEFORE             Rank 0                   Rank 1
 ─────────────────────────────────────────────────────────
 Round 1       [512/8K, 64/1K]           [ 64/1K, 64/1K]
                   Padding                  Waiting
 Round 2       [512/8K,512/8K]           [512/8K, 64/1K]
                                            Padding
                         ↓ Optimizer step

                    Group similar costs
                             ▼

 AFTER              Rank 0                   Rank 1
 ─────────────────────────────────────────────────────────
 Round 1       [512/8K,512/8K]           [512/8K,512/8K]
 Round 2       [ 64/1K, 64/1K]           [ 64/1K, 64/1K]
                         ↓ Optimizer step

      Same samples per step → less padding + less waiting
      (anchor slots per micro-batch = the max in that micro-batch,
       so a 64/1K sample next to a 512/8K one pays 512 slots)

 DSpark: after regrouping, rounds carry very different token totals.
 Normalizing per round would give the short round heavier per-token
 weights, so under scheduling DSpark switches automatically to a
 per-optimizer-step normalization, as DFlash already does.

This PR is the first of three:

  1. DSpark per-step loss normalization, selected automatically under cost-aware scheduling (round, today's behaviour, stays bit for bit otherwise)
  2. online cost-aware scheduling (shared planner + RefDistributor)
  3. offline cost-aware scheduling (sampler + feature cost index)

Design

 training.cost_aware_scheduling: true
   key = auto → declared per algorithm
                (length: EAGLE3 / P-EAGLE / MTP;  anchors: DFlash / DFlash2 / DSpark / Domino)
                     │
                     ▼
      Shared window planner: sort the window by cost → group similar
      samples into one round → assign one slice per rank
                     │
          ┌──────────┴──────────┐
        Online                Offline
     RefDistributor           Data sampler
     dispatches sample refs   orders sample indices
          └──────────┬──────────┘
                     │
        DataLoader → training strategy → draft model (unchanged)
                     │
        Exception: DSpark loss is normalized per optimizer step under scheduling

Split

If need, this PR carries three parts; they can also be reviewed as three stacked PRs (1 is independent, 3 depends on 2).

Part PR What it does core tests docs
1 #986 DSpark per-step loss normalization under cost-aware scheduling (automatic; round, today's behaviour, stays bit for bit otherwise); resolved mode in the resume contract, old checkpoints resume as round +62 / −22 +136 0
2 #987 Online cost-aware scheduling: shared window planner, cost_aware_scheduling / cost_aware_key config, per-algorithm key declaration and validation, RefDistributor dispatches planned rounds, producer records valid_anchors ~+405 ~+540 ~+100
3 #988 Offline cost-aware scheduling: sampler regroups each window (aligned to the accumulation counter), feature cost index with cache, disagg ingest metadata, cost_aware_window, offline resume contract ~+380 / −2 ~+540 ~+35

@yushengsu-thu
yushengsu-thu force-pushed the dspark-loss-normalization branch from 8b6cab8 to fdcc2ed Compare October 13, 2026 09:34
@yushengsu-thu yushengsu-thu reopened this Oct 13, 2026
@yushengsu-thu yushengsu-thu changed the title DSpark: make the loss normalization an explicit option (round | step) feat(training): cost-aware scheduling (online + offline) and DSpark step-level loss normalization Oct 13, 2026
…ware scheduling

DSpark historically averages every DP micro-batch round by its own all-reduced
token weight (`round`). Cost-aware scheduling regroups rounds by cost, which
would make that normalization re-weight tokens by round composition, so the
model gains a `step` mode: it hands the trainer additive `loss_terms` and the
whole optimizer step is averaged by its global token weight, like DFlash, with
no per-micro-batch all-reduce. The mode is chosen automatically (`step` with
`training.cost_aware_scheduling`, `round` otherwise) and recorded in the
DSpark resume contract.
@yushengsu-thu
yushengsu-thu force-pushed the dspark-loss-normalization branch from 3fcf007 to 12c3553 Compare October 13, 2026 12:57
Checkpoints written before the DSpark resume contract recorded
`dspark_loss_normalization` were trained with the per-round normalization.
Treat a missing key as `round` so those runs resume unchanged, while a resume
that now resolves to `step` (cost-aware scheduling on) is still rejected.
One optimizer window is sorted by a per-sample cost key, cut into DP rounds
of similar cost, and each rank takes one contiguous slice. The planner is
pure Python so the online dispatcher and the offline sampler can share it.
…ithm scheduling keys

`training.cost_aware_scheduling` enables cost-balanced DP rounds;
`training.cost_aware_key` picks the per-sample cost (`length`, `anchors`, or
`auto` for the key each algorithm declares in its capabilities: `anchors` for
the DFlash family, `length` for EAGLE3, P-EAGLE and MTP). The application
layer rejects algorithms without a key, EAGLE3 above batch size 1 (its loss
is a per-micro-batch mean), and the anchors key on non-anchor objectives.
With scheduling on, DSpark resolves to its per-step loss normalization.
The capture producer counts the positions whose own and next token are
supervised (the DFlash-family anchor rule) from the prompt's loss mask and
stores the count in the ref metadata, next to num_tokens, so the online
consumer can schedule by anchors without touching the features.
…-balanced rounds

With a scheduling policy the rank-0 distributor plans every secured
optimizer window with the shared planner and publishes its rounds to the
per-rank inboxes in planned order, so each round holds samples of similar
cost. Inboxes are consumed in publish order, so the ack and backpressure
accounting is unchanged. A window whose refs carry no anchor count is
scheduled by length, and one without any usable cost keeps arrival order.
The online consumer records the policy in its checkpoint contract; older
checkpoints without the key resume with scheduling off.
Offline refs need one cost per sample before the first epoch is planned.
Refs that carry num_tokens and valid_anchors metadata are used as-is;
file:// refs are scanned once (input_ids and loss_mask) in parallel threads
and cached under output_dir, keyed by the file list, sizes, mtimes and
max_length. The disaggregated offline producer records valid_anchors in the
ref metadata so its consumer needs no scan.
The offline sampler keeps its seeded per-epoch permutation and DP padding,
then regroups each window of rounds before the DP striding so every rank's
consecutive micro-batches form the planned rounds. Windows follow the global
micro-batch count (gradient accumulation spans epochs) and the drop_last tail
keeps its order, so each optimizer step trains on the same samples as
without scheduling. `training.cost_aware_window` widens the window beyond
one step for offline runs. The builders record the policy, window,
max_length and a digest of the per-sample costs in the checkpoint, so a
resume whose ordering inputs differ is rejected.
…ne runs

CUDA tests through the offline trainer runtime: a DSpark run with scheduling
resumes from its checkpoint with the same inputs, and is rejected when
max_length changes or scheduling is switched off; EAGLE3 trains at batch
size one with the length key. The docs page gains the offline section and
the offline measurements.
@yushengsu-thu
yushengsu-thu marked this pull request as ready for review October 16, 2026 00:37
Copilot AI balanced review requested due to automatic review settings October 16, 2026 00:37

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@yushengsu-thu

yushengsu-thu commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Throughput: cost-aware scheduling vs. baseline (Qwen3-8B, 4x H200)

Steady-state training throughput in samples/s, summed over all trainer ranks. Each row compares the default dispatch with training.cost_aware_scheduling: true (cost_aware_key: auto) on the same data, model, and hardware.

Algorithm Offline baseline Offline cost-aware Offline gain Online baseline Online cost-aware Online gain
DFlash 22.16 23.47 +5.9% 10.80 11.95 +10.6%
DFlash2 22.59 23.96 +6.1% 11.43 12.24 +7.1%
DSpark 29.42 31.86 +8.3% 15.43 16.81 +8.9%
Domino 40.55 41.43 +2.2% 20.97 21.72 +3.6%
EAGLE3, batch 1 11.71 11.78 +0.6% 9.62 9.56 -0.6%

Each configuration ran once, and step time varies by about ±2-3% within a run, so gains of about 3% or less should be read as no change.

Models

  • Target: Qwen/Qwen3-8B, bf16.
  • Drafts: configs/qwen3-8b-{eagle3,peagle,dflash,domino,dspark}.json from the repo. DFlash2 uses a local Qwen3-8B DFlash2 config, trained with strategy: dflash. All drafts are trained from scratch.
  • num_anchors: 512 for DFlash, DFlash2, and DSpark; 256 for Domino.

Dataset

  • Source: ShareGPT from scripts/prepare_data.py --dataset sharegpt (Aeala/ShareGPT_Vicuna_unfiltered, 120,675 conversations), shuffled with seed 42.
  • Responses regenerated by Qwen3-8B with examples/data_regeneration/run_qwen3_8b_sharegpt_non_reasoning.sh (temperature 0, thinking off, up to 4,096 tokens). The first 20,000 successful conversations are used.
  • max_length: 4096, chat_template: qwen. Token lengths: mean 2,095, p10 424, p50 1,796, p90 4,096. 82% of samples have at least 512 valid anchors.

Comment on lines +81 to +97
def scan_feature_files(
paths: Sequence[str], max_len: int, *, workers: int = _SCAN_WORKERS
) -> Dict[str, FileEntry]:
"""Scan ``paths`` in parallel threads (I/O bound: mmap + two small tensors)."""
entries: Dict[str, FileEntry] = {}
total = len(paths)
with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
scanned = pool.map(lambda path: scan_feature_file(path, max_len), paths)
for count, (path, entry) in enumerate(zip(paths, scanned), 1):
entries[path] = entry
if count % 1000 == 0 or count == total:
logger.info(
"cost-aware scheduling: indexed %d/%d feature files",
count,
total,
)
return entries

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.

Does that actually go through mmap, as the comment on scan_feature_files claims? If it materializes every tensor, the one-time index build is a full dataset read per rank — 20k feature files is a lot of I/O, multiplied by DP size since every rank scans independently

@maocheng23

Copy link
Copy Markdown
Collaborator

Closed due to PR 966 is merged

@maocheng23 maocheng23 closed this Oct 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants