Skip to content

feat(dynamo): single-block low_memory with map_weights, model_weights_on_meta, and Hub checkpoints - #5005

Open
cehongwang wants to merge 1 commit into
mainfrom
cehongw/low-memory-from-loaded-model
Open

cehongwang wants to merge 1 commit into
mainfrom
cehongw/low-memory-from-loaded-model

Conversation

@cehongwang

@cehongwang cehongwang commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Description

low_memory now runs model construction, weight streaming, and compilation inside a single with block — users no longer build separate save_weights_for_mapping scripts, wrap model constructors in lambdas, or manage a second meta context manager. Part of #5001.

  • with torch_tensorrt.dynamo.low_memory(*, model_weights_on_meta=False, ...) as low_mem: exposes compilation memory settings (offload_module_to_cpu, enable_resource_partitioning, cpu_memory_budget, max_partition_size, release_weights_after_build); CPU offload and resource partitioning are on unless set, and max_partition_size fixes the engine size instead of deriving it from free memory. With model_weights_on_meta=True, entering places newly registered nn.Parameter tensors on meta while keeping computed buffers real (such as rotary inv_freq), and offload_module_to_cpu stays on even when set to False, with a warning: the mapped weights are CPU tensors, and offload is what moves the weights of the parts that run in PyTorch to the GPU after the engines are built (without it, a model whose embedding ran in PyTorch failed when called: Expected all tensors to be on the same device). By default (model_weights_on_meta=False), model construction is left untouched so low_mem.compile_settings can be used on its own without map_weights.
  • low_mem.map_weights(model, checkpoint=None, *, checkpoint_key=None) immediately turns meta parameter creation off (and compiler entry points also call stop_placing_parameters_on_meta() automatically if map_weights was skipped), streams weights in 64 MiB chunks into a temporary file in Torch-TensorRT's cache directory (casting each chunk to the model's dtype), and points model's tensors at zero-copy views of that file.

Three ways to use low_memory:

# 1. Standard Hugging Face model (zero weight allocation): construct with from_config (NOT from_pretrained)
config = AutoConfig.from_pretrained("meta-llama/Llama-3.2-1B")
with torch_tensorrt.dynamo.low_memory(model_weights_on_meta=True) as low_mem:
    model = AutoModelForCausalLM.from_config(config, dtype=torch.bfloat16).eval()
    low_mem.map_weights(model)  # auto-detects checkpoint from model.config._name_or_path
    exported = torch.export.export(model, (example,))
    trt_model = torch_tensorrt.dynamo.compile(
        exported, inputs=[example.cuda()], **low_mem.compile_settings
    )

# 2. Custom / LeRobot model on meta: construct from config, pass local path or Hub repo id (+ optional checkpoint_key)
with torch_tensorrt.dynamo.low_memory(model_weights_on_meta=True) as low_mem:
    policy = PI05Policy(config).eval()
    pi05_recipe.store_in_bfloat16(policy)
    low_mem.map_weights(policy, "lerobot/pi05_base", checkpoint_key=pi05_checkpoint_key)
    ...

# 3. Compilation settings only, without weight mapping (default model_weights_on_meta=False)
with torch_tensorrt.dynamo.low_memory() as low_mem:
    trt_model = torch_tensorrt.dynamo.compile(
        exported, inputs=[example.cuda()], **low_mem.compile_settings
    )

(If you already have an allocated in-memory nn.Module and cannot construct from a config, calling low_mem.map_weights(model) with checkpoint=None writes its tensors to the cache file and frees the in-memory copy before compilation.)

Why from_config + model_weights_on_meta=True instead of from_pretrained?

  1. What happens if you load with from_pretrained and compile without low_memory:
    • Checkpoints that cast dtypes, convert keys, or target GPU (e.g., pi0.5's 14.5 GB float32 checkpoint cast to bfloat16, .bin files, or .to("cuda")): from_pretrained materializes all model weights in RAM/VRAM immediately during load, which OOMs small devices before compilation starts.
    • Same-dtype CPU safetensors checkpoints (like the bfloat16 Llama benchmark below): Hugging Face from_pretrained opens the shards via safetensors' internal read-only mmap. That makes from_pretrained return with near-zero initial weight RSS (no pages faulted in yet), but Torch-TensorRT cannot evict pages from safetensors' read-only mmap (resize_(0) fails on mmap storage, and only low_memory.map_weights registers copy-on-write mmaps for madvise page eviction). As TensorRT builds each engine, every weight it reads faults into host RSS and stays resident for the rest of the process.
  2. Why you should not call from_pretrained with low_memory:
    • Under torch.device("meta"), Hugging Face from_pretrained raises RuntimeError outright — and putting everything on torch.device("meta") (as 2.15's low_memory(model_fn, weights) did) also put computed non-persistent buffers on meta, failing compilation with 1 weights of the program are on the meta device, so they have no values: ['m.model.rotary_emb.inv_freq'].
    • Under model_weights_on_meta=True (parameter-only meta), from_pretrained still runs its checkpoint loading/casting work in host memory only for the meta hook to discard those parameters onto meta. Constructing via AutoModel.from_config(config) / Model(config) skips weight loading completely, keeps computed buffers real, and lets low_mem.map_weights(model) stream 64 MiB chunks into a tracked mmap whose pages are evicted after each engine build. (low_memory logs a warning if from_pretrained is used.)

Measured

The compile peak is set by building one engine, not by the model's size, so a large model compiles in less memory than its weights take.

Benchmark setup: a Llama-2-7B-shaped model in bfloat16 (hidden size 4096, MLP 11008, 32 heads; random bfloat16 weights saved as sharded Hugging Face safetensors) at 4, 9, and 20 layers on an A40 (TensorRT 11.4, warm timing cache), exported to ExecuTorch .pte:

  • low_memory (0.5 GiB engines): constructed via from_config inside low_memory(model_weights_on_meta=True) + low_mem.map_weights(model), exported on CPU, and compiled via compile_and_save with max_partition_size=512 MiB and **low_mem.compile_settings (offload_module_to_cpu=True, enable_resource_partitioning=True).
  • Default baseline (no low_memory, 1 whole engine): loaded via AutoModelForCausalLM.from_pretrained(..., dtype=torch.bfloat16) with default compilation settings (no low_memory, no enable_resource_partitioning, so the whole model builds as 1 engine): measured both with CPU compile_and_save and with stock GPU .cuda() + compile(...) + save(...). (An ablation adding the same 0.5 GiB resource partitioning to from_pretrained without low_memory is also shown to isolate weight eviction alone.)

Each peak is the highest host RSS + GPU memory at one instant from starting Python through saving the .pte:

Model weights low_memory(model_weights_on_meta=True) + from_config (0.5 GiB engines) Peak ÷ weights Default baseline (from_pretrained, 1 whole engine, CPU compile_and_save) Stock GPU baseline (from_pretrained.cuda() + compile + save, 1 whole engine) from_pretrained + same 0.5 GiB partitioning (no low_memory)
2.00 GiB (4 layers) 4.63 GiB 2.32× 8.85 GiB 11.12 GiB 5.72 GiB
3.88 GiB (9 layers) 4.64 GiB 1.20× 14.49 GiB 18.72 GiB 7.38 GiB
8.03 GiB (20 layers) 4.75 GiB 0.59× 26.99 GiB 35.37 GiB 11.79 GiB
  • Why low_memory stays flat (~4.7 GiB across 2–8 GiB models): host memory returns to ~1.7 GiB after every engine build. The peak is a single engine build: ~3.4 GiB of fixed overhead (Python/PyTorch/TensorRT libraries 1.7 GiB, TensorRT builder scratch 1.4 GiB, CUDA context 0.3 GiB) plus one partition's weights (~0.48 GiB) and serialized plan. Above ~4.7 GiB of weights, compilation uses less memory than the model's weights — whereas the default 1-engine baseline scales linearly at ~3.4–4.4× the weights (26.99 GiB / 35.37 GiB at 8.03 GiB).
  • Engine size: smaller engines lower the peak. On the 2.00 GiB model: 4.11 GiB with 0.25 GiB engines, 4.63 GiB with 0.5 GiB, 6.26 GiB with 1.0 GiB.
  • Cold timing cache: an empty TensorRT timing cache adds ~1–1.5 GiB of host tuning memory on A40 (6.08 GiB for the 2.00 GiB model, 5.71 GiB for the 8.03 GiB model).
  • Writing the weights file from the checkpoint peaked at 1.20–1.26 GiB of host memory at every model size.

Where the 8.03 GiB of weights appear by phase (peak host + GPU):

Phase low_memory(model_weights_on_meta=True) + from_config (17 × 0.5 GiB engines) Default baseline (from_pretrained, 1 whole engine, CPU compile_and_save) Stock GPU baseline (from_pretrained.cuda() + compile + save, 1 whole engine) How much of the 8.03 GiB weights is resident
Start Python, import torch & torch_tensorrt 1.10 GiB 1.10 GiB 1.10 GiB 0 GiB
Build (from_config on meta) or load (from_pretrained) 1.12 GiB 1.12 GiB* 10.45 GiB 0 GiB (meta) vs. 0 GiB faulted in yet* (CPU safetensors lazy mmap) vs. all 8.03 GiB on GPU (8.29 GiB VRAM + 2.16 GiB host)
Stream checkpoint to offloaded_weights (64 MiB chunks) 1.23 GiB – – ≤ 64 MiB chunk buffer; 0 GiB of mapped file faulted in
torch.export (reads shapes/metadata only) 1.51 GiB 1.17 GiB 9.59 GiB 0 GiB (low_memory / CPU mmap) vs. 8.03 GiB on GPU
Engine build (compile) 4.75 GiB (17 engines, 1 at a time) 26.99 GiB (1 whole engine) 35.37 GiB (1 whole engine) low_memory: ~0.48 GiB (1 engine's weights, evicted after each build). 1-engine baselines: all 8.03 GiB source weights + TensorRT whole-network builder host memory (18.40–18.71 GiB host) + whole built engine on GPU (8.59 GiB GPU; 16.66 GiB GPU when PyTorch weights are also on GPU)
Save the .pte 2.09 GiB 18.12 GiB → 10.13 GiB 34.14 GiB low_memory: 0 GiB weights resident (engines streamed from disk). CPU compile_and_save: all 8.03 GiB mmap weights remain pinned in RSS (10.13 GiB steady; 18.12 GiB peak while streaming the 8 GiB engine file). Stock GPU save: 8.03 GiB PyTorch GPU weights + 8 GiB loaded TRT GPU engine + host serialization copy

* Why CPU from_pretrained shows 1.12 GiB at load here: because the checkpoint is already stored in bfloat16 safetensors on CPU, from_pretrained only mmaps the 5 shard files at load time; all 8.03 GiB of pages fault into host RSS as soon as TensorRT reads the network weights (and stay pinned in RSS afterward because Torch-TensorRT cannot evict pages from safetensors' read-only mmap — even with 0.5 GiB resource partitioning enabled on from_pretrained, RSS still climbs to 11.79 GiB across engines 1–17). Moving the model to GPU (.cuda(), stock baseline) or casting dtypes on load (like pi0.5 float32 → bfloat16 below) materializes all weights immediately during load instead.

Benchmark script
import torch
import torch_tensorrt
from transformers import AutoConfig, AutoModelForCausalLM, LlamaConfig

# A checkpoint folder with random weights, standing in for a downloaded one.
config = LlamaConfig(
    hidden_size=4096, intermediate_size=11008, num_hidden_layers=20, num_attention_heads=32,
    num_key_value_heads=32, vocab_size=32000, tie_word_embeddings=False,
)
AutoModelForCausalLM.from_config(config, dtype=torch.bfloat16).save_pretrained("llama_8g", max_shard_size="2GB")


class Logits(torch.nn.Module):
    def __init__(self, model):
        super().__init__()
        self.model = model

    def forward(self, input_ids):
        return self.model(input_ids, use_cache=False).logits


# In a new process, so writing the checkpoint above doesn't count:
config = AutoConfig.from_pretrained("llama_8g")
with torch_tensorrt.dynamo.low_memory(model_weights_on_meta=True) as low_mem:
    model = AutoModelForCausalLM.from_config(config, dtype=torch.bfloat16).eval()
    low_mem.map_weights(model)
    input_ids = torch.randint(0, config.vocab_size, (1, 128))
    with torch.no_grad():
        exported = torch.export.export(Logits(model), (input_ids,))
    torch_tensorrt.compile_and_save(
        exported, "llama_8g.pte", output_format="executorch", arg_inputs=[input_ids],
        min_block_size=1, max_partition_size=512 << 20, **low_mem.compile_settings,
    )

Memory was sampled every 0.2 s from outside the process: the process's host RSS, and NVML device memory above idle.

End-to-end on lerobot/pi05_base (14.5 GB float32 checkpoint on Hub → 6.74 GiB bfloat16 policy weights, exported to ExecuTorch with compile_and_save):

  • Constructed from config inside low_memory(model_weights_on_meta=True) (PI05Policy(config) + low_mem.map_weights(policy, "lerobot/pi05_base", checkpoint_key=...)): streaming and casting the 14.5 GB float32 checkpoint into the 7.72 GiB cache file took 22 s and peaked at 2.00 GiB host + GPU (down from 15.29 GiB before switching checkpoint_source off safetensors.safe_open's mmap). Warm-cache compile + save of all three programs peaked at 5.49 GiB host + GPU (fits within an 8 GB budget), and the compiled TensorRT chunk matched the PyTorch reference to max abs error 0.0181 (tolerance 5). On a cold first run from an empty Hub cache, the Hub download peaked at 3.58 GiB (0.10 GiB with HF_HUB_DISABLE_XET=1).
  • Pre-loaded via PI05Policy.from_pretrained before low_memory(): loading + the harness's eager GPU reference run peaked at 23.67 GiB (14.57 GiB host + 9.32 GiB GPU) before low_memory ran — illustrating why small devices need model_weights_on_meta=True + config construction instead of from_pretrained. Calling low_mem.map_weights(policy) then streamed the 6.74 GiB of GPU weights to disk, dropped GPU usage from 9.32 GiB to 0.32 GiB, and kept the subsequent warm-cache compile + save peak at 5.51 GiB (5,644 MiB).

How it works

  • Opt-in parameter-only meta hook (model_weights_on_meta): register_module_parameter_registration_hook(_place_parameter_on_meta) is installed once at import and gated by a ContextVar (_meta_parameter_context) holding a WeakIdKeyDictionary so tied parameters stay tied and concurrent threads aren't disrupted. __enter__ sets _meta_parameter_context when model_weights_on_meta=True; map_weights, __exit__ (when model_weights_on_meta=True), and compiler entry points (pre_export_lowering / post_lowering via stop_placing_parameters_on_meta()) clear it so compilation never places internal parameters on meta even if map_weights was skipped. Calling from_pretrained under model_weights_on_meta=True logs a warning recommending from_config.
  • Checkpoint resolution & unmapped streaming: checkpoint accepts a .safetensors file, model.safetensors.index.json, a local folder containing either, or a Hugging Face Hub repo id (huggingface_hub imported lazily, checking try_to_load_from_cache before hf_hub_download for single or sharded repos). When checkpoint is omitted for a meta model, map_weights inspects model.config._name_or_path / model.name_or_path. checkpoint_source parses headers once and reads 64 MiB slices via unbuffered seek + readinto into fresh tensors so checkpoint pages never accumulate in RSS (and safetensors is no longer required for reading).
  • Pre-loaded models & external-holder warning: real tensors keep their Python identity via .data = view. StorageWeakRefs taken before mapping detect loaded storages kept alive outside model (such as a grad-enabled forward's autograd graph, state_dict copy, or optimizer) and log a warning when ≥ 1 MiB remains (ignoring tiny view bases like SigLIP's 2 KB expanded position_ids). Passing a from_pretrained-loaded model to map_weights also logs a warning recommending model_weights_on_meta=True + from_config to avoid initialization peak memory.
  • Cache file lifecycle & fsync: files live at <TMPDIR>/torch_tensorrt_<user>/offloaded_weights/weights_<pid>_<random>.safetensors (low_mem.weights_file), synced to disk with os.fsync before atomic rename so unified-memory boards (Jetson) don't start compilation with gigabytes of unreclaimable dirty pages. delete_file_when_unmapped attaches weakref.finalize to the mmap so the file is unlinked once no tensor views it or at exit, and _new_weights_file_path cleans up files left by dead PIDs. low_mem.map_weights raises NotImplementedError on Windows (which cannot unlink an open mmap), matching compile_and_save, while low_memory() without map_weights works on Windows too.

Docs: updated low_memory docstrings, docsrc/py_api/dynamo.rst, docsrc/tutorials/resource_memory/resource_management.rst, and examples/dynamo/compile_from_mapped_weights.py.

Names:

  • low_memory(model_fn, weights, ...) → low_memory(*, model_weights_on_meta=False, offload_module_to_cpu=None, enable_resource_partitioning=None, cpu_memory_budget=None, max_partition_size=None, release_weights_after_build=None) + low_mem.map_weights(model, checkpoint=None, *, checkpoint_key=None).
  • New attribute low_memory.weights_file.
  • New stop_placing_parameters_on_meta() and torch_tensorrt.dynamo.tools.weight_mapping.delete_file_when_unmapped(path); private _MetaParameterContext, _meta_parameter_context, _place_parameter_on_meta, _warn_if_called_from_pretrained, _warn_if_loaded_via_from_pretrained, _get_checkpoint_from_model_config, _weak_refs_to_storages, _new_weights_file_path, _remove_files_of_dead_processes, and _is_running in _low_memory.py; private _read_file_bytes, _resolve_checkpoint_path, _is_hub_repo_id, and _download_hub_checkpoint in weight_mapping.py; cache subdirectory offloaded_weights mirrors offloaded_engines.

Testing

C++ runtime, torch 2.16.0.dev20261029, TensorRT 11.4, A40:

  • tests/py/dynamo/models/test_low_memory.py + test_weight_mapping.py: 64 passed (model_weights_on_meta=False default & pure compile_settings compilation without map_weights, model_weights_on_meta=True parameter-only meta construction & tied weights, turning meta off at map_weights / compiler entry / early exception, from_pretrained warnings, model.config._name_or_path auto-discovery, Hub single & sharded repo-id resolution, unmapped chunked checkpoint reads, pre-loaded storage release & ≥ 1 MiB leak warning, GPU-to-CPU offload, TMPDIR full-disk error, dead-PID file cleanup, Windows guard, and end-to-end TensorRT compilation).
  • tests/py/dynamo/models/test_release_weights_after_build.py: 25 passed.
  • examples/dynamo/compile_from_mapped_weights.py: runs end-to-end (+0 MiB anonymous delta during meta construction, max abs diff 6.34e-06).
  • pre-commit run --files on all changed files: clean.

Type of change

  • Breaking change to an experimental API: low_memory
  • This change requires a documentation update (included)

Checklist:

  • My code follows the style guidelines of this project (You can use the linters)
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas and hacks
  • I have made corresponding changes to the documentation
  • I have added tests to verify my fix or my feature
  • New and existing unit tests pass locally with my changes
  • I have added the relevant labels to my PR in so that relevant reviewers are notified

@cehongwang cehongwang added this to the v2.16.0 milestone Nov 11, 2026
@cehongwang cehongwang added documentation Improvements or additions to documentation component: tests Issues re: Tests component: api [Python] Issues re: Python API component: dynamo Issues relating to the `torch.compile` or `torch._dynamo.export` paths labels Nov 11, 2026
@meta-cla meta-cla Bot added the cla signed label Nov 11, 2026
@github-actions
github-actions Bot requested a review from zewenli98 November 11, 2026 01:33
@github-actions github-actions Bot added the component: core Issues re: The core compiler label Nov 11, 2026
@cehongwang
cehongwang force-pushed the cehongw/low-memory-from-loaded-model branch from 56005cf to da97f6a Compare November 16, 2026 10:26
@cehongwang cehongwang changed the title feat(dynamo): low_memory takes the loaded model and moves its weights into a file feat(dynamo): single-block low_memory with map_weights, meta parameter creation, and Hub checkpoints Nov 16, 2026
@cehongwang
cehongwang force-pushed the cehongw/low-memory-from-loaded-model branch 2 times, most recently from d63743c to 4482b56 Compare November 16, 2026 13:41
@cehongwang cehongwang changed the title feat(dynamo): single-block low_memory with map_weights, meta parameter creation, and Hub checkpoints feat(dynamo): single-block low_memory with map_weights, model_weights_on_meta, and Hub checkpoints Nov 16, 2026
@github-actions github-actions Bot added the component: lowering Issues re: The lowering / preprocessing passes label Nov 16, 2026
@cehongwang
cehongwang force-pushed the cehongw/low-memory-from-loaded-model branch 2 times, most recently from 3568d7e to 19b23ac Compare November 17, 2026 07:32
@cehongwang
cehongwang marked this pull request as ready for review November 18, 2026 01:23
@cehongwang
cehongwang force-pushed the cehongw/low-memory-from-loaded-model branch from 19b23ac to 03285de Compare November 18, 2026 01:56
…_on_meta, and Hub checkpoints

Redesign experimental `low_memory` for 2.16 so model construction, checkpoint
streaming, and compilation happen in one block without manual safetensors dumps:

- `with low_memory(*, model_weights_on_meta=False, ...) as low_mem:` provides
  `compile_settings` (`offload_module_to_cpu`, `enable_resource_partitioning`,
  `cpu_memory_budget`, `max_partition_size`, `release_weights_after_build`),
  with CPU offload and resource partitioning on unless set. By default
  (`model_weights_on_meta=False`), model construction is untouched so
  `compile_settings` can be used without `map_weights` (including on Windows).
  With `model_weights_on_meta=True`, entering installs a ContextVar-gated
  parameter registration hook that places newly registered `nn.Parameter`
  tensors on `meta` (preserving tied weights) while keeping buffers real (e.g.
  rotary `inv_freq`), and warns if `from_pretrained` is called instead of
  `from_config`.
- `low_mem.map_weights(model, checkpoint=None, *, checkpoint_key=None)` turns
  `meta` parameter creation off before compilation (and `pre_export_lowering` /
  `post_lowering` also call `stop_placing_parameters_on_meta()` if `map_weights`
  was skipped), resolves `checkpoint` (local file/index/folder, Hugging Face Hub
  repo id via `huggingface_hub`, or `model.config._name_or_path` when omitted),
  streams 64 MiB chunks into `<TMPDIR>/torch_tensorrt_<user>/offloaded_weights/`,
  and maps zero-copy views onto `model`. Also offloads already-loaded models and
  warns (>= 1 MiB) when external references hold loaded storages.
- `checkpoint_source` reads safetensors chunks via unbuffered file reads instead
  of `safetensors.safe_open` mmap so checkpoint pages do not accumulate in RSS
  (pi0.5 14.5 GB checkpoint conversion: 15.29 -> 2.00 GiB host + GPU).
- `save_weights_for_mapping` calls `os.fsync` before renaming, and
  `delete_file_when_unmapped` unlinks the cache file when its mmap is finalized
  (plus dead-PID cleanup on entry).

Names:
- `low_memory(model_fn, weights, ...)` ->
  `low_memory(*, model_weights_on_meta=False, ...)` +
  `low_mem.map_weights(model, checkpoint=None, *, checkpoint_key=None)`
- New attribute `low_memory.weights_file` and argument
  `low_memory(max_partition_size=...)`, passed through to `compile`
- New `stop_placing_parameters_on_meta()` and
  `weight_mapping.delete_file_when_unmapped`; private `_MetaParameterContext`,
  `_meta_parameter_context`, `_place_parameter_on_meta`,
  `_warn_if_called_from_pretrained`, `_warn_if_loaded_via_from_pretrained`,
  `_get_checkpoint_from_model_config`, `_weak_refs_to_storages`,
  `_new_weights_file_path`, `_remove_files_of_dead_processes`, `_is_running`,
  `_read_file_bytes`, `_resolve_checkpoint_path`, `_is_hub_repo_id`,
  `_download_hub_checkpoint`

Part of #5001.
@cehongwang
cehongwang force-pushed the cehongw/low-memory-from-loaded-model branch from 03285de to c52a10e Compare November 18, 2026 02:00

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cla signed component: api [Python] Issues re: Python API component: core Issues re: The core compiler component: dynamo Issues relating to the `torch.compile` or `torch._dynamo.export` paths component: lowering Issues re: The lowering / preprocessing passes component: tests Issues re: Tests documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant