pytorch-patterns
하는 일
이 에이전트는 PyTorch 라이브러리로 인공지능(AI) 코드를 작성하도록 돕습니다. 코드를 체계적으로 정리하고, 강력한 그래픽 카드가 있는 컴퓨터나 없는 컴퓨터 모두에서 작동하도록 하며, 결과를 재현할 수 있도록 보장합니다.
사용하는 경우
- ✓PyTorch로 새로운 AI 모델을 만들기 시작할 때.
- ✓AI 코드가 모범 사례를 따르는지 검토할 때.
- ✓AI 테스트 결과가 매번 완전히 같아야 할 때.
스킬 링크
https://github.com/affaan-m/ECC/blob/main/pi/core/skills/pytorch-patterns/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“PyTorch 코드가 CPU와 GPU 모두에서 작동하고 결과가 항상 같도록 하려면 어떻게 해야 할까요?”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
코드가 실행되는 장소(CPU 또는 GPU)와 무관하게 작성되었는지, 재현 가능한 결과를 위한 설정이 있는지 확인합니다. 또한 코드 구조와 데이터 차원을 관리하도록 돕습니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.
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()
…
자주 묻는 질문
코드가 CPU와 GPU에서 모두 작동하는 것이 왜 중요한가요?
강력한 그래픽 카드(GPU)가 없는 컴퓨터에서도 모델을 학습할 수 있어서 코드가 더 유연해지기 때문입니다.
‘재현 가능한 결과’란 무엇을 뜻하나요?
같은 코드를 같은 데이터로 실행하면 매번 정확히 같은 결과를 얻는다는 뜻입니다. 테스트와 모델 비교에 매우 중요합니다.
에이전트는 코드 구조를 어떻게 정리하도록 돕나요?
모델의 여러 부분(계층과 함수)과 학습 과정에 대한 구조 패턴을 제안해, 코드를 읽고 관리하기 쉽게 만듭니다.
상세 정보
작성자의 원본 설명
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
인기도
- GitHub 스타
- 280k
- 순위
- #230
- 라이선스
- MIT
- 업데이트
- 2026. 10. 15.
댓글
- …
이 저장소의 다른 스킬
accessibility
280k에이전트가 모든 사람이 쓸 수 있는 인터페이스를 만들도록 돕습니다. 시각 장애나 운동 장애가 있는 사람도 쓸 수 있게 합니다.
agent-architecture-audit
280k에이전트가 모든 것이 올바르게 작동하는지 점검하도록 돕습니다. AI 시스템의 문제를 찾아 고쳐서 기대대로 작동하게 합니다.
agent-eval
280k에이전트가 서로 다른 AI 코딩 도구를 비교하도록 돕습니다. 특정 작업에서 어느 도구가 더 빠르고, 저렴하고, 믿을 만한지 측정합니다.
agent-harness-construction
280k에이전트가 작업을 더 잘 이해하도록 돕습니다. 에이전트가 쓰는 도구와 지시문을 최적화해 성공 가능성을 높입니다.
비슷한 스킬
accelerate
260kHugging Face Accelerate를 사용해, 몇 줄만 추가하여 PyTorch 학습 스크립트를 여러 GPU에서 실행하도록 에이전트를 돕습니다.
evaluating-llms-harness
260kMMLU, GSM8K, HellaSwag 같은 표준 학술 시험으로 언어 모델을 벤치마크하고 결과를 비교하도록 에이전트를 돕습니다.
flash-attention
260k트랜스포머 모델의 어텐션 단계를 빠르게 하고 메모리 사용을 줄이도록 에이전트를 돕습니다. 특히 학습이나 추론에서 긴 입력에 효과적입니다.