Using CUDA streams in PyTorch allows you to parallelize operations on the GPU, enabling concurrent execution of independent tasks. This can improve performance by overlapping computation, memory transfers, and other operations. Below is a step-by-step guide to using CUDA streams in PyTorch to parallelize tasks.
Key Concepts
CUDA Streams: A CUDA stream is a sequence of operations that execute in order on the GPU. By default, all operations in PyTorch are executed in the default stream. You can create additional streams to run operations concurrently, provided they are independent.
Parallelization: To achieve parallelism, you need to assign independent tasks to different streams. For example, you can run multiple models, process different batches, or overlap data transfers with computation.
Synchronization: Streams must be synchronized when you need to ensure that operations in different streams have completed before proceeding (e.g., when combining results).
Steps to Use CUDA Streams in PyTorch
1. Check for CUDA Availability
Ensure that your system has a CUDA-capable GPU and that PyTorch is installed with CUDA support.
python
import torch
# Check if CUDA is available
if not torch.cuda.is_available():
raise RuntimeError("CUDA is not available. Please check your setup.")
2. Create CUDA Streams
You can create multiple CUDA streams using torch.cuda.Stream. Each stream can execute operations independently of others.
python
# Create two CUDA streams
stream1 = torch.cuda.Stream()
stream2 = torch.cuda.Stream()
3. Assign Operations to Streams
To execute operations in a specific stream, use the with torch.cuda.stream(stream) context manager. Operations within this context will be queued in the specified stream.
python
# Example: Parallelize two matrix multiplications
A1 = torch.randn(1000, 1000, device="cuda")
B1 = torch.randn(1000, 1000, device="cuda")
A2 = torch.randn(1000, 1000, device="cuda")
B2 = torch.randn(1000, 1000, device="cuda")
# Perform matrix multiplication in stream1
with torch.cuda.stream(stream1):
C1 = torch.matmul(A1, B1)
# Perform matrix multiplication in stream2
with torch.cuda.stream(stream2):
C2 = torch.matmul(A2, B2)
In this example, the two matrix multiplications (C1 and C2) can run concurrently because they are assigned to different streams and are independent.
4. Synchronize Streams
If you need to ensure that operations in all streams have completed (e.g., before accessing results), you can synchronize the streams using torch.cuda.synchronize() or stream.synchronize().
python
# Synchronize all streams (wait for all operations to complete)
torch.cuda.synchronize()
# Now it is safe to access C1 and C2
print(C1)
print(C2)
Alternatively, you can synchronize a specific stream if you only need to wait for operations in that stream to complete:
python
stream1.synchronize() # Wait for operations in stream1 to complete
stream2.synchronize() # Wait for operations in stream2 to complete
5. Overlap Data Transfers and Computation
CUDA streams are particularly useful for overlapping data transfers (e.g., host-to-device or device-to-host) with computation. To achieve this, use non-blocking data transfers (non_blocking=True) and assign operations to different streams.
python
# Example: Overlap data transfer and computation
data1 = torch.randn(10000, 10000)
data2 = torch.randn(10000, 10000)
# Create CUDA tensors with non-blocking transfers
with torch.cuda.stream(stream1):
data1_gpu = data1.to("cuda", non_blocking=True)
result1 = data1_gpu * 2 # Computation in stream1
with torch.cuda.stream(stream2):
data2_gpu = data2.to("cuda", non_blocking=True)
result2 = data2_gpu * 3 # Computation in stream2
# Synchronize before accessing results
torch.cuda.synchronize()
print(result1)
print(result2)
In this example, the data transfers (to("cuda")) and computations (* 2 and * 3) can overlap because they are in different streams and the transfers are non-blocking.
6. Use Streams in a Training Loop
In a training loop, you can use streams to parallelize operations such as data loading, forward passes, and backward passes for different batches or models. Below is an example of using streams to process two batches in parallel:
python
import torch.nn as nn
import torch.optim as optim
# Define a simple model
model = nn.Linear(10, 10).cuda()
optimizer = optim.SGD(model.parameters(), lr=0.01)
criterion = nn.MSELoss()
# Create two streams
stream1 = torch.cuda.Stream()
stream2 = torch.cuda.Stream()
# Example data (two batches)
batch1_input = torch.randn(32, 10, device="cuda")
batch1_target = torch.randn(32, 10, device="cuda")
batch2_input = torch.randn(32, 10, device="cuda")
batch2_target = torch.randn(32, 10, device="cuda")
# Process batch1 in stream1
with torch.cuda.stream(stream1):
optimizer.zero_grad()
output1 = model(batch1_input)
loss1 = criterion(output1, batch1_target)
loss1.backward()
optimizer.step()
# Process batch2 in stream2
with torch.cuda.stream(stream2):
optimizer.zero_grad()
output2 = model(batch2_input)
loss2 = criterion(output2, batch2_target)
loss2.backward()
optimizer.step()
# Synchronize streams
torch.cuda.synchronize()
print("Training complete for both batches.")
Note: In this example, the two batches are processed in parallel, but the optimizer updates the same model parameters, so you need to be careful about race conditions. For true parallelism, you might want to use separate models or ensure that operations are independent.
7. Profile Your Code
To verify that your operations are truly running in parallel, use PyTorch's built-in profiler or NVIDIA's profiling tools (e.g., Nsight Systems or Visual Profiler). Here's an example of using PyTorch's profiler:
python
from torch.profiler import profile, record_function, ProfilerActivity
with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof:
with record_function("stream1"):
with torch.cuda.stream(stream1):
C1 = torch.matmul(A1, B1)
with record_function("stream2"):
with torch.cuda.stream(stream2):
C2 = torch.matmul(A2, B2)
torch.cuda.synchronize()
# Print profiling results
print(prof.key_averages().table(sort_by="cuda_time_total"))
This will show you the timeline of operations and help you confirm that tasks are overlapping as expected.
Important Considerations
Independence of Tasks: Streams can only parallelize tasks that are independent. If one task depends on the output of another, they must be executed sequentially or synchronized appropriately.
Resource Limits: The degree of parallelism is limited by the GPU's resources (e.g., number of SMs, memory bandwidth). Overusing streams can lead to resource contention and reduced performance.
Default Stream: Operations not explicitly assigned to a stream will run in the default stream. Be cautious, as this can introduce implicit synchronization points.
Non-Blocking Transfers: Use non_blocking=True for data transfers to allow overlap with computation.
Synchronization Overhead: Excessive synchronization can negate the benefits of parallelism. Use synchronization only when necessary.
Example Use Cases
Data Loading and Preprocessing: Use streams to overlap data loading/preprocessing with model training.
Multi-Model Inference: Run inference for multiple models in parallel.
Multi-Batch Processing: Process multiple batches of data in parallel (e.g., in reinforcement learning or distributed training).
Conclusion
Using CUDA streams in PyTorch is a powerful way to parallelize GPU operations and improve performance. By carefully assigning independent tasks to different streams, overlapping data transfers with computation, and profiling your code, you can achieve significant speedups. However, always ensure that your tasks are truly independent and that you are not introducing unnecessary synchronization or resource contention.