mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 23:04:59 +08:00
Regenerate all MDC rules with fresh Exa data and December 2025 best practices
- Refreshed all 241 library rules with current best practices - Updated Exa search results for all libraries with 2025 content - Fixed --regenerate-all flag logic to properly process all libraries - Removed duplicate astro entry in rules.json (merged tags) - Added missing docker.mdc and vim.mdc files - All rules now include modern patterns and anti-patterns - Updated with framework-specific recommendations for 2025 Technical improvements: - Fixed retry_failed_only logic in generate_mdc_files.py - Improved progress tracking for regeneration scenarios - Ensured proper handling of --refresh-exa flag
This commit is contained in:
+396
-283
@@ -1,381 +1,494 @@
|
||||
---
|
||||
description: This rule provides comprehensive guidelines for PyTorch development, covering code organization, performance optimization, security, testing, and common pitfalls. It aims to ensure readable, maintainable, and efficient PyTorch code.
|
||||
globs: *.py
|
||||
description: Definitive guidelines for writing clean, performant, and maintainable PyTorch code, emphasizing modern best practices, explicit device management, and efficient training patterns.
|
||||
globs: **/*.py
|
||||
---
|
||||
# PyTorch Best Practices and Coding Standards
|
||||
# PyTorch Best Practices
|
||||
|
||||
This document provides comprehensive guidelines for developing PyTorch projects, encompassing code organization, performance optimization, security, testing methodologies, and common pitfalls. Adhering to these best practices will result in more readable, maintainable, and efficient PyTorch code.
|
||||
|
||||
**Library Information:**
|
||||
- Name: PyTorch
|
||||
- Category: ai_ml
|
||||
- Subcategory: machine_learning
|
||||
This guide outlines the definitive best practices for developing with PyTorch, ensuring your code is readable, performant, and production-ready. We prioritize usability, explicit control, and modern tooling.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1 Directory Structure Best Practices
|
||||
Structure your PyTorch projects for clarity, testability, and scalability. Encapsulate logical blocks into distinct functions or classes.
|
||||
|
||||
A well-organized directory structure enhances code maintainability and collaboration. Here's a recommended structure for PyTorch projects:
|
||||
### 1.1. Modularize Your Codebase
|
||||
|
||||
Separate data loading, model definition, training, and evaluation into dedicated modules or functions. This makes components reusable and testable.
|
||||
|
||||
project_root/
|
||||
├── data/
|
||||
│ ├── raw/
|
||||
│ ├── processed/
|
||||
│ └── ...
|
||||
├── models/
|
||||
│ ├── layers.py
|
||||
│ ├── networks.py
|
||||
│ ├── losses.py
|
||||
│ ├── ops.py
|
||||
│ └── model_name.py
|
||||
├── src/
|
||||
│ ├── data/
|
||||
│ │ ├── datasets.py
|
||||
│ │ ├── dataloaders.py
|
||||
│ │ └── transforms.py
|
||||
│ ├── models/
|
||||
│ │ └── ... (model-related code)
|
||||
│ ├── utils/
|
||||
│ │ └── ... (utility functions)
|
||||
│ └── visualization/
|
||||
│ └── ...
|
||||
├── notebooks/
|
||||
│ └── ... (Jupyter notebooks for experimentation)
|
||||
├── tests/
|
||||
│ ├── unit/
|
||||
│ ├── integration/
|
||||
│ └── ...
|
||||
├── scripts/
|
||||
│ └── train.py
|
||||
│ └── eval.py
|
||||
├── configs/
|
||||
│ └── ... (Configuration files, e.g., YAML)
|
||||
├── README.md
|
||||
├── requirements.txt
|
||||
├── .gitignore
|
||||
└── ...
|
||||
❌ BAD: Monolithic script
|
||||
```python
|
||||
# train.py
|
||||
import torch.nn as nn
|
||||
from torch.utils.data import DataLoader, TensorDataset
|
||||
|
||||
# ... data loading, model definition, training loop all in one file ...
|
||||
|
||||
- `data/`: Stores raw and processed datasets.
|
||||
- `models/`: Contains PyTorch model definitions, layers, and custom loss functions. Separate network architectures, individual layers/blocks, and operations into different files.
|
||||
- `src/`: Holds the main source code, including data loading, model definitions, utility functions, and visualization tools. It's common to split the `src/` folder further based on responsibilities.
|
||||
- `notebooks/`: Jupyter notebooks for experimentation and exploration. Use notebooks for initial exploration and prototyping but transition finalized code to Python scripts.
|
||||
- `tests/`: Unit, integration, and end-to-end tests.
|
||||
- `scripts/`: Training, evaluation, and deployment scripts. The main training script should import model definitions.
|
||||
- `configs/`: Configuration files for hyperparameter settings and other parameters.
|
||||
class MyModel(nn.Module):
|
||||
# ...
|
||||
pass
|
||||
|
||||
### 1.2 File Naming Conventions
|
||||
def main():
|
||||
# Data loading
|
||||
train_data = TensorDataset(...)
|
||||
train_loader = DataLoader(train_data, batch_size=32)
|
||||
|
||||
- Use descriptive and consistent file names.
|
||||
- Python files: `lower_with_under.py` (e.g., `data_loader.py`, `model_utils.py`).
|
||||
- Model files: `model_name.py` (e.g., `resnet.py`, `transformer.py`).
|
||||
- Configuration files: `config_name.yaml` (e.g., `train_config.yaml`).
|
||||
# Model, optimizer, loss
|
||||
model = MyModel()
|
||||
optimizer = torch.optim.Adam(model.parameters())
|
||||
criterion = nn.CrossEntropyLoss()
|
||||
|
||||
### 1.3 Module Organization
|
||||
# Training loop
|
||||
for epoch in range(10):
|
||||
for batch_idx, (data, target) in enumerate(train_loader):
|
||||
# ... training logic ...
|
||||
pass
|
||||
|
||||
- Group related functions and classes into modules.
|
||||
- Use clear and concise module names.
|
||||
- Include a docstring at the beginning of each module to describe its purpose.
|
||||
- Follow a consistent import style:
|
||||
python
|
||||
# Standard library imports
|
||||
import os
|
||||
import sys
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
```
|
||||
|
||||
# Third-party library imports
|
||||
import numpy as np
|
||||
import torch
|
||||
import torchvision
|
||||
✅ GOOD: Modularized structure
|
||||
```python
|
||||
# src/data.py
|
||||
import torch
|
||||
from torch.utils.data import DataLoader, TensorDataset
|
||||
|
||||
# Local application/library imports
|
||||
from src.data import data_loader
|
||||
from src.models import resnet
|
||||
from src.utils import helper_functions
|
||||
|
||||
def get_dataloaders(batch_size: int) -> tuple[DataLoader, DataLoader]:
|
||||
# Example: Create synthetic data
|
||||
X = torch.randn(1000, 784)
|
||||
y = torch.randint(0, 10, (1000,))
|
||||
train_dataset = TensorDataset(X, y)
|
||||
val_dataset = TensorDataset(X[:100], y[:100]) # Smaller val set
|
||||
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=4, pin_memory=True)
|
||||
val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False, num_workers=4, pin_memory=True)
|
||||
return train_loader, val_loader
|
||||
|
||||
### 1.4 Component Architecture
|
||||
|
||||
- **`nn.Module`:** The fundamental building block for creating neural networks in PyTorch. Always subclass `nn.Module` for defining models, layers, and custom operations.
|
||||
- **`forward()` method:** Implement the forward pass of your module within the `forward()` method. PyTorch uses the `__call__` method, which executes `forward()`, to pass data through the model.
|
||||
- **Separation of Concerns:** Design models as compositions of smaller, reusable modules. This promotes modularity and simplifies debugging.
|
||||
|
||||
Example:
|
||||
|
||||
python
|
||||
# src/model.py
|
||||
import torch.nn as nn
|
||||
|
||||
class ConvBlock(nn.Module):
|
||||
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1):
|
||||
super().__init__()
|
||||
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding)
|
||||
self.relu = nn.ReLU()
|
||||
self.bn = nn.BatchNorm2d(out_channels)
|
||||
|
||||
def forward(self, x):
|
||||
x = self.conv(x)
|
||||
x = self.relu(x)
|
||||
x = self.bn(x)
|
||||
return x
|
||||
|
||||
class SimpleCNN(nn.Module):
|
||||
def __init__(self, num_classes=10):
|
||||
def __init__(self, num_classes: int = 10):
|
||||
super().__init__()
|
||||
self.conv1 = ConvBlock(3, 32)
|
||||
self.conv2 = ConvBlock(32, 64)
|
||||
self.pool = nn.MaxPool2d(2, 2)
|
||||
self.fc = nn.Linear(64 * 8 * 8, num_classes)
|
||||
self.features = nn.Sequential(
|
||||
nn.Conv2d(1, 32, kernel_size=3, padding=1),
|
||||
nn.ReLU(),
|
||||
nn.MaxPool2d(kernel_size=2, stride=2),
|
||||
nn.Conv2d(32, 64, kernel_size=3, padding=1),
|
||||
nn.ReLU(),
|
||||
nn.MaxPool2d(kernel_size=2, stride=2)
|
||||
)
|
||||
self.classifier = nn.Sequential(
|
||||
nn.Flatten(),
|
||||
nn.Linear(64 * 7 * 7, 128), # Assuming 28x28 input, adjust for other sizes
|
||||
nn.ReLU(),
|
||||
nn.Linear(128, num_classes)
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
x = self.conv1(x)
|
||||
x = self.pool(x)
|
||||
x = self.conv2(x)
|
||||
x = self.pool(x)
|
||||
x = x.view(x.size(0), -1)
|
||||
x = self.fc(x)
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
x = self.features(x)
|
||||
x = self.classifier(x)
|
||||
return x
|
||||
|
||||
# src/train.py
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.optim import Adam
|
||||
from src.model import SimpleCNN
|
||||
from src.data import get_dataloaders
|
||||
|
||||
### 1.5 Code Splitting Strategies
|
||||
def train_epoch(model: nn.Module, loader: DataLoader, optimizer: Adam, criterion: nn.Module, device: torch.device) -> float:
|
||||
model.train()
|
||||
total_loss = 0.0
|
||||
for data, target in loader:
|
||||
data, target = data.to(device), target.to(device)
|
||||
optimizer.zero_grad()
|
||||
output = model(data)
|
||||
loss = criterion(output, target)
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
total_loss += loss.item()
|
||||
return total_loss / len(loader)
|
||||
|
||||
- **Vertical Splitting (Feature-based):** Divide code based on features or functionalities (e.g., data loading, model definition, training loop). This approach aligns well with module organization.
|
||||
- **Horizontal Splitting (Layer-based):** Split code based on layers or components of a neural network. This is suitable for complex models with distinct layers (e.g., encoder, decoder). The `models/` directory structure supports this.
|
||||
- **Microservices (for large projects):** For very large and complex machine learning deployments, consider breaking the workload into microservices - one for training, one for inference, another for data preprocessing, etc. This can improve scalability and fault tolerance.
|
||||
def evaluate_model(model: nn.Module, loader: DataLoader, device: torch.device) -> float:
|
||||
model.eval()
|
||||
correct = 0
|
||||
total = 0
|
||||
with torch.no_grad():
|
||||
for data, target in loader:
|
||||
data, target = data.to(device), target.to(device)
|
||||
output = model(data)
|
||||
_, predicted = torch.max(output.data, 1)
|
||||
total += target.size(0)
|
||||
correct += (predicted == target).sum().item()
|
||||
return 100 * correct / total
|
||||
|
||||
# main.py
|
||||
import torch
|
||||
from src.model import SimpleCNN
|
||||
from src.data import get_dataloaders
|
||||
from src.train import train_epoch, evaluate_model
|
||||
|
||||
def run_experiment(epochs: int = 10, batch_size: int = 64, lr: float = 1e-3):
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
train_loader, val_loader = get_dataloaders(batch_size)
|
||||
model = SimpleCNN().to(device)
|
||||
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
|
||||
criterion = torch.nn.CrossEntropyLoss()
|
||||
|
||||
for epoch in range(epochs):
|
||||
train_loss = train_epoch(model, train_loader, optimizer, criterion, device)
|
||||
val_accuracy = evaluate_model(model, val_loader, device)
|
||||
print(f"Epoch {epoch+1}: Train Loss = {train_loss:.4f}, Val Acc = {val_accuracy:.2f}%")
|
||||
|
||||
torch.save(model.state_dict(), "final_model.pth")
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_experiment()
|
||||
```
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### 2.1 Design Patterns Specific to PyTorch
|
||||
Adopt patterns that enhance clarity and performance, and avoid common pitfalls.
|
||||
|
||||
- **`nn.Sequential`:** A container for chaining layers in a sequential manner. Suitable for simple, linear models.
|
||||
- **Custom `nn.Module`:** Create custom modules for encapsulating reusable blocks of layers or operations. This promotes modularity and code reuse.
|
||||
- **Hooks:** Utilize forward and backward hooks for inspecting and modifying activations and gradients during training. Useful for debugging and research.
|
||||
- **DataParallel/DistributedDataParallel:** Wrap models with `DataParallel` or `DistributedDataParallel` to leverage multiple GPUs for training. `DistributedDataParallel` is generally preferred for multi-node training and offers better performance.
|
||||
- **Transfer Learning:** Reuse pretrained models from `torchvision.models` as a starting point for new tasks. Fine-tune the pretrained weights or add custom layers.
|
||||
### 2.1. Explicit Device Placement
|
||||
|
||||
### 2.2 Recommended Approaches for Common Tasks
|
||||
Always explicitly move tensors and models to the correct device (`cpu` or `cuda`). Never rely on implicit device handling.
|
||||
|
||||
- **Data Loading:** Use `torch.utils.data.Dataset` and `torch.utils.data.DataLoader` for efficient data loading and batching. Use custom Datasets to control data transformation.
|
||||
- **Model Definition:** Define models as classes that inherit from `nn.Module`. Use the layers defined in `torch.nn` to build the model.
|
||||
- **Training Loop:** Implement a structured training loop that iterates over epochs and batches. Include forward pass, loss calculation, backward pass, and optimization steps.
|
||||
- **Validation:** Evaluate model performance on a validation set during training to monitor overfitting and tune hyperparameters.
|
||||
- **Checkpointing:** Save model weights and optimizer state during training to resume training or load the best model.
|
||||
❌ BAD: Implicit device assumption
|
||||
```python
|
||||
model = MyModel() # Model is on CPU by default
|
||||
data = torch.randn(1, 3, 224, 224) # Data is on CPU
|
||||
output = model(data) # This will run on CPU, even if CUDA is available
|
||||
```
|
||||
|
||||
### 2.3 Anti-patterns and Code Smells to Avoid
|
||||
✅ GOOD: Explicit device placement
|
||||
```python
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
model = MyModel().to(device)
|
||||
data = torch.randn(1, 3, 224, 224).to(device)
|
||||
output = model(data) # Model and data are on the same device
|
||||
```
|
||||
|
||||
- **Hardcoding shapes:** Avoid hardcoding input or output shapes. Use dynamic shapes or calculate shapes based on input data.
|
||||
- **Global Variables:** Minimize the use of global variables. Pass data and configurations as function arguments.
|
||||
- **Magic Numbers:** Avoid using magic numbers without explanation. Define constants with descriptive names.
|
||||
- **Deeply Nested Loops:** Optimize performance-critical sections of code. Consider using vectorized operations or optimized data structures to avoid nested loops where possible.
|
||||
- **Ignoring Warnings:** Address all warnings. They often indicate potential problems or inefficiencies in your code. Use a debugger and logging to diagnose runtime behavior.
|
||||
- **Over-commenting:** Avoid redundant comments that simply reiterate the code. Focus on explaining the *why* rather than the *what*.
|
||||
- **Not using GPU when Available:** Always check if cuda is available and moves tensors and models to cuda for faster training and inference.
|
||||
### 2.2. Disable Gradient Calculation for Inference
|
||||
|
||||
### 2.4 State Management Best Practices
|
||||
Use `torch.no_grad()` for validation and inference to save memory and speed up computation.
|
||||
|
||||
- **Model Parameters:** Model parameters are automatically managed by PyTorch. Use `nn.Parameter` to register tensors as model parameters.
|
||||
- **Buffers:** Use `nn.Buffer` to store non-trainable tensors that are part of the model state (e.g., running statistics in BatchNorm).
|
||||
- **Optimizer State:** The optimizer maintains its own state, such as learning rate and momentum. Access and modify optimizer state through the `optimizer.state_dict()` and `optimizer.load_state_dict()` methods.
|
||||
- **Random Seeds:** Set random seeds for reproducibility:
|
||||
❌ BAD: Calculating unnecessary gradients
|
||||
```python
|
||||
model.eval()
|
||||
for data, target in val_loader:
|
||||
output = model(data) # Gradients are still computed and stored
|
||||
loss = criterion(output, target)
|
||||
# ...
|
||||
```
|
||||
|
||||
python
|
||||
import numpy as np
|
||||
import torch
|
||||
✅ GOOD: Disabling gradients
|
||||
```python
|
||||
model.eval()
|
||||
with torch.no_grad():
|
||||
for data, target in val_loader:
|
||||
output = model(data) # No gradients computed
|
||||
loss = criterion(output, target)
|
||||
# ...
|
||||
```
|
||||
|
||||
def set_seed(seed):
|
||||
np.random.seed(seed)
|
||||
torch.manual_seed(seed)
|
||||
if torch.cuda.is_available():
|
||||
torch.cuda.manual_seed(seed)
|
||||
torch.cuda.manual_seed_all(seed) # if using multiple GPUs
|
||||
torch.backends.cudnn.deterministic = True #Ensures that CUDA uses deterministic algorithms.
|
||||
torch.backends.cudnn.benchmark = False #Prevents CUDA from benchmarking multiple convolution algorithms.
|
||||
|
||||
### 2.3. Avoid In-Place Operations (Unless Profiled)
|
||||
|
||||
### 2.5 Error Handling Patterns
|
||||
In-place operations (`.add_()`, `.mul_()`, etc.) can break PyTorch's autograd engine and make debugging difficult. Prefer out-of-place operations unless profiling explicitly shows an in-place operation is a critical bottleneck for memory or speed.
|
||||
|
||||
- **Specific Exception Handling:** Catch specific exceptions rather than using bare `except` clauses. This allows you to handle different error scenarios appropriately.
|
||||
- **Logging:** Use the `logging` module to log errors and warnings. Include relevant information, such as timestamps, file names, and line numbers.
|
||||
- **Assertion Statements:** Use `assert` statements to check for unexpected conditions. This can help catch errors early in development.
|
||||
- **Custom Exceptions:** Define custom exception classes for specific error conditions in your application. This improves code readability and maintainability.
|
||||
- **Graceful Degradation:** Implement mechanisms to handle errors gracefully, such as providing default values or skipping problematic data points. Avoid crashing the application.
|
||||
❌ BAD: In-place operation
|
||||
```python
|
||||
x = torch.randn(5, requires_grad=True)
|
||||
y = x * 2
|
||||
x.add_(1) # Modifies x in-place, can cause autograd issues
|
||||
```
|
||||
|
||||
✅ GOOD: Out-of-place operation
|
||||
```python
|
||||
x = torch.randn(5, requires_grad=True)
|
||||
y = x * 2
|
||||
x = x + 1 # Creates a new tensor, preserving autograd graph
|
||||
```
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1 Optimization Techniques
|
||||
Optimize your PyTorch code for speed and memory efficiency.
|
||||
|
||||
- **GPU Utilization:** Use a GPU for training and inference. Move models and tensors to the GPU using `.to('cuda')`.
|
||||
- **Batch Size:** Tune the batch size to maximize GPU utilization without running out of memory. Larger batch sizes generally lead to better performance.
|
||||
- **Data Loading:** Optimize data loading by using multiple workers in the `DataLoader`. Consider using asynchronous data loading techniques.
|
||||
- **Mixed Precision Training:** Use mixed precision training (`torch.cuda.amp`) to reduce memory usage and accelerate training on NVIDIA GPUs with Tensor Cores.
|
||||
- **Gradient Accumulation:** Accumulate gradients over multiple batches to simulate a larger batch size when memory is limited.
|
||||
- **Operator Fusion:** Utilize PyTorch's JIT compiler (`torch.jit.script` or `torch.jit.trace`) to fuse multiple operations into a single kernel, reducing overhead and improving performance.
|
||||
- **Memory Usage:** When using `DataParallel`, ensure that the input data is evenly distributed across the available GPUs. Uneven data distribution can result in memory imbalances and slow down training.
|
||||
### 3.1. Leverage `torch.compile`
|
||||
|
||||
### 3.2 Memory Management
|
||||
Use `torch.compile` to significantly accelerate your models by tracing and optimizing the computation graph. Apply it to your `nn.Module` instances.
|
||||
|
||||
- **Tensor Deletion:** Delete unnecessary tensors using `del` to free up memory.
|
||||
- **`torch.no_grad()`:** Use `torch.no_grad()` during inference to disable gradient calculation and reduce memory usage.
|
||||
- **In-place Operations:** Use in-place operations (e.g., `x.add_(1)`) to modify tensors directly without creating new tensors. Be cautious with in-place operations as they can sometimes cause issues with autograd.
|
||||
- **Memory Profiling:** Use memory profiling tools to identify memory leaks and optimize memory usage.
|
||||
- **Garbage Collection:** Explicitly call `gc.collect()` to force garbage collection. This can be useful in situations where memory is not being released promptly.
|
||||
❌ BAD: Running model in eager mode only
|
||||
```python
|
||||
model = MyModel().to(device)
|
||||
# Training loop
|
||||
for data, target in loader:
|
||||
output = model(data)
|
||||
# ...
|
||||
```
|
||||
|
||||
### 3.3 Rendering Optimization (if applicable)
|
||||
✅ GOOD: Compiling the model
|
||||
```python
|
||||
model = MyModel().to(device)
|
||||
compiled_model = torch.compile(model) # Compile once
|
||||
# Training loop
|
||||
for data, target in loader:
|
||||
output = compiled_model(data) # Use the compiled model
|
||||
# ...
|
||||
```
|
||||
|
||||
- This section applies if PyTorch is used for rendering tasks (e.g., neural rendering).
|
||||
- **Optimize Mesh Data Structures:** Use efficient mesh data structures to reduce memory usage and improve rendering performance.
|
||||
- **Level of Detail (LOD):** Implement LOD techniques to reduce the complexity of rendered objects at a distance.
|
||||
- **Caching:** Cache frequently accessed data to reduce rendering time.
|
||||
### 3.2. Mixed Precision Training with `torch.cuda.amp`
|
||||
|
||||
### 3.4 Bundle Size Optimization (if applicable)
|
||||
For CUDA devices, use automatic mixed precision (AMP) to halve memory bandwidth and speed up computation without significant accuracy loss.
|
||||
|
||||
- This section applies if PyTorch models are deployed in web applications or other size-sensitive environments.
|
||||
- **Model Quantization:** Quantize models to reduce their size. Use `torch.quantization` to quantize models to 8-bit integers.
|
||||
- **Model Pruning:** Prune unimportant weights from models to reduce their size. Use `torch.nn.utils.prune` to prune models.
|
||||
- **ONNX Export:** Convert PyTorch models to ONNX format for deployment on various platforms.
|
||||
❌ BAD: Full precision training
|
||||
```python
|
||||
optimizer = torch.optim.Adam(model.parameters())
|
||||
for data, target in loader:
|
||||
output = model(data)
|
||||
loss = criterion(output, target)
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
```
|
||||
|
||||
### 3.5 Lazy Loading Strategies
|
||||
✅ GOOD: Mixed precision training
|
||||
```python
|
||||
from torch.cuda.amp import autocast, GradScaler
|
||||
|
||||
- **Lazy Initialization:** Defer the initialization of expensive resources until they are needed.
|
||||
- **Data Streaming:** Load data in smaller chunks instead of loading the entire dataset into memory at once.
|
||||
- **Just-In-Time (JIT) Compilation:** Use `torch.jit.script` or `torch.jit.trace` to compile models just before they are used. This can improve performance and reduce memory usage.
|
||||
scaler = GradScaler()
|
||||
optimizer = torch.optim.Adam(model.parameters())
|
||||
|
||||
## 4. Security Best Practices
|
||||
for data, target in loader:
|
||||
with autocast(): # Operations within this context run in mixed precision
|
||||
output = model(data)
|
||||
loss = criterion(output, target)
|
||||
|
||||
### 4.1 Common Vulnerabilities and How to Prevent Them
|
||||
scaler.scale(loss).backward() # Scale gradients
|
||||
scaler.step(optimizer) # Update optimizer
|
||||
scaler.update() # Update scaler for next iteration
|
||||
```
|
||||
|
||||
- **Adversarial Attacks:** Be aware of adversarial attacks that can manipulate model predictions. Implement techniques like adversarial training and input sanitization.
|
||||
- **Data Poisoning:** Protect against data poisoning attacks by validating input data and using robust training techniques.
|
||||
- **Model Extraction:** Prevent model extraction by limiting access to model weights and predictions.
|
||||
- **Integer Overflow:** Be aware of integer overflow issues in user-provided data.
|
||||
### 3.3. Optimize `DataLoader`
|
||||
|
||||
### 4.2 Input Validation
|
||||
Configure `DataLoader` for efficient asynchronous data loading.
|
||||
|
||||
- **Data Type Validation:** Ensure that input data has the correct data type.
|
||||
- **Range Validation:** Check that input values are within a valid range.
|
||||
- **Format Validation:** Validate the format of input strings (e.g., URLs, email addresses).
|
||||
- **Sanitization:** Sanitize input data to remove potentially malicious characters or code.
|
||||
❌ BAD: Default `DataLoader` settings
|
||||
```python
|
||||
DataLoader(dataset, batch_size=32) # num_workers=0, pin_memory=False
|
||||
```
|
||||
|
||||
### 4.3 Authentication and Authorization Patterns
|
||||
✅ GOOD: Optimized `DataLoader`
|
||||
```python
|
||||
DataLoader(
|
||||
dataset,
|
||||
batch_size=32,
|
||||
shuffle=True,
|
||||
num_workers=min(os.cpu_count(), 8), # Tune based on CPU cores
|
||||
pin_memory=True, # Faster host-to-GPU transfer
|
||||
persistent_workers=True # Keep workers alive between epochs
|
||||
)
|
||||
```
|
||||
|
||||
- **API Keys:** Use API keys to authenticate clients accessing your models.
|
||||
- **OAuth 2.0:** Implement OAuth 2.0 for secure authorization of user access.
|
||||
- **Role-Based Access Control (RBAC):** Use RBAC to restrict access to specific models or functionalities based on user roles.
|
||||
## 4. Common Pitfalls and Gotchas
|
||||
|
||||
### 4.4 Data Protection Strategies
|
||||
Be aware of these common issues to avoid frustrating debugging sessions.
|
||||
|
||||
- **Encryption:** Encrypt sensitive data at rest and in transit.
|
||||
- **Anonymization:** Anonymize data to protect user privacy.
|
||||
- **Differential Privacy:** Use differential privacy techniques to protect the privacy of training data.
|
||||
- **Access Control:** Implement strict access control policies to limit access to sensitive data.
|
||||
### 4.1. Device Mismatches
|
||||
|
||||
### 4.5 Secure API Communication
|
||||
Ensure all tensors involved in an operation are on the same device. This is the most frequent error.
|
||||
|
||||
- **HTTPS:** Use HTTPS to encrypt communication between clients and your API.
|
||||
- **TLS/SSL:** Use TLS/SSL certificates to secure your API endpoints.
|
||||
- **Rate Limiting:** Implement rate limiting to prevent denial-of-service attacks.
|
||||
- **Input Validation:** Always validate and sanitize input data to prevent injection attacks.
|
||||
❌ BAD: Device mismatch
|
||||
```python
|
||||
model = MyModel().cuda()
|
||||
input_tensor = torch.randn(1, 3, 224, 224).cpu() # Input on CPU
|
||||
output = model(input_tensor) # ERROR: Expected all tensors to be on the same device
|
||||
```
|
||||
|
||||
## 5. Testing Approaches
|
||||
✅ GOOD: Consistent device placement
|
||||
```python
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
model = MyModel().to(device)
|
||||
input_tensor = torch.randn(1, 3, 224, 224).to(device)
|
||||
output = model(input_tensor) # All good
|
||||
```
|
||||
|
||||
### 5.1 Unit Testing Strategies
|
||||
### 4.2. Multiprocessing Start Method
|
||||
|
||||
- **Test Individual Modules:** Write unit tests for individual modules to ensure they function correctly.
|
||||
- **Test Edge Cases:** Test edge cases and boundary conditions to identify potential errors.
|
||||
- **Use Assertions:** Use assertions to verify expected outcomes.
|
||||
- **Test Model Outputs:** Verify that model outputs have the correct shape and data type.
|
||||
When using multiprocessing with CUDA, always set the start method to `"spawn"` or `"forkserver"` to avoid "poison fork" issues.
|
||||
|
||||
### 5.2 Integration Testing
|
||||
❌ BAD: Default `fork` start method with CUDA
|
||||
```python
|
||||
# This might implicitly use 'fork' on Linux, leading to CUDA errors
|
||||
import torch.multiprocessing as mp
|
||||
mp.set_start_method('fork') # Explicitly setting bad practice
|
||||
```
|
||||
|
||||
- **Test Interactions Between Modules:** Write integration tests to ensure that different modules work together correctly.
|
||||
- **Test Data Pipelines:** Test the entire data pipeline, from data loading to model output.
|
||||
- **Test End-to-End Functionality:** Test the entire application to ensure that it meets the requirements.
|
||||
✅ GOOD: Safe multiprocessing start method
|
||||
```python
|
||||
import torch.multiprocessing as mp
|
||||
try:
|
||||
mp.set_start_method('spawn', force=True) # Recommended for cross-platform safety
|
||||
except RuntimeError:
|
||||
pass # Already set
|
||||
```
|
||||
|
||||
### 5.3 End-to-End Testing
|
||||
## 5. Type Hints
|
||||
|
||||
- **Simulate User Interactions:** Write end-to-end tests that simulate user interactions with the application.
|
||||
- **Test the Entire System:** Test the entire system, including the user interface, API, and database.
|
||||
- **Verify Expected Outcomes:** Verify that the application produces the expected outcomes.
|
||||
Use type hints extensively for improved readability, maintainability, and static analysis.
|
||||
|
||||
### 5.4 Test Organization
|
||||
❌ BAD: Untyped functions
|
||||
```python
|
||||
def train_step(model, data, target, optimizer, criterion):
|
||||
# ...
|
||||
pass
|
||||
```
|
||||
|
||||
- **Separate Test Files:** Create separate test files for each module or component.
|
||||
- **Use a Test Runner:** Use a test runner (e.g., `pytest`, `unittest`) to discover and run tests.
|
||||
- **Follow a Consistent Naming Convention:** Follow a consistent naming convention for test files and test functions.
|
||||
✅ GOOD: Type-hinted functions
|
||||
```python
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.optim import Optimizer
|
||||
from torch.utils.data import DataLoader
|
||||
|
||||
### 5.5 Mocking and Stubbing
|
||||
def train_step(
|
||||
model: nn.Module,
|
||||
data: torch.Tensor,
|
||||
target: torch.Tensor,
|
||||
optimizer: Optimizer,
|
||||
criterion: nn.Module
|
||||
) -> float:
|
||||
# ...
|
||||
return loss.item()
|
||||
```
|
||||
|
||||
- **Use Mocks to Isolate Units:** Use mocks to isolate units of code from their dependencies.
|
||||
- **Use Stubs to Provide Test Data:** Use stubs to provide test data to units of code.
|
||||
- **Verify Interactions with Dependencies:** Verify that units of code interact with their dependencies as expected.
|
||||
## 6. Virtual Environments
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
Always use virtual environments (`venv` or `conda`) to manage dependencies and ensure reproducible setups.
|
||||
|
||||
### 6.1 Frequent Mistakes Developers Make
|
||||
❌ BAD: Global package installation
|
||||
```bash
|
||||
pip install torch torchvision # Pollutes global Python environment
|
||||
```
|
||||
|
||||
- **Incorrect Tensor Shapes:** Pay close attention to tensor shapes when performing operations. Use `torch.Size()` to check tensor shapes.
|
||||
- **Gradient Issues:** Be mindful of gradient flow. Ensure that gradients are properly calculated and propagated through the network. Use `torch.autograd.set_detect_anomaly(True)` for debugging autograd issues.
|
||||
- **Memory Leaks:** Be careful to deallocate tensors when they are no longer needed. Use memory profiling tools to identify memory leaks.
|
||||
- **Data Type Mismatches:** Ensure that tensors have the correct data type (e.g., `torch.float32`, `torch.int64`).
|
||||
- **Device Mismatches:** Ensure that tensors and models are on the same device (CPU or GPU).
|
||||
✅ GOOD: Virtual environment setup
|
||||
```bash
|
||||
# Using venv
|
||||
python -m venv .venv
|
||||
source .venv/bin/activate
|
||||
pip install torch torchvision
|
||||
|
||||
### 6.2 Edge Cases to Be Aware Of
|
||||
# Using conda
|
||||
conda create -n my_env python=3.10
|
||||
conda activate my_env
|
||||
conda install pytorch torchvision torchaudio pytorch-cuda=12.1 -c pytorch -c nvidia
|
||||
```
|
||||
|
||||
- **Empty Datasets:** Handle cases where datasets are empty or contain missing data.
|
||||
- **Out-of-Memory Errors:** Handle out-of-memory errors gracefully by reducing batch size or using gradient accumulation.
|
||||
- **Numerical Instability:** Be aware of numerical instability issues, such as vanishing or exploding gradients. Use techniques like gradient clipping and batch normalization.
|
||||
## 7. Packaging
|
||||
|
||||
### 6.3 Version-Specific Issues
|
||||
For reusable components or libraries, package your code properly using `setuptools` or `poetry`.
|
||||
|
||||
- **Compatibility with Libraries:** Be aware of compatibility issues between different versions of PyTorch and other libraries.
|
||||
- **API Changes:** Track API changes in PyTorch releases and update your code accordingly.
|
||||
❌ BAD: Just a collection of scripts
|
||||
```
|
||||
my_project/
|
||||
├── train.py
|
||||
├── model.py
|
||||
└── data.py
|
||||
```
|
||||
|
||||
### 6.4 Compatibility Concerns
|
||||
✅ GOOD: Packaged structure
|
||||
```
|
||||
my_project/
|
||||
├── pyproject.toml # Or setup.py
|
||||
├── src/
|
||||
│ └── my_project_lib/
|
||||
│ ├── __init__.py
|
||||
│ ├── model.py
|
||||
│ ├── data.py
|
||||
│ └── train_utils.py
|
||||
├── scripts/
|
||||
│ └── run_training.py # Entry point that imports from src/
|
||||
└── tests/
|
||||
├── test_model.py
|
||||
└── test_data.py
|
||||
```
|
||||
|
||||
- **Hardware Compatibility:** Ensure that your code is compatible with different hardware configurations (e.g., different GPUs).
|
||||
- **Operating System Compatibility:** Ensure that your code is compatible with different operating systems (e.g., Linux, Windows, macOS).
|
||||
## 8. Testing Approaches
|
||||
|
||||
### 6.5 Debugging Strategies
|
||||
Implement unit tests for individual modules and integration tests for training loops.
|
||||
|
||||
- **Print Statements:** Use print statements to inspect the values of tensors and variables.
|
||||
- **Debuggers:** Use a debugger (e.g., `pdb`) to step through your code and inspect the state of your application.
|
||||
- **TensorBoard:** Use TensorBoard to visualize model training progress, including loss curves, metrics, and model architecture.
|
||||
- **`torch.autograd.set_detect_anomaly(True)`:** A powerful tool for debugging autograd issues. It will raise an error when a NaN gradient is detected, helping you pinpoint the source of the problem.
|
||||
### 8.1. Unit Tests for Modules
|
||||
|
||||
## 7. Tooling and Environment
|
||||
Test `nn.Module` definitions, data transformations, and utility functions independently.
|
||||
|
||||
### 7.1 Recommended Development Tools
|
||||
❌ BAD: No tests, or only end-to-end testing
|
||||
```python
|
||||
# No dedicated tests for SimpleCNN
|
||||
```
|
||||
|
||||
- **IDEs:** Visual Studio Code (with Python extension), PyCharm.
|
||||
- **Virtual Environments:** `venv`, `conda`.
|
||||
- **Debugging Tools:** `pdb`, `ipdb`.
|
||||
- **Profiling Tools:** `torch.profiler`, `memory_profiler`.
|
||||
✅ GOOD: Unit test for a model
|
||||
```python
|
||||
# tests/test_model.py
|
||||
import unittest
|
||||
import torch
|
||||
from src.model import SimpleCNN
|
||||
|
||||
### 7.2 Build Configuration
|
||||
class TestSimpleCNN(unittest.TestCase):
|
||||
def test_forward_pass(self):
|
||||
model = SimpleCNN(num_classes=10)
|
||||
input_tensor = torch.randn(1, 1, 28, 28) # Batch, Channels, H, W
|
||||
output = model(input_tensor)
|
||||
self.assertEqual(output.shape, (1, 10))
|
||||
|
||||
- **`requirements.txt`:** Specify project dependencies in a `requirements.txt` file. Use `pip freeze > requirements.txt` to generate the file.
|
||||
def test_output_range(self):
|
||||
model = SimpleCNN(num_classes=2)
|
||||
input_tensor = torch.randn(1, 1, 28, 28)
|
||||
output = model(input_tensor)
|
||||
# Check if output is float
|
||||
self.assertTrue(output.dtype == torch.float32)
|
||||
|
||||
Example `requirements.txt`:
|
||||
|
||||
torch==1.13.1
|
||||
torchvision==0.14.1
|
||||
numpy==1.24.1
|
||||
|
||||
- **`setup.py` (for libraries):** Use `setup.py` to define your library's metadata and dependencies.
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
```
|
||||
|
||||
### 7.3 Linting and Formatting
|
||||
### 8.2. Integration Tests for Training Loops
|
||||
|
||||
- **Linters:** `flake8`, `pylint`.
|
||||
- **Formatters:** `black`, `autopep8`.
|
||||
- **Pre-commit Hooks:** Use pre-commit hooks to automatically run linters and formatters before committing code.
|
||||
Use small, mock datasets to quickly verify the training loop's functionality without long training times.
|
||||
|
||||
### 7.4 Deployment Best Practices
|
||||
❌ BAD: Only testing with full datasets
|
||||
```python
|
||||
# Training script only runs with full data, slow to verify changes
|
||||
```
|
||||
|
||||
- **Model Serialization:** Use `torch.save` to serialize models for deployment. Use `torch.load` to load models.
|
||||
- **ONNX Export:** Convert PyTorch models to ONNX format for deployment on various platforms.
|
||||
- **Serving Frameworks:** Use serving frameworks like TorchServe, FastAPI, or Flask to deploy PyTorch models as REST APIs.
|
||||
✅ GOOD: Integration test with mock data
|
||||
```python
|
||||
# tests/test_training.py
|
||||
import unittest
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.data import DataLoader, TensorDataset
|
||||
from src.model import SimpleCNN
|
||||
from src.train import train_epoch, evaluate_model
|
||||
|
||||
### 7.5 CI/CD Integration
|
||||
class TestTrainingLoop(unittest.TestCase):
|
||||
def test_training_run(self):
|
||||
device = torch.device("cpu") # Use CPU for faster testing
|
||||
model = SimpleCNN(num_classes=2).to(device)
|
||||
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
|
||||
criterion = nn.CrossEntropyLoss()
|
||||
|
||||
- **Continuous Integration (CI):** Use CI tools like Jenkins, GitHub Actions, or GitLab CI to automatically build and test your code.
|
||||
- **Continuous Deployment (CD):** Use CD tools to automatically deploy your code to production environments.
|
||||
- **Automated Testing:** Integrate automated testing into your CI/CD pipeline to ensure code quality and prevent regressions. Run unit, integration, and end-to-end tests.
|
||||
# Create a small mock dataset
|
||||
mock_X = torch.randn(10, 1, 28, 28)
|
||||
mock_y = torch.randint(0, 2, (10,))
|
||||
mock_dataset = TensorDataset(mock_X, mock_y)
|
||||
mock_loader = DataLoader(mock_dataset, batch_size=2)
|
||||
|
||||
initial_loss = train_epoch(model, mock_loader, optimizer, criterion, device)
|
||||
# Run a second epoch to ensure loss decreases (basic sanity check)
|
||||
second_epoch_loss = train_epoch(model, mock_loader, optimizer, criterion, device)
|
||||
|
||||
self.assertLess(second_epoch_loss, initial_loss * 1.1) # Expect some decrease or stability
|
||||
accuracy = evaluate_model(model, mock_loader, device)
|
||||
self.assertGreaterEqual(accuracy, 0.0) # Basic check that accuracy is calculated
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
```
|
||||
Reference in New Issue
Block a user