pytorch-patterns
Skill này làm gì
Agent này giúp viết code AI bằng thư viện PyTorch. Nó đảm bảo code được tổ chức tốt, chạy được trên các máy khác nhau (có hoặc không có card đồ họa mạnh) và kết quả có thể tái tạo.
Khi nào nên dùng
- ✓Khi bắt đầu viết một mô hình AI mới bằng PyTorch.
- ✓Khi xem lại code AI để đảm bảo tuân theo thực hành tốt nhất.
- ✓Khi bạn cần kết quả thử nghiệm AI luôn giống nhau mỗi lần chạy.
Liên kết skill
https://github.com/affaan-m/ECC/blob/main/pi/core/skills/pytorch-patterns/SKILL.mdSao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.
Cách dùng
Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.
Tin nhắn có sẵn để dán
Dành cho Claude Code, Codex hoặc Cursor: chạy lệnh trong thư mục dự án của bạn và skill sẽ được cài đặt.
Tải tệp SKILL.md về và thả vào thư mục skill của agent.
Ví dụ cách nhờ AI
“Làm sao để code PyTorch của tôi chạy được cả trên CPU và GPU, và kết quả luôn giống nhau?”
5 skill mới mỗi tuần. Đọc chỉ 1 phút.
Cách hoạt động
Nó kiểm tra xem code có được viết để không phụ thuộc vào nơi chạy (CPU hay GPU) hay không, và các thiết lập để có kết quả tái tạo được đã có chưa. Nó cũng giúp tổ chức cấu trúc code và quản lý kích thước dữ liệu.
Nội dung kỹ thuật (SKILL.md gốc)
Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.
PyTorch Development Patterns
Idiomatic PyTorch patterns and best practices for building robust, efficient, and reproducible deep learning applications.
When to Activate
- Writing new PyTorch models or training scripts
- Reviewing deep learning code
- Debugging training loops or data pipelines
- Optimizing GPU memory usage or training speed
- Setting up reproducible experiments
Core Principles
1. Device-Agnostic Code
Always write code that works on both CPU and GPU without hardcoding devices.
# Good: Device-agnostic
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = MyModel().to(device)
data = data.to(device)
# Bad: Hardcoded device
model = MyModel().cuda() # Crashes if no GPU
data = data.cuda()
2. Reproducibility First
Set all random seeds for reproducible results.
# Good: Full reproducibility setup
def set_seed(seed: int = 42) -> None:
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
# Bad: No seed control
model = MyModel() # Different weights every run
3. Explicit Shape Management
Always document and verify tensor shapes.
# Good: Shape-annotated forward pass
def forward(self, x: torch.Tensor) -> torch.Tensor:
# x: (batch_size, channels, height, width)
x = self.conv1(x) # -> (batch_size, 32, H, W)
x = self.pool(x) # -> (batch_size, 32, H//2, W//2)
x = x.view(x.size(0), -1) # -> (batch_size, 32*H//2*W//2)
return self.fc(x) # -> (batch_size, num_classes)
# Bad: No shape tracking
def forward(self, x):
x = self.conv1(x)
x = self.pool(x)
x = x.view(x.size(0), -1) # What size is this?
return self.fc(x) # Will this even work?
Model Architecture Patterns
Clean nn.Module Structure
# Good: Well-organized module
class ImageClassifier(nn.Module):
def __init__(self, num_classes: int, dropout: float = 0.5) -> None:
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=3, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
nn.MaxPool2d(2),
)
self.classifier = nn.Sequential(
nn.Dropout(dropout),
nn.Linear(64 * 16 * 16, num_classes),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.features(x)
x = x.view(x.size(0), -1)
return self.classifier(x)
# Bad: Everything in forward
class ImageClassifier(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
x = F.conv2d(x, weight=self.make_weight()) # Creates weight each call!
return x
Proper Weight Initialization
# Good: Explicit initialization
def _init_weights(self, module: nn.Module) -> None:
if isinstance(module, nn.Linear):
nn.init.kaiming_normal_(module.weight, mode="fan_out", nonlinearity="relu")
if module.bias is not None:
nn.init.zeros_(module.bias)
elif isinstance(module, nn.Conv2d):
nn.init.kaiming_normal_(module.weight, mode="fan_out", nonlinearity="relu")
elif isinstance(module, nn.BatchNorm2d):
nn.init.ones_(module.weight)
nn.init.zeros_(module.bias)
model = MyModel()
model.apply(model._init_weights)
Training Loop Patterns
Standard Training Loop
# Good: Complete training loop with best practices
def train_one_epoch(
model: nn.Module,
dataloader: DataLoader,
optimizer: torch.optim.Optimizer,
criterion: nn.Module,
device: torch.device,
scaler: torch.amp.GradScaler | None = None,
) -> float:
model.train() # Always set train mode
total_loss = 0.0
for batch_idx, (data, target) in enumerate(dataloader):
data, target = data.to(device), target.to(device)
optimizer.zero_grad(set_to_none=True) # More efficient than zero_grad()
# Mixed precision training
with torch.amp.autocast("cuda", enabled=scaler is not None):
output = model(data)
loss = criterion(output, target)
if scaler is not None:
scaler.scale(loss).backward()
scaler.unscale_(optimizer)
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
scaler.step(optimizer)
scaler.update()
…
Câu hỏi thường gặp
Vì sao code chạy được cả trên CPU và GPU là quan trọng?
Để bạn có thể huấn luyện mô hình trên nhiều máy khác nhau, kể cả máy không có card đồ họa (GPU) mạnh, giúp code linh hoạt hơn.
'Kết quả có thể tái tạo' nghĩa là gì?
Nghĩa là khi chạy cùng code với cùng dữ liệu, bạn sẽ luôn nhận được đúng kết quả giống nhau, điều rất quan trọng để kiểm thử và so sánh mô hình.
Agent giúp tổ chức code như thế nào?
Nó gợi ý các mẫu tổ chức cho từng phần của mô hình (như các lớp và hàm) và cho quá trình huấn luyện, giúp code dễ đọc và dễ bảo trì hơn.
Chi tiết
Mô tả gốc của tác giả
PyTorch deep learning patterns and best practices for building robust, efficient, and reproducible training pipelines, model architectures, and data loading. Use when writing or reviewing PyTorch training loops, model architectures, or data loading, or when a run will not reproduce.
repo: affaan-m/ECC
Độ phổ biến
- Sao GitHub
- 280k
- Vị trí xếp hạng
- #230
- Giấy phép
- MIT
- Cập nhật
- 15/10/2026
Bình luận
- …
Thêm skill từ kho mã này
accessibility
280kGiúp agent của bạn tạo giao diện mà ai cũng dùng được, đảm bảo website và app hoạt động tốt với người khuyết tật như người mù hoặc khó vận động.
agent-architecture-audit
280kGiúp agent của bạn kiểm tra xem mọi thứ có hoạt động đúng không, đồng thời tìm và sửa các lỗi trong hệ thống AI để chúng chạy như mong đợi.
agent-eval
280kGiúp agent của bạn so sánh các công cụ lập trình AI khác nhau, đo xem công cụ nào nhanh hơn, rẻ hơn và đáng tin cậy hơn cho từng tác vụ.
agent-harness-construction
280kGiúp agent của bạn hiểu rõ hơn cách thực hiện tác vụ, tối ưu các công cụ và chỉ dẫn mà agent dùng để tăng khả năng thành công.
Skill tương tự
accelerate
260kGiúp agent của bạn chạy một script huấn luyện PyTorch trên nhiều GPU chỉ với vài dòng thêm vào, dùng Hugging Face Accelerate.
evaluating-llms-harness
260kGiúp agent của bạn đánh giá một mô hình ngôn ngữ trên các bài kiểm tra học thuật chuẩn như MMLU, GSM8K và HellaSwag, rồi so sánh kết quả.
flash-attention
260kGiúp agent của bạn tăng tốc bước attention của mô hình transformer và giảm bộ nhớ dùng, đặc biệt với đầu vào dài khi huấn luyện hoặc suy luận.