Using GPUs and TPUs in Deep Learning

अब जब आप PyTorch और Keras दोनों में model बना और train कर रहे हैं, तो performance boost के लिए GPU/TPU का इस्तेमाल करना ज़रूरी हो जाता है — खासकर बड़े datasets या deep models के लिए।


🔷 1. 🔥 Why Use GPUs?

CPU vs GPUGPU Advantage
SequentialParallel computing
Few coresThousands of cores
Slower matrix opsFaster tensor operations
General-purposeSpecial for ML/DL, CUDA-optimized

🔶 PyTorch में GPU का उपयोग कैसे करें?

✅ Step 1: Check GPU Availability

import torch

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Using device:", device)

✅ Step 2: Model और Data को GPU पर भेजना

model = MyNet().to(device)  # Model को GPU पर भेजें
X = X.to(device)
y = y.to(device)

✅ Training Code में बदलाव:

for epoch in range(1000):
y_pred = model(X)
loss = criterion(y_pred, y)

optimizer.zero_grad()
loss.backward()
optimizer.step()

बस यह ध्यान रखें कि model और data दोनों एक ही device पर होने चाहिए


🔷 2. GPU से Prediction (Inference)

model.eval()
with torch.no_grad():
test = torch.tensor([[1., 0.]]).to(device)
output = model(test)
print("Prediction:", output.item())

🔷 3. Keras (TensorFlow) में GPU का उपयोग

TensorFlow अपने आप GPU को detect करता है और उपयोग करता है (अगर उपलब्ध हो)। बस ensure करें कि:

  • TensorFlow-GPU version install हो
  • NVIDIA Drivers + CUDA Toolkit सही से install हो

✅ Check GPU:

import tensorflow as tf
print("Num GPUs Available:", len(tf.config.list_physical_devices('GPU')))

✅ Tensor और Model GPU पर चलेंगे अपने आप:

model.fit(X, y, epochs=10)  # If GPU available, TensorFlow will use it

✅ Manually GPU select करना:

with tf.device('/GPU:0'):
model = tf.keras.Sequential([...])
model.compile(...)
model.fit(...)

🔷 4. Google Colab में GPU/TPU Use

✅ GPU Enable करें:

Runtime → Change runtime type → Hardware accelerator → GPU or TPU

✅ Check GPU/TPU:

import tensorflow as tf
print(tf.config.list_physical_devices('GPU')) # For GPU
print(tf.config.list_logical_devices('TPU')) # For TPU

🔷 5. TPUs क्या होते हैं?

AspectDetail
TPUTensor Processing Unit (Google द्वारा बनाया गया)
SpeedGPU से भी तेज़ है कुछ tasks में
Best forVery large models, production-level serving
UseMainly in Google Colab, Cloud TPUs, TensorFlow

📝 Practice Questions:

  1. PyTorch में GPU support कैसे check करते हैं?
  2. Model को GPU पर भेजने के लिए कौनसा syntax है?
  3. TensorFlow GPU vs TPU में क्या अंतर है?
  4. Google Colab में GPU enable कैसे करते हैं?
  5. क्या CPU से GPU training में फर्क आता है?

🧠 Summary Table

TaskPyTorchKeras (TF)
GPU Checktorch.cuda.is_available()tf.config.list_physical_devices()
Send to GPUx.to(device)Automatic
Model to GPUmodel.to(device)Automatic
Use Colab GPURuntime > Change > GPUSame
TPU Support❌ (Limited)✅ (Good)