Repository navigation
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
Open
feat(dynamo): single-block low_memory with map_weights, model_weights_on_meta, and Hub checkpoints#5005cehongwang wants to merge 1 commit into
cehongwang wants to merge 1 commit into
Conversation
cehongwang
force-pushed
the
cehongw/low-memory-from-loaded-model
branch
from
November 16, 2026 10:26
56005cf to
da97f6a
Compare
cehongwang
force-pushed
the
cehongw/low-memory-from-loaded-model
branch
2 times, most recently
from
November 16, 2026 13:41
d63743c to
4482b56
Compare
cehongwang
force-pushed
the
cehongw/low-memory-from-loaded-model
branch
2 times, most recently
from
November 17, 2026 07:32
3568d7e to
19b23ac
Compare
cehongwang
marked this pull request as ready for review
November 18, 2026 01:23
cehongwang
force-pushed
the
cehongw/low-memory-from-loaded-model
branch
from
November 18, 2026 01:56
19b23ac to
03285de
Compare
…_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
force-pushed
the
cehongw/low-memory-from-loaded-model
branch
from
November 18, 2026 02:00
03285de to
c52a10e
Compare
6 of 7 tasks
This branch has not been deployed
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.
Description
low_memorynow runs model construction, weight streaming, and compilation inside a singlewithblock — users no longer build separatesave_weights_for_mappingscripts, wrap model constructors in lambdas, or manage a secondmetacontext 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, andmax_partition_sizefixes the engine size instead of deriving it from free memory. Withmodel_weights_on_meta=True, entering places newly registerednn.Parametertensors onmetawhile keeping computed buffers real (such as rotaryinv_freq), andoffload_module_to_cpustays on even when set toFalse, 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 solow_mem.compile_settingscan be used on its own withoutmap_weights.low_mem.map_weights(model, checkpoint=None, *, checkpoint_key=None)immediately turnsmetaparameter creation off (and compiler entry points also callstop_placing_parameters_on_meta()automatically ifmap_weightswas 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 pointsmodel's tensors at zero-copy views of that file.Three ways to use
low_memory:(If you already have an allocated in-memory
nn.Moduleand cannot construct from a config, callinglow_mem.map_weights(model)withcheckpoint=Nonewrites its tensors to the cache file and frees the in-memory copy before compilation.)Why
from_config+model_weights_on_meta=Trueinstead offrom_pretrained?from_pretrainedand compile withoutlow_memory:pi0.5's 14.5 GB float32 checkpoint cast to bfloat16,.binfiles, or.to("cuda")):from_pretrainedmaterializes all model weights in RAM/VRAM immediately during load, which OOMs small devices before compilation starts.from_pretrainedopens the shards viasafetensors' internal read-onlymmap. That makesfrom_pretrainedreturn with near-zero initial weight RSS (no pages faulted in yet), but Torch-TensorRT cannot evict pages fromsafetensors' read-only mmap (resize_(0)fails on mmap storage, and onlylow_memory.map_weightsregisters copy-on-write mmaps formadvisepage eviction). As TensorRT builds each engine, every weight it reads faults into host RSS and stays resident for the rest of the process.from_pretrainedwithlow_memory:torch.device("meta"), Hugging Facefrom_pretrainedraisesRuntimeErroroutright — and putting everything ontorch.device("meta")(as 2.15'slow_memory(model_fn, weights)did) also put computed non-persistent buffers onmeta, failing compilation with1 weights of the program are on the meta device, so they have no values: ['m.model.rotary_emb.inv_freq'].model_weights_on_meta=True(parameter-onlymeta),from_pretrainedstill runs its checkpoint loading/casting work in host memory only for themetahook to discard those parameters ontometa. Constructing viaAutoModel.from_config(config)/Model(config)skips weight loading completely, keeps computed buffers real, and letslow_mem.map_weights(model)stream 64 MiB chunks into a tracked mmap whose pages are evicted after each engine build. (low_memorylogs a warning iffrom_pretrainedis 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 GiBengines): constructed viafrom_configinsidelow_memory(model_weights_on_meta=True)+low_mem.map_weights(model), exported on CPU, and compiled viacompile_and_savewithmax_partition_size=512 MiBand**low_mem.compile_settings(offload_module_to_cpu=True,enable_resource_partitioning=True).low_memory, 1 whole engine): loaded viaAutoModelForCausalLM.from_pretrained(..., dtype=torch.bfloat16)with default compilation settings (nolow_memory, noenable_resource_partitioning, so the whole model builds as 1 engine): measured both with CPUcompile_and_saveand with stock GPU.cuda()+compile(...)+save(...). (An ablation adding the same 0.5 GiB resource partitioning tofrom_pretrainedwithoutlow_memoryis 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:low_memory(model_weights_on_meta=True)+from_config(0.5 GiB engines)from_pretrained, 1 whole engine, CPUcompile_and_save)from_pretrained.cuda()+compile+save, 1 whole engine)from_pretrained+ same 0.5 GiB partitioning (nolow_memory)low_memorystays 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 GiBat 8.03 GiB).Where the 8.03 GiB of weights appear by phase (peak host + GPU):
low_memory(model_weights_on_meta=True)+from_config(17 × 0.5 GiB engines)from_pretrained, 1 whole engine, CPUcompile_and_save)from_pretrained.cuda()+compile+save, 1 whole engine)torch&torch_tensorrtfrom_configonmeta) or load (from_pretrained)meta) vs. 0 GiB faulted in yet* (CPU safetensors lazy mmap) vs. all 8.03 GiB on GPU (8.29 GiBVRAM +2.16 GiBhost)offloaded_weights(64 MiB chunks)torch.export(reads shapes/metadata only)low_memory/ CPU mmap) vs. 8.03 GiB on GPUcompile)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 GiBhost) + whole built engine on GPU (8.59 GiBGPU;16.66 GiBGPU when PyTorch weights are also on GPU).ptelow_memory: 0 GiB weights resident (engines streamed from disk). CPUcompile_and_save: all 8.03 GiB mmap weights remain pinned in RSS (10.13 GiBsteady;18.12 GiBpeak while streaming the 8 GiB engine file). Stock GPUsave: 8.03 GiB PyTorch GPU weights + 8 GiB loaded TRT GPU engine + host serialization copy* Why CPU
from_pretrainedshows1.12 GiBat load here: because the checkpoint is already stored inbfloat16safetensors on CPU,from_pretrainedonly 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 fromsafetensors' read-only mmap — even with 0.5 GiB resource partitioning enabled onfrom_pretrained, RSS still climbs to11.79 GiBacross engines 1–17). Moving the model to GPU (.cuda(), stock baseline) or casting dtypes on load (likepi0.5float32 → bfloat16 below) materializes all weights immediately during load instead.Benchmark script
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 withcompile_and_save):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 switchingcheckpoint_sourceoffsafetensors.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 withHF_HUB_DISABLE_XET=1).PI05Policy.from_pretrainedbeforelow_memory(): loading + the harness's eager GPU reference run peaked at 23.67 GiB (14.57 GiBhost +9.32 GiBGPU) beforelow_memoryran — illustrating why small devices needmodel_weights_on_meta=True+ config construction instead offrom_pretrained. Callinglow_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
metahook (model_weights_on_meta):register_module_parameter_registration_hook(_place_parameter_on_meta)is installed once at import and gated by aContextVar(_meta_parameter_context) holding aWeakIdKeyDictionaryso tied parameters stay tied and concurrent threads aren't disrupted.__enter__sets_meta_parameter_contextwhenmodel_weights_on_meta=True;map_weights,__exit__(whenmodel_weights_on_meta=True), and compiler entry points (pre_export_lowering/post_loweringviastop_placing_parameters_on_meta()) clear it so compilation never places internal parameters onmetaeven ifmap_weightswas skipped. Callingfrom_pretrainedundermodel_weights_on_meta=Truelogs a warning recommendingfrom_config.checkpointaccepts a.safetensorsfile,model.safetensors.index.json, a local folder containing either, or a Hugging Face Hub repo id (huggingface_hubimported lazily, checkingtry_to_load_from_cachebeforehf_hub_downloadfor single or sharded repos). Whencheckpointis omitted for ametamodel,map_weightsinspectsmodel.config._name_or_path/model.name_or_path.checkpoint_sourceparses headers once and reads 64 MiB slices via unbufferedseek+readintointo fresh tensors so checkpoint pages never accumulate in RSS (andsafetensorsis no longer required for reading)..data = view.StorageWeakRefs taken before mapping detect loaded storages kept alive outsidemodel(such as a grad-enabled forward's autograd graph,state_dictcopy, or optimizer) and log a warning when ≥ 1 MiB remains (ignoring tiny view bases like SigLIP's 2 KB expandedposition_ids). Passing afrom_pretrained-loaded model tomap_weightsalso logs a warning recommendingmodel_weights_on_meta=True+from_configto avoid initialization peak memory.fsync: files live at<TMPDIR>/torch_tensorrt_<user>/offloaded_weights/weights_<pid>_<random>.safetensors(low_mem.weights_file), synced to disk withos.fsyncbefore atomic rename so unified-memory boards (Jetson) don't start compilation with gigabytes of unreclaimable dirty pages.delete_file_when_unmappedattachesweakref.finalizeto themmapso the file is unlinked once no tensor views it or at exit, and_new_weights_file_pathcleans up files left by dead PIDs.low_mem.map_weightsraisesNotImplementedErroron Windows (which cannot unlink an open mmap), matchingcompile_and_save, whilelow_memory()withoutmap_weightsworks on Windows too.Docs: updated
low_memorydocstrings,docsrc/py_api/dynamo.rst,docsrc/tutorials/resource_memory/resource_management.rst, andexamples/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).low_memory.weights_file.stop_placing_parameters_on_meta()andtorch_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_runningin_low_memory.py; private_read_file_bytes,_resolve_checkpoint_path,_is_hub_repo_id, and_download_hub_checkpointinweight_mapping.py; cache subdirectoryoffloaded_weightsmirrorsoffloaded_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=Falsedefault & purecompile_settingscompilation withoutmap_weights,model_weights_on_meta=Trueparameter-onlymetaconstruction & tied weights, turningmetaoff atmap_weights/ compiler entry / early exception,from_pretrainedwarnings,model.config._name_or_pathauto-discovery, Hub single & sharded repo-id resolution, unmapped chunked checkpoint reads, pre-loaded storage release & ≥ 1 MiB leak warning, GPU-to-CPU offload,TMPDIRfull-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 duringmetaconstruction, max abs diff6.34e-06).pre-commit run --fileson all changed files: clean.Type of change
low_memoryChecklist: