Skip to content

graph_trainer: two-level ILP memory policy using torchinsights estimators - #3975

Closed
nnurlan008 wants to merge 2 commits into
gh/nnurlan008/6/basefrom
gh/nnurlan008/6/head
Closed

nnurlan008 wants to merge 2 commits into
gh/nnurlan008/6/basefrom
gh/nnurlan008/6/head

Conversation

@nnurlan008

@nnurlan008 nnurlan008 commented Jul 24, 2026 •

Copy link
Copy Markdown

Stack from ghstack (oldest at bottom):

Summary - single-rank auto_perf_maxing

Adds --compile.memory_policy auto_perf_maxing, which automatically decides, per
activation, whether to keep, recompute, or CPU-offload it so the graph's
real peak memory stays under a user budget while minimizing added runtime. This policy
operates on the joint fwd+loss+bwd FX graph at individual tensor/node granularity,
and the three strategies mix freely within a single layer.

It is a two-level ILP:

  • Outer ILP allocates, per transformer layer, continuous keep/recompute/offload
    fractions under a per-GPU peak-memory budget, minimizing estimated added runtime.
    Peak is constrained at every backward position (not just the global peak), and
    offload feasibility respects the D2H/H2D copy-engine window.
  • Inner ILP turns each layer's requested fractions into concrete per-node tags
    (MUST_SAVE / MUST_RECOMPUTE / MUST_CPU_OFFLOAD). RNG and collective/wait ops
    are forced to keep/offload (never recomputed); views/aliases are never offloaded (no
    independent storage). Structurally identical layers are solved once and broadcast,
    which is a large solve-time win with an identical plan.

Tags are materialized by the existing apply_cpu_offload_pass and
selective_activation_remat_pass.

Usage

--compile.memory_policy auto_perf_maxing \
--compile.memory_budget_gb 21.4 \
--compile.runtime_est_mode cost_model      # cost_model | benchmark | interpreter

added to

NGPU=1 MODULE=graph_trainer.llama3 CONFIG=graph_trainer_llama3_1b \
./run_train.sh       --compile.mode aot_fx_trace \
--compile.memory_policy auto_perf_maxing \
--compile.memory_budget_gb 21.4 \
--compile.runtime_est_mode cost_model \
--training.local_batch_size 4 --training.seq_len 2048 \
--compile.disable_passes cudagraph_pass \
--hf_assets_path ./tests/assets/tokenizer \
--dataloader.dataset c4_test --training.steps 5

Results

Single H100, graph_trainer.llama3 (1B) and graph_trainer.qwen3 (1.7B),
local_batch=4, seq_len=2048, cudagraph disabled. Peak = real max_memory_allocated;
step time = median over 10 reps (cost-model runtime estimation). k/r/o = byte-weighted
keep/recompute/offload over layer activations.

At the min achievable budget, auto_perf_maxing matches the offload heuristic's peak but is
faster, using ~2.5x less offload:

model policy peak (GB) step (s) k / r / o (%)
Llama3-1B none (all keep) 32.23 0.288 100 / 0 / 0
Llama3-1B default (SAC) 24.88 0.309 39 / 61 / 0
Llama3-1B sac_and_offload 21.39 0.371 5.9 / 61 / 33.1
Llama3-1B auto_perf_maxing @21.4 21.39 0.331 13.8 / 72.3 / 13.9
Qwen3-1.7B none (all keep) 46.96 0.540 100 / 0 / 0
Qwen3-1.7B default (SAC) 34.95 0.619 41.9 / 58.1 / 0
Qwen3-1.7B sac_and_offload 29.49 0.719 5.5 / 58.1 / 36.5
Qwen3-1.7B auto_perf_maxing @29.5 29.49 0.617 14.4 / 69.9 / 15.7

Same peak as sac_and_offload, ~11% faster (1B) / ~14% faster (1.7B), with roughly
half the offload volume.

Tunable budget -- raising the budget keeps more activations resident (less
recompute), trading memory for speed:

Llama3-1B budget peak (GB) step (s) k / r / o (%)
21.4 21.39 0.331 13.8 / 72.3 / 13.9
23.0 22.07 0.323 28.0 / 58.1 / 13.9
25.0 24.35 0.306 44.2 / 41.9 / 13.9
Qwen3-1.7B budget peak (GB) step (s) k / r / o (%)
29.5 29.49 0.617 14.4 / 69.9 / 15.7
31.5 30.32 0.598 24.4 / 59.9 / 15.7
34.0 33.76 0.595 37.0 / 47.3 / 15.7

