Skip to main content

1. What is Performance Profiling?

Performance profiling means analyzing how much time and resources a program spends during execution. For a PyTorch model, profiling can help identify:
  • Slow operations
  • CPU usage
  • GPU usage
  • Memory usage
  • Training bottlenecks
  • Inference bottlenecks

2. What is a Bottleneck?

A bottleneck is a part of the program that takes significantly more time or resources than other parts. Example:
The backward pass is the main bottleneck.

3. PyTorch Profiler

PyTorch provides torch.profiler for analyzing model performance. Import:
The profiler can record operations using:
It can measure CPU and CUDA operations.

4. Profiling Training

A typical training loop is:
The profiler can measure each part.

5. Profiling Inference

Inference does not require gradient calculation.
The profiler can identify which model operations consume the most time.

6. Basic Profiler Example

After profiling:
This displays performance statistics.

7. Important Profiler Metrics

CPU Time

Time spent executing an operation on the CPU.

CUDA Time

Time spent executing an operation on a CUDA GPU.

Self CPU Time

Time spent directly inside an operation without including child operations.

Calls

Number of times an operation was executed. Example:

8. DQN Training Loop

The DQN example from the previous topic contains:
Profiling helps determine which operations consume the most execution time.

9. profile_demo.py

This is a small profiling example based on the DQN training concept:
Output:

10. Install Dependencies

Run:
The profiler will produce a table similar to:
The exact values depend on the computer and PyTorch version.

11. Understanding the Profiler Code

Start profiler

Starts collecting performance information.

Record tensor shapes

Records the shapes of tensors used by operations. This can help identify operations working with unexpectedly large tensors.

Get profiling results

Groups operations with the same name.

Sort by execution time

Places operations with the highest CPU execution time first.

Limit results

Displays the top 10 operations.

12. Finding the Bottleneck

Suppose the profiler shows:
The biggest operation is:
Therefore:
This helps determine where optimization should be focused.

13. Profiling Workflow

Profiling should be repeated after optimization to verify that performance actually improved.

14. CPU vs GPU Profiling

For CPU-only profiling:
For a CUDA system:
This allows CPU and GPU operations to be analyzed together.

15. Profiling Training vs Inference

Training

Training usually requires more computation because gradients must be calculated.

Inference

Inference normally does not require backpropagation.

16. Main Learning

Key takeaway

PyTorch Profiler helps identify which operations consume the most time and resources, making it easier to optimize training and inference performance.