Communitygithub.com

pytorch-patterns

PyTorchディープラーニングのパターンとベストプラクティス。堅牢で効率的、再現可能なトレーニングパイプライン、モデルアーキテクチャ、データローディングを構築するためのものです。PyTorchのトレーニングループ、モデルアーキテクチャ、データローディングを記述またはレビューする際、または実行が再現されない場合に使用します。

pytorch-patterns とは?

このスキルは、PyTorchを使用したディープラーニング開発において、ベストプラクティスに従った堅牢で効率的、再現可能なコードを記述するための包括的なガイドを提供します。デバイスに依存しないコード(CPU/GPU)、再現性の確保(シード設定)、テンソル形状の明示的な管理、クリーンな`nn.Module`構造、適切な重み初期化、標準的なトレーニング/検証ループ、カスタムデータセットと最適化されたDataLoaderの構成、チェックポイントの保存・読み込み、混合精度学習(AMP)、勾配チェックポイント、`torch.compile`による高速化など、主要なパターンをカバーしています。各パターンは良い例と悪い例を対比して示されており、初心者から上級者まで、PyTorchコードの品質とパフォーマンスを向上させるために役立ちます。また、`model.train()`/`model.eval()`の設定忘れやインプレース操作など、避けるべきアンチパターンも明示しています。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/pytorch-patterns

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

PyTorch開発パターン

PyTorchの慣用的なパターンとベストプラクティスで、堅牢で効率的、再現可能なディープラーニングアプリケーションを構築します。

アクティブにするタイミング

  • 新しいPyTorchモデルやトレーニングスクリプトを作成するとき
  • ディープラーニングコードをレビューするとき
  • トレーニングループやデータパイプラインをデバッグするとき
  • GPUメモリ使用量やトレーニング速度を最適化するとき
  • 再現可能な実験をセットアップするとき

コア原則

1. デバイスに依存しないコード

デバイスをハードコードせず、CPUとGPUの両方で動作するコードを常に記述します。

# 良い例: デバイス非依存
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = MyModel().to(device)
data = data.to(device)

# 悪い例: ハードコードされたデバイス
model = MyModel().cuda()  # GPUがないとクラッシュ
data = data.cuda()

2. 再現性を最優先

再現可能な結果を得るために、すべての乱数シードを設定します。

# 良い例: 完全な再現性設定
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

# 悪い例: シード制御なし
model = MyModel()  # 実行ごとに異なる重み

3. 明示的な形状管理

テンソルの形状を常に文書化し、検証します。

# 良い例: 形状が注釈されたforward
    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)

# 悪い例: 形状追跡なし
    def forward(self, x):
        x = self.conv1(x)
        x = self.pool(x)
        x = x.view(x.size(0), -1)  # このサイズは何?
        return self.fc(x)           # これで動くのか?

モデルアーキテクチャのパターン

クリーンなnn.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)

# 悪い例: すべてをforwardに書く
class ImageClassifier(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, x):
        x = F.conv2d(x, weight=self.make_weight())  # 呼び出すたびに重みを作成!
        return x

適切な重み初期化

# 良い例: 明示的な初期化
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)

トレーニングループのパターン

標準的なトレーニングループ

# 良い例: ベストプラクティスを備えた完全なトレーニングループ
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()  # 常にトレーニングモードに設定
    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)  # zero_grad()より効率的

        # 混合精度トレーニング
        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()
        else:
            loss.backward()
            torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
            optimizer.step()

        total_loss += loss.item()

    return total_loss / len(dataloader)

検証ループ

# 良い例: 適切な評価
@torch.no_grad()  # torch.no_grad()ブロックでラップするより効率的
def evaluate(
    model: nn.Module,
    dataloader: DataLoader,
    criterion: nn.Module,
    device: torch.device,
) -> tuple[float, float]:
    model.eval()  # 常に評価モードに設定—ドロップアウト無効、バッチノルムのランニング統計を使用
    total_loss = 0.0
    correct = 0
    total = 0

    for data, target in dataloader:
        data, target = data.to(device), target.to(device)
        output = model(data)
        total_loss += criterion(output, target).item()
        correct += (output.argmax(1) == target).sum().item()
        total += target.size(0)

    return total_loss / len(dataloader), correct / total

データパイプラインパターン

カスタムデータセット

# 良い例: 型ヒント付きのクリーンなデータセット
class ImageDataset(Dataset):
    def __init__(
        self,
        image_dir: str,
        labels: dict[str, int],
        transform: transforms.Compose | None = None,
    ) -> None:
        self.image_paths = list(Path(image_dir).glob("*.jpg"))
        self.labels = labels
        self.transform = transform

    def __len__(self) -> int:
        return len(self.image_paths)

    def __getitem__(self, idx: int) -> tuple[torch.Tensor, int]:
        img = Image.open(self.image_paths[idx]).convert("RGB")
        label = self.labels[self.image_paths[idx].stem]

        if self.transform:
            img = self.transform(img)

        return img, label

効率的なDataLoader設定

# 良い例: 最適化されたDataLoader
dataloader = DataLoader(
    dataset,
    batch_size=32,
    shuffle=True,            # トレーニング用にシャッフル
    num_workers=4,           # 並列データ読み込み
    pin_memory=True,         # CPU→GPU転送を高速化
    persistent_workers=True, # エポック間でワーカーを維持
    drop_last=True,          # BatchNorm用に一貫したバッチサイズ
)

# 悪い例: デフォルトのまま(遅い)
dataloader = DataLoader(dataset, batch_size=32)  # num_workers=0, pin_memory=False

可変長データ用のカスタムcollate

# 良い例: collate_fnでシーケンスをパディング
def collate_fn(batch: list[tuple[torch.Tensor, int]]) -> tuple[torch.Tensor, torch.Tensor]:
    sequences, labels = zip(*batch)
    # バッチ内の最大長にパディング
    padded = nn.utils.rnn.pad_sequence(sequences, batch_first=True, padding_value=0)
    return padded, torch.tensor(labels)

dataloader = DataLoader(dataset, batch_size=32, collate_fn=collate_fn)

チェックポイントのパターン

チェックポイントの保存と読み込み

# 良い例: すべてのトレーニング状態を含む完全なチェックポイント
def save_checkpoint(
    model: nn.Module,
    optimizer: torch.optim.Optimizer,
    epoch: int,
    loss: float,
    path: str,
) -> None:
    torch.save({
        "epoch": epoch,
        "model_state_dict": model.state_dict(),
        "optimizer_state_dict": optimizer.state_dict(),
        "loss": loss,
    }, path)

def load_checkpoint(
    path: str,
    model: nn.Module,
    optimizer: torch.optim.Optimizer | None = None,
) -> dict:
    checkpoint = torch.load(path, map_location="cpu", weights_only=True)
    model.load_state_dict(checkpoint["model_state_dict"])
    if optimizer:
        optimizer.load_state_dict(checkpoint["optimizer_state_dict"])
    return checkpoint

# 悪い例: モデルの重みだけ保存(トレーニング再開不可)
torch.save(model.state_dict(), "model.pt")

パフォーマンス最適化

混合精度トレーニング

# 良い例: GradScalerを使用したAMP
scaler = torch.amp.GradScaler("cuda")
for data, target in dataloader:
    with torch.amp.autocast("cuda"):
        output = model(data)
        loss = criterion(output, target)
    scaler.scale(loss).backward()
    scaler.step(optimizer)
    scaler.update()
    optimizer.zero_grad(set_to_none=True)

大規模モデル向け勾配チェックポイント

# 良い例: 計算とメモリのトレードオフ
from torch.utils.checkpoint import checkpoint

class LargeModel(nn.Module):
    def forward(self, x: torch.Tensor) -> torch.Tensor:
        # バックワード時に活性化を再計算してメモリを節約
        x = checkpoint(self.block1, x, use_reentrant=False)
        x = checkpoint(self.block2, x, use_reentrant=False)
        return self.head(x)

高速化のためのtorch.compile

# 良い例: より高速な実行のためにモデルをコンパイル(PyTorch 2.0+)
model = MyModel().to(device)
model = torch.compile(model, mode="reduce-overhead")

# モード: "default"(安全)、"reduce-overhead"(より高速)、"max-autotune"(最速)

クイックリファレンス: PyTorchイディオム

イディオム説明
model.train() / model.eval()トレーニング/評価の前に必ずモードを設定
torch.no_grad()推論時に勾配を無効化
optimizer.zero_grad(set_to_none=True)より効率的な勾配クリア
.to(device)デバイス非依存のテンソル/モデル配置
torch.amp.autocast2倍の速度向上のための混合精度
pin_memory=Trueより高速なCPU→GPUデータ転送
torch.compile高速化のためのJITコンパイル(2.0+)
weights_only=Trueセキュアなモデル読み込み
torch.manual_seed再現可能な実験
gradient_checkpointing計算とメモリのトレードオフ

避けるべきアンチパターン

# 悪い例: 検証中にmodel.eval()を忘れる
model.train()
with torch.no_grad():
    output = model(val_data)  # ドロップアウトがまだ有効!BatchNormがバッチ統計を使用!

# 良い例: 常に評価モードを設定
model.eval()
with torch.no_grad():
    output = model(val_data)

# 悪い例: 自動微分を壊すインプレース操作
x = F.relu(x, inplace=True)  # 勾配計算を壊す可能性がある
x += residual                  # インプレース加算がautogradグラフを壊す

# 良い例: インプレースでない操作
x = F.relu(x)
x = x + residual

# 悪い例: トレーニングループ内でデータを繰り返しGPUに移動
for data, target in dataloader:
    model = model.cuda()  # 毎イテレーションでモデルを移動!

# 良い例: ループの前に1度だけモデルを移動
model = model.to(device)
for data, target in dataloader:
    data, target = data.to(device), target.to(device)

# 悪い例: backwardの前に.item()を使用
loss = criterion(output, target).item()  # グラフから切り離し!
loss.backward()  # エラー: .item()を通じて逆伝播できない

# 良い例: ログ出力のためだけに.item()を呼ぶ
loss = criterion(output, target)
loss.backward()
print(f"Loss: {loss.item():.4f}")  # backward後の.item()は問題ない

# 悪い例: torch.saveを正しく使っていない
torch.save(model, "model.pt")  # モデル全体を保存(脆弱で移植性がない)

# 良い例: state_dictを保存
torch.save(model.state_dict(), "model.pt")

覚えておいてください: PyTorchコードは、デバイス非依存で、再現可能で、メモリ効率が良いものであるべきです。迷ったら、torch.profilerでプロファイルし、torch.cuda.memory_summary()でGPUメモリを確認してください。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

関連スキル