Across all budgets, the achieved peak stays within budget.

Grouped solve (solve one representative layer per signature/fractions, broadcast with each_layer_separately flag) yields an
identical plan/peak/fractions to solving every layer, with a less inner ILP solve time:

Inner-ILP solve time is the median over the full sweep (all budgets x 10 reps;
n=80 for 1B, n=100 for 1.7B); min-max in brackets. Per-layer solve time is heavily
right-skewed for 1.7B (CBC per-layer tail), so median is the typical case and the
by-mean speedup is smaller (~13x for 1.7B).

model per-layer inner-ILP (median [min-max]) grouped inner-ILP (median [min-max]) median speedup
Llama3-1B 0.565 s [0.25-0.91] 0.062 s [0.05-0.09] 9.0x
Qwen3-1.7B 9.843 s [0.91-182.9] 0.112 s [0.07-74.5] 87.7x

Numerical proof (non-computation change)

Save/recompute/offload only change where/when an activation lives, never what is
computed. Verified bit-identical loss and grad_norm vs the default policy, per
step, with --debug.seed 42 --debug.deterministic (local_batch=4, seq_len=2048;
full-precision values from TensorBoard; cudagraph disabled; offload+remat enabled):

model budget (min-achievable) loss grad_norm
Llama3-1B 21.4 GB (peak 21.392) bit-identical (5/5 steps) bit-identical
Qwen3-1.7B 29.5 GB (peak 29.489) bit-identical (5/5 steps) bit-identical

Matching the grad_norm curve step-by-step (not just step-1 loss) shows the backward
pass is numerically untouched -- any divergence from recompute/offload would compound
through the weight updates and appear by step 2+.

Files

file what
two_level_ilp_memory_policy_pass.py outer + inner ILP and graph tagging
memory_policy.py register auto_perf_maxing; read budget + runtime mode from config
configs.py memory_policy option, runtime_est_mode, memory_budget_gb

Depends on the FX estimators (peak-memory / runtime / transfer-time) landed in the
prior estimators change.

Limitations / follow-ups

  • interpreter runtime mode needs interp_ctx=(model, *run_args) threaded from
    the trainer; until then it warns and falls back to cost_model. cost_model
    (default, deterministic) and benchmark work as-is.
  • Multi-rank: the policy runs per-rank with no cross-rank coordination. Under
    SPMD, cost_model is deterministic so all ranks produce an identical plan (safe);
    benchmark's per-rank timing noise can yield divergent plans -- use cost_model
    for multi-GPU, or solve-once-and-broadcast (follow-up). Validated single-GPU only.
  • Infeasible budget (below the min achievable) is not handled; it warns and
    returns the origina graph.
  • MoE is not supported;

Test plan

  • I have noticed that when increasing the batch size, he sac_and_offload policy cannot
    find the minimum peak memory. But the 2-level ILP policy can find it. I will add more
    tests for different batch sizes and different models.

[ghstack-poisoned]
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jul 24, 2026
@nnurlan008
nnurlan008 requested a review from yushangdi July 24, 2026 02:07
@yushangdi

Copy link
Copy Markdown
Contributor

let's add some tests in this PR

@yushangdi

Copy link
Copy Markdown
Contributor

@nnurlan008

Copy link
Copy Markdown
Author

can I leave the tests to next PR?

[ghstack-poisoned]
nnurlan008 added a commit that referenced this pull request Aug 20, 2026
…tors

Adds `auto_perf_maxing`: you give it a peak-memory budget, and it decides for
each saved activation whether to keep, recompute, or CPU-offload it, choosing
the combination that costs the least runtime.

The existing policies decide by rule and the peak is whatever falls out. `full`
recomputes everything, `default` saves a fixed set of ops, `sac_and_offload`
offloads whatever fits the host. None of them lets you ask for a memory target.
This one does.

## Quick start

    NGPU=8 MODULE=graph_trainer.llama3 CONFIG=graph_trainer_llama3_8b_c4_test \
      ./run_train.sh \
      --compile.mode aot_fx_trace \
      --compile.memory_policy auto_perf_maxing \
      --compile.memory_budget_gb 29

Two flags matter: turn the policy on, and tell it the budget.

