Registry / ai-ml / torchvision

torchvision

JSON →
library0.28.0pypypi✓ verified 26d ago

Torchvision is a PyTorch domain library providing popular datasets, model architectures, and common image and video transformations for computer vision tasks. It is actively maintained and releases are synchronized with PyTorch versions, with the current version 0.26.0 compatible with torch 2.11.0. It aims to simplify the data loading, preprocessing, and model development workflow for computer vision researchers and practitioners.

pip install torchvision
INSTALL
IMPORT
SIG · TORCHVISION
T
torchvision
ai-mlpythonv0.28.0
Install
Import
Disk
Pass rate
0/ 10
Env Coverage0 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.28.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
glibc
py 3.10
✕ build_error
1/2 runs
py 3.11
✕ build_error
1/2 runs
py 3.12
✕ build_error
1/2 runs
py 3.13
✕ build_error
1/2 runs
py 3.9
✕ build_error
✕ timeout
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

transforms
from torchvision import transforms
import torchvision.transforms
While 'import torchvision.transforms' works, aliasing to 'transforms' is common practice for brevity.
v2 (recommended transforms)
from torchvision.transforms import v2
The v2 transforms are the recommended and actively developed API.
datasets
from torchvision import datasets
models
from torchvision import models
io (image I/O)
from torchvision import io
from torchvision.io import read_video
Video decoding/encoding functions (e.g., read_video, write_video) were removed in v0.26.0.
tv_tensors
from torchvision import tv_tensors
Used for structured data types like BoundingBoxes and KeyPoints in v2 transforms.

This quickstart demonstrates how to use `torchvision` to preprocess an image and perform inference with a pre-trained ResNet-18 model. It covers defining transformations with `torchvision.transforms.v2.Compose`, loading a pre-trained model with `torchvision.models`, and obtaining human-readable predictions.

import torch from torchvision.transforms import v2 from torchvision import models import os # 1. Create a dummy image tensor (simulating a loaded image) H, W = 256, 256 # Example image dimensions dummy_image = torch.randint(0, 256, size=(3, H, W), dtype=torch.uint8) # 2. Define image transforms using the recommended v2 API preprocess = v2.Compose([ v2.Resize((224, 224), antialias=True), # Resize for common model input sizes v2.ToDtype(torch.float32, scale=True), # Convert to float and scale pixel values to [0, 1] v2.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), # ImageNet normalization ]) # Apply transforms to the dummy image input_tensor = preprocess(dummy_image) input_batch = input_tensor.unsqueeze(0) # Add a batch dimension (models expect batches) # 3. Load a pre-trained image classification model (e.g., ResNet-18) # Use DEFAULT_WEIGHTS to automatically get the best available pre-trained weights weights = models.ResNet18_Weights.DEFAULT model = models.resnet18(weights=weights) model.eval() # Set the model to evaluation mode for inference # Get the categories the model was trained on for human-readable output categories = weights.meta["categories"] # 4. Perform inference with torch.no_grad(): # Disable gradient calculation for inference to save memory and computations output = model(input_batch) # 5. Get the predicted class probabilities = torch.nn.functional.softmax(output, dim=1) predicted_probability, predicted_idx = torch.max(probabilities, 1) predicted_label = categories[predicted_idx.item()] print(f"Predicted class: {predicted_label} (Probability: {predicted_probability.item():.2f})") print("Quickstart successful: Image processed and classified using torchvision.")
Debug
Known issues
breakingThe video decoding and encoding utilities (`torchvision.io.video.*`, `read_video`, `write_video`, `VideoReader` class) were removed in Torchvision 0.26.0.
fix
Migrate any video decoding/encoding code to the `TorchCodec` library (github.com/meta-pytorch/torchcodec).
affects: >=0.26.0
deprecatedThe video decoding and encoding capabilities of TorchVision were deprecated starting from version 0.22 and were slated for removal. While initially targeted for 0.25, they were fully removed in 0.26.0.
fix
Users on older versions should plan to migrate to `TorchCodec` before upgrading to 0.26.0 or newer.
affects: 0.22.x - 0.25.x
gotchaSince version 0.25.0, KeyPoints are no longer clamped by default after a transform. This is a behavior change from previous versions.
fix
If clamping is desired, explicitly use the `SanitizeKeyPoints` transform to remove keypoints outside the image area, or refer to `ClampKeyPoints` for precise control.
affects: >=0.25.0
gotchaThe `torchvision.transforms.v2` API is the recommended and actively developed set of transforms. It offers better performance and supports transforming not just images, but also bounding boxes, masks, videos, and keypoints simultaneously.
fix
Prefer `from torchvision.transforms import v2` over `from torchvision import transforms` for new code and consider migrating existing code for improved functionality and performance.
affects: >=0.15.0
gotchaA version mismatch between `torch` and `torchvision` is a common cause of runtime errors (e.g., 'undefined symbol', 'CUDA toolkit version is incompatible').
fix
Always install `torch` and `torchvision` with compatible versions, ideally from the same installation command or by consulting the official PyTorch installation matrix for matching versions.
affects: All versions
gotchaSince v0.8.0, all random transformations in `torchvision.transforms` use PyTorch's default random generator (`torch.manual_seed`) instead of Python's `random` module. Setting `random.seed()` will not affect these transforms.
fix
To ensure reproducibility for random transforms, use `torch.manual_seed(seed_value)`.
affects: >=0.8.0
breaking`torchvision` might not have pre-built wheels or official support for certain Python versions (e.g., Python 3.13, which is still in beta) or specific operating systems (e.g., Alpine Linux), leading to installation failures like 'No matching distribution found'.
fix
Check `torchvision`'s official installation instructions and compatibility matrix for supported Python versions and OS distributions. Consider using a stable Python version (e.g., 3.10, 3.11, 3.12) or a more commonly supported OS distribution (e.g., Debian, Ubuntu) if encountering installation issues. Manual compilation from source might be an option but is generally not recommended unless necessary.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'torchvision'
The torchvision library is not installed in the current Python environment.
fix
Install torchvision using pip or conda: `pip install torchvision` or `conda install torchvision -c pytorch`.
TypeError: img should be PIL Image. Got <class 'numpy.ndarray'>
A torchvision transform (e.g., `Resize`, `CenterCrop`, `ToPILImage`) that explicitly expects a PIL Image object received a NumPy array instead.
fix
Convert the NumPy array to a PIL Image using `PIL.Image.fromarray(image_np)` before applying the transform.
RuntimeError: Dataset not found or corrupted.
The specified dataset (e.g., from `torchvision.datasets`) could not be found at the provided `root` path, or its automatic download/extraction failed.
fix
Verify that the `root` path is correct and accessible, ensure you have an active internet connection if `download=True` is used, and check disk space. You may need to manually download and extract the dataset.
RuntimeError: DataLoader worker (pid XXXXX) exited unexpectedly
An unhandled exception occurred within the dataset's `__getitem__` method, data transformations, or the collate function when using `torch.utils.data.DataLoader` with `num_workers > 0`.
fix
Set `num_workers=0` in the DataLoader to force data loading in the main process, which will reveal the specific error message and traceback for debugging.
requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: ...
This error often occurs when `torchvision.models` tries to download pre-trained weights (e.g., using `pretrained=True`) but is blocked by a firewall, proxy, or network configuration.
fix
Check your network connectivity, proxy settings, and firewall rules. Alternatively, manually download the pre-trained weights from the official PyTorch model zoo and place them in the appropriate cache directory (`~/.cache/torch/hub/checkpoints/`).
Upgrade
Version history
0.28.0latest on PyPI · released Jul 8, 2026
Audit
Dependencies
torchrequiredCore PyTorch library.
numpyrequiredNumerical operations, often used internally by PyTorch and Torchvision.
pillowrequiredImage loading and manipulation, especially for PIL Image inputs to transforms.
torchvision-extra-decodersoptionalOptional package for decoding HEIC and AVIF image formats.
scipyoptionalRequired for specific datasets.
gdownoptionalRequired for downloading certain datasets from Google Drive.
Agent activity
87 hits · last 30 days
node
78
OpenAI (training)
1
Resources
torchvision — pip install torchvision · libregistry