Repository navigation
graph_trainer: two-level ILP memory policy using torchinsights estimators - #3975
Closed
nnurlan008 wants to merge 2 commits into
Closed
nnurlan008 wants to merge 2 commits into
nnurlan008 wants to merge 2 commits into
Conversation
nnurlan008
requested review from
IvanKobzarev,
SherlockNoMad,
aditvenk,
sanketpurandare,
tianyu-l and
xmfan
as code owners
July 24, 2026 00:52
Contributor
|
let's add some tests in this PR |
Contributor
|
is the GraphTrainer 8 GPU Integration Tests / build-test / linux-job (pull_request) failure related? |
Author
|
can I leave the tests to next PR? |
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
marked this pull request as draft
September 12, 2026 07:03
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stack from ghstack (oldest at bottom):
Summary - single-rank
auto_perf_maxingAdds
--compile.memory_policy auto_perf_maxing, which automatically decides, peractivation, 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:
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.
(
MUST_SAVE/MUST_RECOMPUTE/MUST_CPU_OFFLOAD). RNG and collective/wait opsare 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_passandselective_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 | interpreteradded to
Results
Single H100,
graph_trainer.llama3(1B) andgraph_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_maxingmatches the offload heuristic's peak but isfaster, using ~2.5x less offload:
Same peak as
sac_and_offload, ~11% faster (1B) / ~14% faster (1.7B), with roughlyhalf the offload volume.
Tunable budget -- raising the budget keeps more activations resident (less
recompute), trading memory for speed:
Across all budgets, the achieved peak stays within budget.
Grouped solve (solve one representative layer per signature/fractions, broadcast with
each_layer_separatelyflag) yields anidentical 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).
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
defaultpolicy, perstep, with
--debug.seed 42 --debug.deterministic(local_batch=4, seq_len=2048;full-precision values from TensorBoard; cudagraph disabled; offload+remat enabled):
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
two_level_ilp_memory_policy_pass.pymemory_policy.pyauto_perf_maxing; read budget + runtime mode from configconfigs.pymemory_policyoption,runtime_est_mode,memory_budget_gbDepends on the FX estimators (peak-memory / runtime / transfer-time) landed in the
prior estimators change.
Limitations / follow-ups
interpreterruntime mode needsinterp_ctx=(model, *run_args)threaded fromthe trainer; until then it warns and falls back to
cost_model.cost_model(default, deterministic) and
benchmarkwork as-is.SPMD,
cost_modelis deterministic so all ranks produce an identical plan (safe);benchmark's per-rank timing noise can yield divergent plans -- usecost_modelfor multi-GPU, or solve-once-and-broadcast (follow-up). Validated single-GPU only.
returns the origina graph.
Test plan
sac_and_offloadpolicy cannotfind 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.