## Flags

    --compile.memory_policy auto_perf_maxing
        Enables the solver.

    --compile.memory_budget_gb <N>          REQUIRED
        Peak GPU memory budget per rank, in GB. Without it the default is
        1000, the budget is never binding, and the policy silently does
        nothing.

    --compile.runtime_est_mode <mode>       default: cost_model
        How per-node runtimes are estimated. `cost_model` is analytical and
        instant. `benchmark` times each kernel for real: slower to plan, but
        the analytical model misprices some ops by 2-7x and the solver then
        makes the wrong call on them. Use `benchmark` when the plan quality
        matters.

    --compile.cpu_offload_budget_gb <N>     default: -1
        Pinned host memory per rank. -1 means "whatever the host allows",
        which is usually right. 0 disables offload entirely and leaves the
        solver with keep/recompute only.

    --compile.cpu_offload_bw <N>            default: 10000
        Assumed D2H/H2D bandwidth in GB/s. This sizes the window the solver
        thinks it has to hide transfers behind compute, so it directly
        controls how much gets offloaded. Lower it if throughput drops from
        over-offloading: the real per-rank rate under contention is well
        below what an idle single-GPU benchmark reports, because every rank
        shares the host path.

    --compile.debug_memory_policy_solver    default: off
        Logs solver inputs and each calibration iteration. Useful when a
        budget is refused and you want to see why.

## Picking a budget

Run full recompute first and read its `Real Peak memory`:

    --compile.memory_policy full

That is the activation-checkpointing floor: `full` already recomputes everything
except RNG ops and layer boundaries, and the solver keeps the same boundaries,
so no keep/recompute split can possibly go below it. Offload can, and measured runs do:
on 8x H100 with qwen3-14B bs16, where full recompute peaks at 45.31 GiB,
completed runs reached 43.73 GiB at 4214 tps (faster than full's 4073) and as
low as 39.99 GiB.

Setting the budget at full's peak gives the "same memory, more speed"
comparison. Going below it works but the headroom shrinks with rank count, so
expect to iterate on the budget rather than assume a target is reachable.

If the budget cannot be met, the solver refuses and tells the tightest peak it
actually measured:

    memory_budget_gb=29.00 GiB is not achievable for this model and
    parallelism: the tightest plan measured is 32.74 GiB after 9 calibration
    iterations. Raise --compile.memory_budget_gb to at least 32.7.

That figure is measured, not modeled, so it is a reliable number to retry from.
The policy never silently exceeds the budget.

## How it works

An outer LP spreads the budget across transformer blocks into per-layer
keep/recompute/offload fractions. An inner ILP then solves each block
independently and tags individual tensors to realize them.

Because the modeled peak is only a proxy for the post-pass graph, the plan is
then calibrated: it is materialized on a throwaway clone, the real peak is
measured, the budget is corrected, and the loop repeats. What ships is a plan whose
measured peak fits, not one the model predicts will fit.

Rank 0 runs the search and broadcasts the winning cap so every rank solves the
same problem and tags the same nodes. Otherwise ranks pick different optima and
deadlock in NCCL on a mismatched all-gather.

## Test plan

4x H100, seq_len 2048, 20 steps, budget set to ceil(full recompute peak) per
cell so memory is matched and only throughput differs:

| model / batch / seq  | full recompute      | auto_perf_maxing     |
|----------------------|---------------------|----------------------|
| qwen3-14B  8 x 2048  | 61.43 GiB / 3580    | 61.62 / 3617 (+1.0%) |
| qwen3-14B 16 x 2048  | 66.31 / 4026        | 66.91 / 4135 (+2.7%) |
| qwen3-14B  8 x 4096  | 66.39 / 3946        | 66.93 / 4103 (+4.0%) |
| llama3-8B  8 x 2048  | 34.22 / 6553        | 34.67 / 7002 (+6.9%) |
| llama3-8B 16 x 2048  | 40.11 / 7746        | 40.31 / 7750 (+0.1%) |
| llama3-8B  8 x 4096  | 40.14 / 7442        | 40.34 / 7502 (+0.8%) |

Faster than full recompute in all six cells, at a peak within 0.2-0.6 GiB. The
margin grows with sequence length: longer sequences make recompute more
expensive while activation memory stays linear in tokens, so there is more to
gain by keeping or offloading instead.

For contrast, `sac_and_offload` on the same cells OOMed on every qwen3 config
and used about twice full recompute's memory on llama3, because it has no
memory target at all.

## Notes

Requires `UNKNOWN_OPTIMIZER_BYTES` and estimators from torchinsights graph_estimation
(meta-pytorch/torchinsights#3). Until that lands, this will not import.

Pull-Request: #3975
ghstack-source-id: dd5932a
@nnurlan008
nnurlan008 marked this pull request as draft September 12, 2026 07:03
@tianyu-l tianyu-l closed this Oct 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants