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

Written for no agent in particular: nothing here depends on one.

Good fit 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.

Compare 6 skills from other repositories ↓
Install with agentmods
npx agentmods add skills/param087/agent-ml-skills/pytorch-training-loop
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.

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/github.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/github.svg" alt="Measured on agentmods" height="20"></a>

Or the 80×15 button, for a site that already has a row of RSS and ATOM ones. Only the verdict fits; the numbers stay here.

agentmods 80×15 button for pytorch-training-loop

Your own site · 80×15
<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="Reviewed on agentmods" width="80" 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. A grade says what 26 rules found in the file — not that it is safe.
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.1 $0.00039 $0.00796
Opus 5.5 $0.00016 $0.00318
Sonnet 5.5 $0.00008 $0.00159
Haiku 4.5 $0.00004 $0.00080

Measured 2mo ago against content hash 6b6c5504b965, method: parsed. Prices are Anthropic first-party input rates as of 2026-10-07, 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 2mo 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. 2mo 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 (13 stars, last pushed 5mo ago), licensed MIT. It adds 39 tokens to every session and 796 once invoked, about $0.0002 per session on Opus 5.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

pytorch-training-loop compared with skills from other repositories

pytorch-training-loop next to 6 skills from other repositories
ModTypeStarsLast pushLicenceScanTokensWorks with
pytorch-training-loopparam087/agent-ml-skillsSkill135mo agoMITA39Claude Code, Codex
yolo-trainingfcakyon/claude-codex-settingsSkill1.2kyesterdayApache-2.0A124Claude Code
alterlab-pyhealthAlterLab-IEU/AlterLab-Academic-SkillsSkill85yesterdayMITA132Claude Code
alterlab-esmAlterLab-IEU/AlterLab-Academic-SkillsSkill85yesterdayMITA101Claude Code
alterlab-deepchemAlterLab-IEU/AlterLab-Academic-SkillsSkill85yesterdayMITA127Claude Code
alterlab-hypogenicAlterLab-IEU/AlterLab-Academic-SkillsSkill85yesterdayMITA122Claude Code
alterlab-molfeatAlterLab-IEU/AlterLab-Academic-SkillsSkill85yesterdayMITA145Claude Code