This program checks if CUDA is available and prints the GPU name if yes, otherwise says CPU is used.
PyTorch
import torch
def check_cuda():
if torch.cuda.is_available():
print('CUDA is available!')
print(f'GPU device name: {torch.cuda.get_device_name(0)}')
else:
print('CUDA is not available. Using CPU.')
check_cuda()
OutputSuccess
Important Notes
Make sure you have installed the correct CUDA drivers and PyTorch version with CUDA support.
If CUDA is not available, your code will run on CPU, which is slower for large models.
Summary
Use torch.cuda.is_available() to check GPU availability.
Set device accordingly to run models on GPU or CPU.
This helps your code adapt to different hardware automatically.
Practice
(1/5)
1. What does the function torch.cuda.is_available() check in PyTorch?
easy
A. If the CPU supports multi-threading
B. If a CUDA-capable GPU is available for PyTorch to use
C. If the PyTorch version is up to date
D. If the current script has internet access
Solution
Step 1: Understand the purpose of torch.cuda.is_available()
This function checks if PyTorch can access a CUDA-enabled GPU on the machine.
Step 2: Differentiate from other hardware checks
It does not check CPU features, PyTorch version, or internet access.
Final Answer:
If a CUDA-capable GPU is available for PyTorch to use -> Option B
Quick Check:
torch.cuda.is_available() = GPU availability [OK]
Hint: Check GPU presence with torch.cuda.is_available() [OK]
Common Mistakes:
Confusing CUDA availability with CPU features
Assuming it checks PyTorch version
Thinking it checks internet connection
2. Which of the following is the correct syntax to check CUDA availability in PyTorch?
easy
A. torch.cuda.is_available()
B. torch.cuda.available()
C. torch.is_cuda_available()
D. torch.cuda.check_available()
Solution
Step 1: Recall the exact function name
The correct function is torch.cuda.is_available() with this exact spelling and structure.
Step 2: Identify incorrect options
Other options have wrong function names or missing parts.
Final Answer:
torch.cuda.is_available() -> Option A
Quick Check:
Correct function name = torch.cuda.is_available() [OK]