pytorch
БесплатноБез исполняемых скриптовНе проверенAssists with building, training, and deploying neural networks using PyTorch. Use when designing architectures for computer vision, NLP, or tabular data…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
PyTorch
Overview
PyTorch is a deep learning framework for building and training neural networks with dynamic computation graphs and automatic differentiation. It provides tensor operations with GPU acceleration, nn.Module for defining architectures, DataLoader for efficient data loading, mixed precision training for performance, and export tools (torch.export, ONNX) for production deployment.
Instructions
- Install with pip from the selector at pytorch.org/get-started/locally (it prints the right index URL for your CUDA version or CPU-only). PyTorch 2.9 and later need Python 3.10+.
- Pick the device once:
device = "cuda" if torch.cuda.is_available() else "cpu"(Apple Silicon:"mps"). - When defining models, subclass
nn.Modulewith__init__for layers andforwardfor computation, usingnn.Sequentialfor simple stacks. - When training, run the standard loop:
optimizer.zero_grad(), forward pass, loss,loss.backward(),clip_grad_norm_,optimizer.step(). Callmodel.train()before the loop andmodel.eval()for validation. - When loading data, subclass
Datasetwith__len__and__getitem__, then useDataLoaderwithnum_workers=4,pin_memory=Trueandpersistent_workers=Truefor GPU training. - When optimizing performance, use
torch.compile(model)(first call is slow while it compiles), mixed precision withtorch.autocast(device_type="cuda", dtype=torch.bfloat16), andDistributedDataParallellaunched withtorchrunfor multi-GPU. With float16 also usetorch.amp.GradScaler("cuda"); bfloat16 does not need it. - When doing transfer learning, load pretrained weights with the
weights=enum (ResNet50_Weights.DEFAULT; the oldpretrained=Truewas removed) or from Hugging Face, freeze the backbone, and replace the classifier head. - When saving, store
model.state_dict(); load withtorch.load(path, map_location=device, weights_only=True).weights_only=Trueis the default since 2.6 and rejects arbitrary pickled objects. - When deploying, use
torch.export.export(model, example_args)for a graph you can ship, andtorch.onnx.export(model, example_args, "model.onnx", dynamo=True)for ONNX (the dynamo exporter is the default since 2.9). TorchScript (torch.jit.trace/script) is deprecated; keep it only for legacy code. - For INT8 or lower-precision inference, use the
torchaopackage (torchao.quantization.quantize_).torch.ao.quantizationis being phased out in favour of it.
Examples
Example 0: Install and verify
pip install torch torchvision
python -c "import torch; print(torch.__version__, torch.cuda.is_available())"
Prints the version (for example 2.14.1) and True when a CUDA GPU is usable.
Example 1: Fine-tune a vision model for image classification
User request: "Fine-tune a pretrained ResNet for classifying product images into 12 categories"
import torch, torch.nn as nn
from torchvision.models import resnet50, ResNet50_Weights
device = "cuda" if torch.cuda.is_available() else "cpu"
model = resnet50(weights=ResNet50_Weights.DEFAULT)
for p in model.parameters():
p.requires_grad = False
model.fc = nn.Linear(2048, 12) # new head is trainable
model.to(device)
opt = torch.optim.AdamW(model.fc.parameters(), lr=1e-3, weight_decay=0.01)
sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=10)
loss_fn = nn.CrossEntropyLoss()
model.train()
for epoch in range(10):
for images, labels in train_loader: # DataLoader with RandomCrop/ColorJitter/Normalize
images, labels = images.to(device), labels.to(device)
opt.zero_grad()
with torch.autocast(device_type=device, dtype=torch.bfloat16):
loss = loss_fn(model(images), labels)
loss.backward()
opt.step()
sched.step()
Result: only the 12-way head is trained, so each epoch is fast; the loss printed per epoch falls steadily and validation accuracy is checked with model.eval() and torch.no_grad().
Example 2: Fine-tune a transformer for sentiment and export it
User request: "Build a sentiment model from bert-base-uncased and export it for serving"
from transformers import AutoTokenizer, AutoModelForSequenceClassification
tok = AutoTokenizer.from_pretrained("bert-base-uncased")
model = AutoModelForSequenceClassification.from_pretrained("bert-base-uncased", num_labels=2)
# ... train with AdamW(lr=2e-5), a linear warmup scheduler and clip_grad_norm_(model.parameters(), 1.0)
model.eval()
sample = tok("great battery life", return_tensors="pt")
torch.onnx.export(model, (sample["input_ids"], sample["attention_mask"]),
"sentiment.onnx", input_names=["input_ids", "attention_mask"],
dynamo=True)
Result: a sentiment.onnx file that ONNX Runtime can load. If export fails on a data-dependent branch, try torch.export.export first to see the exact graph break, then pass dynamic_shapes for variable batch or sequence len
Установить pytorch в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл pytorch?
Assists with building, training, and deploying neural networks using PyTorch. Use when designing architectures for computer vision, NLP, or tabular data, optimizing training with mixed precision and distributed strategies, or exporting models for production inference. Trigger words: pytorch, torch, neural network, deep learning, training loop, cuda.
Как установить скилл pytorch?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл pytorch запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic