Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Pytorch Knowledge Patch?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/nevaberry-pytorch-knowledge-patch)
---
name: pytorch-knowledge-patch
description: PyTorch
version: "2.15.0"
license: MIT
metadata:
author: Nevaberry
---
# PyTorch Knowledge Patch
Load this skill for PyTorch API migrations, compiler and attention behavior,
export and custom operators, distributed training, checkpoint loading, and
platform or extension compatibility. Use the topic references for complete
guidance, examples, experimental status, and version-specific behavior.
## Reference index
| Reference | Topics |
| --- | --- |
| [Compiler and attention](references/compiler-and-attention.md) | Graph breaks, dynamic shapes, compiler settings, control flow, CUDA Graphs, numerical behavior, GEMM backends, SDPA, FlexAttention, variable-length attention |
| [Distributed training and checkpointing](references/distributed-and-checkpointing.md) | Launch, process groups, collectives, DeviceMesh, DTensor, FSDP2, mixed precision, context and pipeline parallelism, Symmetric Memory, checkpoint formats |
| [Export, AOTInductor, and custom operators](references/export-aot-and-custom-ops.md) | Export guards and shapes, custom operators and decompositions, ONNX migration, AOTInductor packaging and ABI, precompile artifacts |
| [Migrations and security](references/migrations-and-security.md) | Restricted loading, repository trust, removed APIs, exceptions, dtype and gradient behavior, activation checkpointing, profiler migrations, memory snapshots |
| [Platforms, extensions, and runtime](references/platforms-extensions-and-runtime.md) | Wheels and hardware requirements, Python and source builds, extension ABI, CUDA, ROCm, XPU, MPS, streams, DLPack, allocation, numerical operators |
## Breaking changes and deprecations
### Installation and source builds
PyTorch 2.15 wheels require Python 3.11 or newer. Its CUDA builds require driver
580 or newer and Turing (SM 7.5) or newer. Pin 2.14 on the `cu126` or `cu130`
index if you need either of those builds. MPS requires macOS 15 or newer;
use 2.14 to keep running on MPS on macOS 14.
Source builds require C++20 and, for CUDA builds, a toolkit at least as new as
CUDA 12.6. `torch.utils.cpp_extension` also builds extensions with C++20.
Build a wheel with `python -m build --wheel --no-isolation` from the checkout.
### Removed APIs and quantization imports
User-facing `torch.jit` APIs emit deprecation warnings, and Python 3.14
compatibility is unspecified. Use `torch.compile` for compilation or
`torch.export` for graph export. Replace `torch.export.export_for_training(model, args)`
with `torch.export.export(model, args)`, which produces the same graph.
Python and C++ named tensor APIs were removed; track dimensions by position.
Run `pip install torchao` and migrate removed PT2E utilities and quantizers
from `torch.ao.quantization.pt2e` and `torch.ao.quantization.quantizer`.
Creating tensors with `torch.quint8`, `torch.qint8`, or `torch.qint32` emits
a deprecation warning in Python and C++.
### Restricted checkpoint loading
Use TorchFix to find `torch.load` calls that omit `weights_only` and set the
intended loading policy explicitly before upgrading to 2.6. The default
`torch.load(..., weights_only=True)` allowlist no longer includes jagged or
strided nested tensors, or builtin exceptions previously allowlisted by
importing `torch.distributed`. For a trusted jagged checkpoint, scope the
allowlist to the load; the migration reference contains the exact example.
`torch.load(..., weights_only=True)` validates sparse tensor invariants
regardless of the global sparse validation setting. Regenerate or repair
checkpoints whose sparse tensors fail validation.
### ONNX export
In 2.9, `torch.onnx.export` defaults to `dynamo=True` and ONNX opset 20.
Use `dynamo=False` for the TorchScript exporter, or `opset_version=18` if
the downstream runtime requires opset 18. For Dynamo export, use
`dynamic_shapes` in place of deprecated `dynamic_axes`.
Drop the removed `fallback` keyword. To retain fallback behavior, catch
the Dynamo export failure and make a separate call with `dynamo=False`.
Give the Dynamo exporter the original `nn.Module` or a
`torch.export.ExportedProgram`; traced and scripted modules are unsupported.
### Distributed checkpoints and FSDP2 gradients
Distributed Checkpoint 2.15 records tensor strides in `.metadata`, so
`dcp.load` on 2.14 or earlier cannot read checkpoints written by 2.15.
Keep older producers when older readers are required: 2.15 has no legacy
write option. Redistribute DTensors with a `Partial` placement to a
non-partial placement before checkpointing them.
With `MixedPrecisionPolicy(reduce_dtype=None)`, FSDP2 accumulates and reduces
gradients in each parameter's `grad_dtype`, which defaults to the original
parameter dtype. Set `reduce_dtype` explicitly to preserve the previous
behavior, for example
`MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.bfloat16)`
for BF16 accumulation and reduction with FP32 parameters.
### Compiled collectives and FSDP2 hooks
Calls to `torch.distributed.nn.functional` raise `RuntimeError` under
`torch.compile`. Migrate compiled calls to `torch.distributed._functional_collectives`.
FSDP2 hooks require graph breaks when using compiled autograd: compile the
sharded model with `fullgraph=False`, compile the inner model before applying
`fully_shard`, or disable compiled autograd for that step.
### Profiler migration
Read the `FunctionEvent.metadata` dict, for example `event.metadata["grid"]`,
with `_ExperimentalConfig(expose_kineto_event_metadata=True)`.
The `metadata_json` property and constructor argument were removed, and
`event_metadata` is deprecated. Use `torch.profiler.ProfilerActivityConfig`
and `torch.profiler.PerformanceMetricsConfig` for metrics per activity group;
removed `profiler_metrics` and `profiler_measure_per_kernel` keywords now
raise `TypeError` when passed to `_ExperimentalConfig`.
## Compiler and attention quick reference
### Specialization and graph boundaries
Use `torch._dynamo.maybe_mark_dynamic(x, 0)` for a dimension that may
specialize. When ranks compile independently, a rank-local recompile or
divergent compilation decisions can lead to an NCCL timeout. Use
`torch._dynamo.mark_unbacked(x, dim)` for a rank-varying dimension whose
runtime size must stay out of specialization decisions.
Use `torch._dynamo.error_on_graph_break(True)` as a context manager or
decorator to raise on graph breaks; nest a `False` scope to resume compilation
after breaks in that region. Set `fullgraph=False` to allow this.
`torch.compile(fullgraph=True)` automatically enables `capture_scalar_outputs`
and `capture_dynamic_output_shape_ops` for calls such as `Tensor.item()`
and `torch.nonzero()`.
### Region options and mutation
Only `fallback_by_default` and `max_autotune` are accepted in the forward
and backward Inductor config patch dicts passed to
`get_invoke_subgraph_compile_options`. Set other keys in the outer
`torch.compile(..., options=...)` call. Pass final values when creating
region options because the dicts are snapshotted.
Dynamo rejects input mutation and aliasing in higher-order op bodies unless
the operator opts in, raising under `fullgraph=True` and graph-breaking
otherwise. Make a FlexAttention `score_mod` out-of-place by returning
`score + 1`. A registered custom operator whose result shares storage with
an input can silently produce incorrect results under `torch.compile` in
2.9: clone a returned view and use `torch.library.opcheck` to catch aliasing
that violates the operator schema.
### Numerical behavior and autograd
`torch.compile` honors `torch.use_deterministic_algorithms(True)` for
run-to-run determinism. Set `torch._inductor.config.emulate_precision_casts = True`
before compiling to preserve intermediate FP16 and BF16 rounding across
fused operations. Reduction order and matmul kernel choices can still affect results.
For `torch.autograd.grad(result, intermediate)`, compute `result` outside
the compiled region returning `intermediate`. Eager autograd receives
gradients at the end of each compiled region's backward pass. Use Compiled
Autograd if earlier updates matter and the entire backward pass can be captured.
### FlexAttention masks and variable-length attention
Rebuild the `BlockMask` when a new input changes the mask's block sparsity;
reuse it across layers sharing the same mask and sequence lengths. Changes
to captured tensor values or block-sparsity metadata alone can reuse the
compiled FlexAttention kernel. Sliced `BlockMask` objects raise, and nested
jagged tensor inputs are unsupported; construct masks for the intended inputs.
For packed documents, require matching document IDs in the mask and subtract
each document's starting offset before applying position-dependent rules.
The compiler reference includes a complete document-local mask example.
Use `torch.nn.attention.varlen.varlen_attn` for ragged or packed sequences.
Use `window_size=(-1, -1)` for full attention, `(-1, 0)` for causal attention,
or `(W, 0)` for a causal sliding window. Pass `enable_gqa=True` for
grouped-query attention and `num_splits=1` to disable split-KV.
## Export and distributed training quick reference
### Dynamic export shapes and decompositions
`Dim.AUTO` can infer relationships involving multiple axes. Sample sizes
of 0 or 1 can specialize an axis even under `Dim.AUTO`; use a sample size
of at least 2 for an axis that should vary. An integer in a dimension spec
fixes that axis and checks the sample input. Use `Dim.STATIC` to take the
size from the sample input; per-dimension `None` is deprecated.
Use `torch._check` before indexing to give export bounds for an index read
from a tensor; the checks also enforce those bounds at runtime. Tensor
`repeat` can keep a count from `.item()` symbolic and inserts a runtime
check for a nonnegative count, while Python `range(n)` requires a concrete
integer when export traces a loop.
Use `torch.export.default_decompositions()` for an editable Core ATen table,
set the entry for a specific operator overload, and pass the table to
`run_decompositions`. The export reference contains working examples.
### FSDP2 scheduling and full checkpoints
Set forward and backward prefetch lists on sharded modules to schedule
multiple all-gathers in execution order. Call `model.unshard()` before
forward to issue the root group's all-gather earlier. TorchAO float8 linear
layers with tensorwise scaling can use FSDP2 float8 weight all-gathers;
the same model can run scaled dot-product attention in BF16.
For a full checkpoint and a meta-initialized FSDP2 model, on each rank convert
the full checkpoint tensors to DTensors using the corresponding sharded
entries' mesh and placements. Load with `assign=True` after sharding on
the meta device. See the distributed reference for the complete example.
### NCCL initialization and checkpoint storage
The new default `nccl` implementation eagerly initializes each group on one
CUDA device, using `device_id` or `LOCAL_RANK` modulo the device count, with
global rank as the fallback when `LOCAL_RANK` is unset. To roll back temporarily
in 2.15, select `nccl-legacy` or set `TORCH_DIST_USE_NCCL2=0` on every rank
before group creation.
Import `FsspecReader` and `FsspecWriter` from `torch.distributed.checkpoint`.
`FsspecWriter` supports `dcp.async_save` via `cache_staged_state_dict`,
inserted before `overwrite`; pass `overwrite` and later options by keyword.