Skip to content
This repository was archived by the owner on Jan 21, 2026. It is now read-only.

[Perf] Performance improvement in multi-cpu environments - #88

Merged
0oshowero0 merged 1 commit into
TransferQueue:devfrom
0oshowero0:han/fix_pytorch_auto_parallel_performance
Oct 27, 2025
Merged

0oshowero0 merged 1 commit into
TransferQueue:devfrom
0oshowero0:han/fix_pytorch_auto_parallel_performance

Conversation

@0oshowero0

Copy link
Copy Markdown
Member

Background

We observe significant performance variance in the torch.stack() operation under a multi-CPU environment. By default, PyTorch enables automatic parallelism using all available CPU resources, which may introduce excessive synchronization overhead.

On a 640-CPU server, the following code takes 5–11 seconds to complete. By uncommenting the line torch.set_num_threads(5), the execution time is reduced to 0.13–0.46 seconds.

import torch
import time

def create_fixed_tensor_list(num_tensors=4096, tensor_length=40960, dtype=torch.float32, device="cpu"):
    fixed_value = 1.0
    tensor_list = []
    for i in range(num_tensors):
        tensor = torch.full((tensor_length,), fixed_value, dtype=dtype, device=device)
        tensor_list.append(tensor)
    return tensor_list


def benchmark_stack_operations(tensor_list):
    # torch.set_num_threads(5)  # using a smaller number will greatly improve the performance
    start_time = time.time()
    torch.stack(tensor_list)
    end_time = time.time()
    elapsed = end_time - start_time
    print(f"Run: {elapsed:.4f} seconds")


def main():
    print("=== torch.stack Performance Benchmark ===")

    num_tensors = 4096
    tensor_length = 40960

    device = "cpu"
    print(f"Using device: {device}")

    tensor_list = create_fixed_tensor_list(
        num_tensors=num_tensors,
        tensor_length=tensor_length,
        device=device
    )

    benchmark_stack_operations(tensor_list)


if __name__ == "__main__":
    main()

Solution

We provide a context manager limit_pytorch_auto_parallel_threads() that can be used to wrap code fragments involving torch.stack(), helping improve performance.

@0oshowero0
0oshowero0 requested a review from Copilot October 25, 2025 08:13

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR introduces a performance optimization for PyTorch operations in multi-CPU environments by limiting automatic parallelism. The change addresses a specific issue where torch.stack() operations suffer from excessive synchronization overhead when PyTorch uses all available CPU threads on high-core-count servers (e.g., 640 CPUs).

Key changes:

  • Added a context manager limit_pytorch_auto_parallel_threads() to control PyTorch's thread usage
  • Applied the context manager to wrap torch.stack() operations in the data retrieval path

Reviewed Changes

Copilot reviewed 2 out of 3 changed files in this pull request and generated 3 comments.

File Description
transfer_queue/utils/utils.py Implements the new context manager with automatic thread count detection based on physical cores
transfer_queue/storage.py Applies the performance optimization by wrapping torch.stack operations with the new context manager

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

"""Prevent PyTorch from overdoing the automatic parallelism during torch.stack() operation"""
pytorch_current_num_threads = torch.get_num_threads()
logical_cores = psutil.cpu_count(logical=True)
physical_cores = psutil.cpu_count(logical=False)

Copilot AI Oct 25, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The function may crash if psutil.cpu_count(logical=False) returns None on systems where physical core count cannot be determined. Add a None check and fallback to logical cores or raise a more informative error.

Suggested change
physical_cores = psutil.cpu_count(logical=False)
physical_cores = psutil.cpu_count(logical=False)
if physical_cores is None:
# Fallback: use logical cores if physical core count cannot be determined
physical_cores = logical_cores

Copilot uses AI. Check for mistakes.
Comment on lines +113 to +116
if physical_cores >= 16:
target_num_threads = 16
else:
target_num_threads = physical_cores

Copilot AI Oct 25, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If physical_cores is None (which can happen on some systems), this comparison will fail. The None check from Comment 1 would prevent this, but this logic also needs to handle the case defensively.

Suggested change
if physical_cores >= 16:
target_num_threads = 16
else:
target_num_threads = physical_cores
if physical_cores is not None:
if physical_cores >= 16:
target_num_threads = 16
else:
target_num_threads = physical_cores
else:
# Fallback: use logical_cores if physical_cores is unavailable
if logical_cores is not None:
if logical_cores >= 16:
target_num_threads = 16
else:
target_num_threads = logical_cores
else:
# As a last resort, use 1
target_num_threads = 1

Copilot uses AI. Check for mistakes.

@contextmanager
def limit_pytorch_auto_parallel_threads(target_num_threads: Optional[int] = None):
"""Prevent PyTorch from overdoing the automatic parallelism during torch.stack() operation"""

Copilot AI Oct 25, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The docstring lacks important information about parameters, return values, usage examples, and the rationale for the default threshold of 16 cores. Consider adding a comprehensive docstring with Args, Yields, and Raises sections, plus an example showing how to use this context manager.

Suggested change
"""Prevent PyTorch from overdoing the automatic parallelism during torch.stack() operation"""
"""
Context manager to limit the number of threads used by PyTorch for automatic parallelism,
particularly during operations like `torch.stack()`. This can help prevent excessive CPU
usage and contention on machines with many cores.
By default, if `target_num_threads` is not specified, the function sets the number of threads
to 16 if the machine has at least 16 physical cores. This threshold is chosen because, on
high-core-count machines, PyTorch's default behavior can lead to oversubscription and
performance degradation. If there are fewer than 16 physical cores, all available physical
cores are used.
Args:
target_num_threads (Optional[int]): The number of threads to set for PyTorch operations.
If None, defaults to 16 if there are at least 16 physical cores, otherwise uses the
number of physical cores.
Yields:
None. This is a context manager; code inside the `with` block will run with the specified
number of PyTorch threads.
Raises:
RuntimeError: If `target_num_threads` is greater than the number of logical CPU cores.
Example:
>>> from transfer_queue.utils.utils import limit_pytorch_auto_parallel_threads
>>> import torch
>>> with limit_pytorch_auto_parallel_threads(8):
... # PyTorch will use at most 8 threads in this block
... x = torch.stack([torch.ones(10) for _ in range(1000)])
# After the block, the original thread setting is restored.
"""

Copilot uses AI. Check for mistakes.
@0oshowero0
0oshowero0 merged commit 9ff2fa5 into TransferQueue:dev Oct 27, 2025
@0oshowero0
0oshowero0 deleted the han/fix_pytorch_auto_parallel_performance branch October 29, 2025 06:12
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants