Legacy APIs & Migration

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

PyTorch books and blog posts age quickly. Code that was idiomatic in 2018, 2020 or even 2023 may now be deprecated, removed, or may belong to a library that is archived. This page lists the most common outdated patterns, says what replaced them, and summarizes the release notes that matter for migration. Outdated spellings appear only in prose and tables, never as recommended code. If you are following an older book (see Learning Resources for the books and courses and the caveats on each), check this page when something fails to import.

Targeted versions: Python 3.13 and PyTorch 2.15, released on 2026-10-28. Examples were run on Python 3.13 with PyTorch 2.15 (CPU) and torchdata 0.11 on 2026-10-31.

Where older books and tutorials are outdated

Older material says Status in 2026 Use instead

Variable wrapping and volatile=True for inference

Removed from practical use since PyTorch 0.4 (2018), when tensors and variables were merged. Tensors track gradients themselves.

Plain tensors with requires_grad, and torch.no_grad() or torch.inference_mode()

torch.jit.script and torch.jit.trace for deployment

TorchScript is deprecated; release notes for 2.10 added deprecation warnings and recommend torch.compile or torch.export.

torch.export, AOTInductor, ONNX or ExecuTorch

torch.ao.quantization (eager and FX graph mode)

Quantization development is centralized in torchao; the documentation announced plans to delete torch.ao.quantization.

torchao

torch.cuda.amp.autocast, torch.cuda.amp.GradScaler

Deprecated: calling them emits a FutureWarning that names the torch.amp replacement.

torch.amp.autocast("cuda"), torch.amp.GradScaler("cuda")

TorchServe (.mar archives, torch-model-archiver)

Repository archived on 2025-08-07; no longer maintained.

Other serving stacks, or ExecuTorch and ONNX Runtime for on-device and portable inference

torchtext

Repository archived on 2025-09-10; 0.18 (April 2024) is the last stable release.

Hugging Face tokenizers and datasets, or your own tokenization

DataPipes (IterDataPipe, torchdata.datapipes) and DataLoader2

Deprecated in torchdata 0.8 and removed in torchdata 0.10; 0.9 was the last release that shipped them, together with DataLoader2.

torch.utils.data.DataLoader; torchdata.stateful_dataloader.StatefulDataLoader and torchdata.nodes

Named tensors (names=...)

Removed in PyTorch 2.13 according to the release notes.

Document dimension order by convention; use einops or comments

conda install pytorch -c pytorch

The official conda channel stopped receiving releases after PyTorch 2.5.

pip wheels, or conda-forge packages

torch.load(path) trusting pickles

weights_only=True has been the default since PyTorch 2.6; nested tensors left the allowlist in 2.15.

Save state_dict; allow-list extra types with torch.serialization.safe_globals

torch.onnx.export with the TorchScript exporter

The default exporter became dynamo=True in 2.9; dynamic_axes was deprecated in 2.10.

torch.onnx.export(model, args, dynamo=True) with dynamic_shapes

The sections below give migration snippets for the items that most often break existing code.

TorchScript

TorchScript (torch.jit.script, torch.jit.trace, torch.jit.save, torch.jit.load) compiled a Python subset to an intermediate representation for use from C++ or on mobile. The 2.10 release notes added deprecation warnings because torch.jit is not guaranteed to work on Python 3.14, and recommend torch.compile or torch.export. Existing .pt TorchScript files may continue to load for now, but do not start new work on it. The replacements are covered in torch.export, AOTInductor, ONNX Export and ExecuTorch.

import torch
from torch import nn

model = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 2)).eval()
example = (torch.randn(1, 4),)

exported = torch.export.export(model, example)
print(exported.module()(*example).shape)   # torch.Size([1, 2])
torch.export.save(exported, "model.pt2")

Quantization

Eager-mode (quantize, quantize_dynamic) and FX graph-mode (prepare_fx, convert_fx) quantization in torch.ao.quantization have a migration path to torchao: the quantize_ API for eager flows and prepare_pt2e and convert_pt2e for the PT2 export flow, which has already moved. A few utility functions (compute_sqnr, compute_normalized_l2_error, compute_cosine_similarity) remain documented in PyTorch. The documentation says deletion was planned for 2.10 if no blockers remained; check the current state of the module before relying on either side. See Quantization & Sparsity.

Automatic mixed precision

The old device-specific spellings are deprecated in favour of the generic ones in torch.amp; the same applies to custom_fwd and custom_bwd. Details of the loop are in Automatic Mixed Precision.

import torch
from torch import nn

device = "cuda" if torch.cuda.is_available() else "cpu"
dtype = torch.float16 if device == "cuda" else torch.bfloat16
model = nn.Linear(16, 4).to(device)
opt = torch.optim.AdamW(model.parameters())
scaler = torch.amp.GradScaler(device)        # not torch.cuda.amp.GradScaler()

x = torch.randn(8, 16, device=device)
with torch.amp.autocast(device, dtype=dtype):   # not torch.cuda.amp.autocast()
    loss = model(x).square().mean()

opt.zero_grad()
scaler.scale(loss).backward()
scaler.step(opt)
scaler.update()

