Repository navigation
[None][perf] Run the weight load on more torch CPU threads on request #21835
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ziyixiong-nv
wants to merge
3
commits into
NVIDIA:main
Choose a base branch
from
ziyixiong-nv:user/fxiong/load-threads
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+160
−7
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
98 changes: 98 additions & 0 deletions
98
tests/unittest/_torch/pyexecutor/test_model_loader_load_threads.py
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| """TLLM_WEIGHT_LOAD_THREADS: a real checkpoint loads to the same bytes on more torch threads.""" | ||
|
|
||
| import os | ||
|
|
||
| import pytest | ||
| import torch | ||
| from transformers import LlamaConfig | ||
| from transformers import LlamaForCausalLM as HFLlamaForCausalLM | ||
|
|
||
| from tensorrt_llm._torch.models.modeling_llama import LlamaForCausalLM | ||
| from tensorrt_llm._torch.modules.linear import Linear | ||
| from tensorrt_llm._torch.pyexecutor.model_loader import ModelLoader, construct_checkpoint_loader | ||
| from tensorrt_llm.llmapi.llm_args import TorchLlmArgs | ||
| from tensorrt_llm.mapping import Mapping | ||
|
|
||
|
|
||
| def _load(checkpoint_dir: str, monkeypatch: pytest.MonkeyPatch, load_threads: str | None): | ||
| """Load the checkpoint; return every tensor's bytes and the thread counts the loads ran with.""" | ||
| seen = {"model": set(), "modules": set()} | ||
| model_load = LlamaForCausalLM.load_weights | ||
| module_load = Linear.load_weights | ||
|
|
||
| def load_model(self, weights, weight_mapper=None, params_map=None, allow_partial_loading=False): | ||
| seen["model"].add(torch.get_num_threads()) | ||
| model_load( | ||
| self, | ||
| weights, | ||
| weight_mapper=weight_mapper, | ||
| params_map=params_map, | ||
| allow_partial_loading=allow_partial_loading, | ||
| ) | ||
|
|
||
| def load_module(self, weights, allow_partial_loading=False): | ||
| seen["modules"].add(torch.get_num_threads()) | ||
| module_load(self, weights, allow_partial_loading=allow_partial_loading) | ||
|
|
||
| with monkeypatch.context() as patch: | ||
| if load_threads is None: | ||
| patch.delenv("TLLM_WEIGHT_LOAD_THREADS", raising=False) | ||
| else: | ||
| patch.setenv("TLLM_WEIGHT_LOAD_THREADS", load_threads) | ||
| patch.setattr(LlamaForCausalLM, "load_weights", load_model) | ||
| patch.setattr(Linear, "load_weights", load_module) | ||
| loader = ModelLoader( | ||
| llm_args=TorchLlmArgs(model=checkpoint_dir), | ||
| mapping=Mapping(), | ||
| spec_config=None, | ||
| sparse_attention_config=None, | ||
| max_num_tokens=64, | ||
| max_seq_len=64, | ||
| ) | ||
| model, _ = loader.load(checkpoint_dir, construct_checkpoint_loader(None, "HF")) | ||
| tensors = dict(model.named_parameters()) | ||
| tensors.update((f"buffer:{name}", buf) for name, buf in model.named_buffers()) | ||
| data = { | ||
| name: t.detach().cpu().contiguous().view(-1).view(torch.uint8) | ||
| for name, t in tensors.items() | ||
| } | ||
| return data, seen | ||
|
|
||
|
|
||
| @pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a GPU") | ||
| def test_load_threads_same_bytes_and_restored(tmp_path, monkeypatch): | ||
| """Unset keeps 1 thread; N raises model.load_weights only, and 1 is back after the load.""" | ||
| # Skip on the native backend only; if the loader stops seeing OpenMP, this fails. | ||
| if "ATen parallel backend: native" in torch.__config__.parallel_info(): | ||
| pytest.skip("torch's native backend keeps one thread count per process") | ||
| config = LlamaConfig( | ||
| hidden_size=256, | ||
| intermediate_size=768, | ||
| num_hidden_layers=2, | ||
| num_attention_heads=4, | ||
| num_key_value_heads=2, | ||
| vocab_size=1024, | ||
| max_position_embeddings=64, | ||
| ) | ||
| torch.manual_seed(0) | ||
| HFLlamaForCausalLM(config).to(torch.bfloat16).save_pretrained(tmp_path) | ||
| monkeypatch.delenv("TRT_LLM_DISABLE_LOAD_WEIGHTS_IN_PARALLEL", raising=False) | ||
| raised = min(4, len(os.sched_getaffinity(0))) | ||
| saved = torch.get_num_threads() | ||
| # Start like a worker launched with OMP_NUM_THREADS=1. | ||
| torch.set_num_threads(1) | ||
| try: | ||
| off, off_threads = _load(str(tmp_path), monkeypatch, None) | ||
| assert torch.get_num_threads() == 1 | ||
| on, on_threads = _load(str(tmp_path), monkeypatch, "4") | ||
| assert torch.get_num_threads() == 1 | ||
| finally: | ||
| torch.set_num_threads(saved) | ||
|
|
||
| assert off_threads == {"model": {1}, "modules": {1}} | ||
| assert on_threads == {"model": {raised}, "modules": {1}} | ||
|
ziyixiong-nv marked this conversation as resolved.
Resolved
|
||
| assert off.keys() == on.keys() | ||
| for name, data in off.items(): | ||
| assert torch.equal(data, on[name]), name | ||
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.