pytorch-training-loop

pytorch-training-loop is a skill for Claude Code, Codex from param087/agent-ml-skills. It costs 39 tokens per session (796 once invoked), scanned A, original, MIT.

A guide for writing or reviewing a PyTorch training loop, the repeated process that feeds data to a model, calculates errors, and updates its parameters. It covers training and evaluation behavior, gradients, mixed-precision calculations, checkpoints, reproducibility, and device use.

In plain words
What is it for?
Use it to build a training loop, debug a model that does not learn or uses too much memory, or review code for correct modes, gradient handling, device movement, and checkpointing.
Why use it?
It helps prevent quiet mistakes such as disabling gradients, leaving dropout active during evaluation, running out of memory, or saving incomplete training state.

Skill for Claude CodeCodex

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add skills/param087/agent-ml-skills/pytorch-training-loop
Any agent
npx skills add param087/agent-ml-skills --skill pytorch-training-loop
Clone the repo
git clone --depth 1 https://github.com/param087/agent-ml-skills

Made for: Claude Code, Codex.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for pytorch-training-loop

README.md
[![agentmods](https://agentmods.dev/badge/skills/param087/agent-ml-skills/pytorch-training-loop.svg)](https://agentmods.dev/skills/param087/agent-ml-skills/pytorch-training-loop)
Your own site
<a href="https://agentmods.dev/skills/param087/agent-ml-skills/pytorch-training-loop"><img src="https://agentmods.dev/badge/skills/param087/agent-ml-skills/pytorch-training-loop.svg" alt="Measured on agentmods" height="20"></a>
Per session 39 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 796 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00039 $0.00796
Opus 5 $0.00019 $0.00398
Sonnet 5 $0.00008 $0.00159
Haiku 4.5 $0.00004 $0.00080

Measured 5d ago against content hash 6b6c5504b965, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

pytorch-training-loop scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 5d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

skills/pytorch-training-loop/SKILL.md · 92 lines

How it starts

The opening of the file, as written. The whole thing — 92 lines — stays where its author put it; the contents beside it link to each section on GitHub.

PyTorch Training Loop

Overview

A correct PyTorch loop has a precise sequence of operations. Getting the order or the modes wrong produces silent bugs (no gradients, dropout active at eval, leaked compute graphs). This skill encodes the canonical, production-ready loop.

When to use

  • Writing a training loop from scratch.
  • Debugging a model that won't learn or OOMs.
  • Reviewing PyTorch training code.

Canonical loop

import torch
from torch.amp import autocast, GradScaler

device = "cuda" if torch.cuda.is_available() else "cpu"
model.to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.01)
scaler = GradScaler(enabled=(device == "cuda"))
best_val = float("inf")

for epoch in range(num_epochs):
    # ---- TRAIN ----
    model.train()
    for x, y in train_loader:
        x, y = x.to(device, non_blocking=True), y.to(device, non_blocking=True)
        optimizer.zero_grad(set_to_none=True)
        with autocast(device_type=device, enabled=(device == "cuda")):
            out = model(x)
            loss = criterion(out, y)
        scaler.scale(loss).backward()
        scaler.unscale_(optimizer)
        torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
        scaler.step(optimizer)
        scaler.update()

    # ---- VALIDATE ----
    model.eval()
    val_loss = 0.0
    with torch.no_grad():
        for x, y in val_loader:
            x, y = x.to(device), y.to(device)
            val_loss += criterion(model(x), y).item() * x.size(0)
    val_loss /= len(val_loader.dataset)

    # ---- CHECKPOINT BEST ----
    if val_loss < best_val:
        best_val = val_loss
        torch.save({"model": model.state_dict(),
                    "optimizer": optimizer.state_dict(),
                    "epoch": epoch}, "best.pt")

Non-negotiable rules

  1. model.train() before training, model.eval() before validation/inference (toggles dropout & batchnorm).
  2. optimizer.zero_grad() every step — gradients accumulate otherwise.
  3. Wrap validation/inference in torch.no_grad() (or inference_mode()) to save memory.
  4. Detach when logging: loss.item(), not loss — keeping tensors leaks the graph and OOMs.
  5. Clip gradients for RNNs/transformers to prevent explosions.

Read the full file on GitHub · 92 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 5d ago First seen · 92 lines · 39 tokens per session scan A 6b6c5504b965

Subscribe to this mod's changes

pytorch-training-loop is a skill published in the GitHub repository param087/agent-ml-skills (9 stars, last pushed 3mo ago), licensed MIT. It adds 39 tokens to every session and 796 once invoked, about $0.0002 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-31.

Related

Other skills, from other repositories

yolo-training

This skill should be used when user asks to "improve my mAP", "why is my model overfitting", "my training is diverging", "read my results.csv", "interpret my training curves", "my AP50 is good but AP50-95 is bad", "my recall is low", "how do I pick learning rate", "which augmentations should I use", "should I use a…

fcakyon/claude-codex-settings · 124 tokens

template-autoresearch-project

AutoResearch loop exemplar — deterministic ML candidate evaluation, evidence registries, claim ledgers, artifact manifests, readiness gates.

docxology/template · 30 tokens

doc-to-lora-evaluator

Evaluate whether Doc-to-LoRA is the right path for turning documents into parametric memory, and guide a safe proof-of-concept before investing in a full plugin or training pipeline. Use when a user wants to internalize long documents, reduce repeated context costs, compare Doc-to-LoRA against RAG or long-context…

markoblogo/abvx-agent-skills · 85 tokens

alterlab-pyhealth

Develops, tests, and deploys clinical machine learning models with the PyHealth healthcare AI toolkit. Use when working with electronic health records (EHR), clinical prediction tasks (mortality, readmission, drug recommendation), medical coding systems (ICD, NDC, ATC), physiological signals (EEG, ECG), healthcare…

AlterLab-IEU/AlterLab-Academic-Skills · 117 tokens

alterlab-deepchem

Runs molecular machine learning with DeepChem — diverse featurizers, pre-built MoleculeNet benchmark datasets, and pre-trained models (ChemBERTa, GROVER) for property prediction (ADMET, toxicity, solubility) via traditional ML or graph neural networks. Use when running end-to-end molecular ML experiments that need…

AlterLab-IEU/AlterLab-Academic-Skills · 126 tokens

alterlab-esm

Run ESM protein language models — ESM3 for generative multimodal protein design across sequence, structure, and function, and ESM C for efficient embeddings and representations — locally or via the cloud Forge API. Use when working with protein sequences, structures, or function prediction, designing novel proteins…

AlterLab-IEU/AlterLab-Academic-Skills · 89 tokens