The CPU branch of the example uses bfloat16. With bfloat16 the scaler is optional on any device, because bfloat16 keeps the float32 exponent range and gradients rarely underflow; torch.autocast alone is enough.

TorchServe, torchtext and DataPipes

TorchServe is archived and read-only, with a notice that it is no longer actively maintained and that vulnerabilities may go unaddressed. Treat it as unsuitable for new deployments; see Deploying & Serving Models and ONNX & Interoperability for current options. torchtext development stopped with release 0.18, whose compatibility table ends at PyTorch 2.3; its vocabulary builders and dataset loaders should be replaced by tokenizer libraries (see Hugging Face Hub Essentials).

The torchdata repository now describes StatefulDataLoader, a drop-in replacement for DataLoader that adds state_dict and load_state_dict so an input pipeline can resume mid-epoch, and torchdata.nodes, a library of composable iterators. The DataPipes API that old tutorials chained with the pipe operator, and its DataLoader2, were removed in torchdata 0.10: the installed package (0.11) contains only stateful_dataloader and nodes. For the standard approach see Datasets & DataLoader.

import torch
from torch.utils.data import Dataset
from torchdata.stateful_dataloader import StatefulDataLoader


class Squares(Dataset):
    def __len__(self):
        return 100

    def __getitem__(self, i):
        return torch.tensor(float(i * i))


loader = StatefulDataLoader(Squares(), batch_size=10, num_workers=0)
it = iter(loader)
next(it)
state = loader.state_dict()          # resume point to store in a checkpoint
loader.load_state_dict(state)

Variable and volatile

Before PyTorch 0.4, a tensor had to be wrapped in torch.autograd.Variable to take part in autograd, and volatile=True disabled graph building for inference. Both ideas are gone from modern code: every tensor can require gradients, and graph recording is switched off with a context manager. Also avoid the related habit of reading .data to bypass autograd; use .detach(), which is safe against in-place modification being silently missed. See no_grad, inference_mode & Grad Modes.

import torch

x = torch.randn(3, requires_grad=True)
with torch.inference_mode():
    y = x * 2                # no graph is recorded
print(y.requires_grad)       # False

Named tensors

The experimental named-tensor feature (names= arguments and rename) was removed in PyTorch 2.13 per the release notes. If an older tutorial uses it, drop the names and track dimension order explicitly.

conda

The pytorch channel on Anaconda received its last release with PyTorch 2.5, according to the announcement in issue 138506, which points users to pip wheels from download.pytorch.org or PyPI, or to the conda-forge packages (pytorch, pytorch-cpu, pytorch-gpu). The nightly and test channels were also to be deprecated. Use the selector at pytorch.org to produce the current install command; see Installation & Versions.

python3.13 -m venv .venv
source .venv/bin/activate
pip install torch
python -c "import torch; print(torch.__version__)"

Release notes that matter for migration

Dates below are from the GitHub release pages. Release 2.9.0 is from 2025 and the later ones from 2026; releases 2.6 to 2.8 are summarized after the table.

Version Date Migration-relevant items

2.9.0

15 Oct

Minimum Python raised to 3.10; ONNX export defaults to dynamo=True.

2.10.0

21 Jan

TorchScript deprecation warnings; dynamic_axes in ONNX export and export_memory_timeline deprecated; torch.compile supports Python 3.14.

2.11.0

23 Mar

PyPI wheels ship CUDA 13.0; Volta (SM 7.0) dropped from CUDA 12.8 and 12.9 binaries; is_causal removed from varlen_attn; trust_repo=None removed from torch.hub.

2.12.0

13 May

CUDA 12.8 binaries removed; torch.distributed.nn.functional operators raise under torch.compile; profiler metadata_json deprecated in favour of event_metadata.

2.13.0

08 Jul

Named tensors and Bazel build removed; CPython 3.13t binaries no longer built; Python 3.15 wheels on Linux.

2.14.0

02 Sep

Deprecated torch.cholesky(), torch.qr() and the profiler use_cuda argument removed; rewritten nccl backend, with the previous implementation still selectable as nccl-legacy during a transition period.

2.15.0

28 Oct

Python 3.10 wheels no longer published (minimum Python 3.11); nested tensors off the default weights_only allowlist; nccl-legacy still registered but scheduled for removal in the next release; distributed checkpoints record strides so 2.14 and earlier cannot load them; MPS requires macOS 15 or newer.

Releases 2.6, 2.7 and 2.8 appeared during 2025. The change most code notices from 2.6 is that torch.load defaults to weights_only=True; see the release pages for the rest. For the load semantics see Saving & Loading Models.

A migration routine

  1. Run your code with warnings visible (python -W default) and treat every DeprecationWarning and FutureWarning from torch as a task.

  2. Replace the renamed APIs in the table above one at a time and run your tests between changes.

  3. Re-export models with torch.export rather than re-tracing with TorchScript.

  4. Pin the PyTorch version of a project and read the release notes before each upgrade, especially for distributed code, checkpoints and serialization.

  5. Check the status of every auxiliary library (torchvision, torchaudio, torchdata, torchao, ExecuTorch) separately from core PyTorch; see Ecosystem.