Registry / ai-ml / torch-fidelity

torch-fidelity

JSON →
library0.4.0pypypi✓ verified 87d ago

Torch-fidelity is a PyTorch library offering precise, efficient, and extensible implementations of popular generative model evaluation metrics, including Inception Score (ISC), Fréchet Inception Distance (FID), Kernel Inception Distance (KID), Perceptual Path Length (PPL), and Precision and Recall (PRC). It aims for epsilon-exact numerical fidelity with reference TensorFlow implementations. The library is actively maintained, with its latest version being 0.4.0, and has a steady release cadence with significant updates, like new metrics and feature extractors.

pip install torch-fidelity
INSTALL
IMPORT
SIG · TORCH-FIDELITY
T
torch-fidelity
ai-mlpythonv0.4.0
Install
68.5s avg
Import
12464ms
Disk
4890MB
Pass rate
4/ 10
Env Coverage4 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.4.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
✓ 79.63s
py 3.11
✕ build_error
✓ 70.63s
py 3.12
✕ build_error
✓ 62.95s
py 3.13
✕ build_error
✓ 60.6s
py 3.9
✕ build_error
✕ timeout
4890MB installed
● package 4890MB
Code
Verified usage

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

torch_fidelity
import torch_fidelity
calculate_metrics
from torch_fidelity import calculate_metrics
GenerativeModelModuleWrapper
from torch_fidelity.generative_model_module_wrapper import GenerativeModelModuleWrapper

This quickstart demonstrates how to calculate Inception Score (ISC), Fréchet Inception Distance (FID), and Kernel Inception Distance (KID) using `torch-fidelity`'s Python API. It involves defining a dummy generative model, wrapping it with `GenerativeModelModuleWrapper`, and then passing it along with a reference input (like a pre-registered dataset 'cifar10-train') to the `calculate_metrics` function. The results are returned as a dictionary.

import torch import torch.nn as nn from torch_fidelity import calculate_metrics from torch_fidelity.generative_model_module_wrapper import GenerativeModelModuleWrapper # Dummy generator model for demonstration class DummyGenerator(nn.Module): def __init__(self, z_size, img_size, img_channels): super().__init__() self.img_size = img_size self.img_channels = img_channels self.main = nn.Sequential( nn.Linear(z_size, 256), nn.ReLU(), nn.Linear(256, img_channels * img_size * img_size), nn.Sigmoid() ) def forward(self, z): img = self.main(z) return img.view(-1, self.img_channels, self.img_size, self.img_size) # Configuration z_size = 128 img_size = 32 img_channels = 3 num_samples = 10000 # Number of samples to generate for metrics device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # Instantiate and wrap the generator generator = DummyGenerator(z_size, img_size, img_channels).to(device) wrapped_generator = GenerativeModelModuleWrapper( generator, z_size, 'normal', 0, num_samples=num_samples, samples_batch_size=32 ) # Calculate metrics # For FID/KID, you need a second input, e.g., a real dataset name or directory path. # Here, we use a registered input 'cifar10-train' for demonstration. metrics_dict = calculate_metrics( input1=wrapped_generator, input2='cifar10-train', cuda=True if device.type == 'cuda' else False, isc=True, fid=True, kid=True, verbose=False, save_cpu_ram=True # Optional: reduce GPU memory if needed ) print(metrics_dict)
Debug
Known issues
breakingIn version 0.4.0, several KID-related API and CLI parameters were renamed for clarity. Specifically, `kid_degree`, `kid_gamma`, and `kid_coef0` are now `kid_kernel_poly_degree`, `kid_kernel_poly_gamma`, and `kid_kernel_poly_coef0` respectively.
fix
Update your API calls and CLI arguments to use the new parameter names: `kid_kernel_poly_degree`, `kid_kernel_poly_gamma`, `kid_kernel_poly_coef0`.
affects: 0.4.0+
breakingIn version 0.3.0, the `calculate_metrics` function's `input1` and `input2` arguments changed from positional to keyword-only arguments. Several CLI arguments were also renamed, e.g., `--datasets-downloaded` to `--no-datasets-download` and `--cache-input1-name` to `--input1-cache-name`.
fix
Ensure `input1` and `input2` are passed as keyword arguments (e.g., `input1=generator, input2='cifar10-train'`) and update CLI arguments according to the changelog.
affects: 0.3.0+
gotchaThe `feature_extractor_compile` option is experimental and might negatively impact numerical precision, leading to discrepancies compared to reference values.
fix
Use `feature_extractor_compile=False` (default) if numerical precision is critical for your evaluation. Only enable it if you have thoroughly validated its impact on your specific use case.
affects: 0.4.0+
gotchaKID (Kernel Inception Distance) metric can mathematically produce negative values. This is expected behavior and not an indication of an error.
fix
Understand that negative KID values are normal and reflect the mathematical properties of the metric.
affects: All
gotchaUsing lossy image formats (like JPG/JPEG) for inputs can affect metric precision and may trigger warnings from `torch-fidelity`.
fix
Prefer lossless image formats (e.g., PNG) for evaluating generative models to maintain the highest numerical precision for metrics.
affects: All
gotcha`torch-fidelity`'s InceptionV3 implementation intentionally differs from `torchvision`'s and uses custom bilinear interpolation to ensure numerical fidelity with original TensorFlow implementations. This is crucial for comparing results with existing literature.
fix
Be aware that direct comparison of InceptionV3 features with `torchvision`'s model might yield minor differences. For precise comparisons with TF-based results, rely on `torch-fidelity`'s built-in InceptionV3.
affects: All
gotchaThe default cache (`fidelity_cache`) and dataset (`fidelity_datasets`) root directories, usually located under `$HOME` or `$ENV_TORCH_HOME`, can consume significant disk space.
fix
To manage disk usage, specify alternative locations using the `--cache-root` and `--datasets-root` CLI arguments or the corresponding `cache_root` and `datasets_root` keyword arguments in `calculate_metrics`. Caching can be disabled with `--no-cache` or `cache=False` (not recommended for efficiency).
affects: All
Errors
Common errors & fixes
TypeError: calculate_metrics() got an unexpected keyword argument 'feature_extractor_arch'
The `feature_extractor_arch` argument was deprecated in torch-fidelity v0.4.0 and replaced by `features`.
fix
Use `features='inception_v3'` (or desired feature type) instead of `feature_extractor_arch='inception_v3'`.
ValueError: Unknown feature extractor name 'my_extractor'. Must be one of {'inception_v3_features', 'vits_small', 'vits_base', 'clip_vit_b_32_features', 'clip_vit_b_16_features'}.
The specified feature extractor name is not recognized by torch-fidelity, possibly due to a typo or an unsupported name.
fix
Use one of the supported feature extractor names listed in the error message, such as `'inception_v3_features'`.
ValueError: No images found at /path/to/my_image_dir
The input directory specified exists but does not contain any image files that torch-fidelity can process (e.g., JPG, PNG, GIF).
fix
Ensure the directory contains valid image files or provide the correct path to a directory with images.
RuntimeError: CUDA out of memory. Tried to allocate X GiB (GPU Y; X GiB total capacity; Z GiB already allocated; W GiB free; P MiB cached)
The GPU does not have enough memory to process the current batch of data or feature extraction, often due to a large `batch_size` or high-resolution images.
fix
Reduce the `batch_size` parameter when calling `calculate_metrics` or `make_features`, or use a GPU with more VRAM.
Upgrade
Version history
0.4.0latest on PyPI · released Feb 17, 2026
Audit
Dependencies
torchrequiredCore deep learning framework.
torchvisionoptionalUsed for standard datasets and transformations.
ftfyoptionalRequired for CLIP feature extractor dependencies.
regexoptionalRequired for CLIP feature extractor dependencies.
setuptoolsoptionalRequired for CLIP feature extractor dependencies.
clean-fidoptionalRequired for CLIP feature extractor dependencies.
Agent activity
18 hits · last 30 days
node
16
OpenAI (training)
1
Resources
torch-fidelity — pip install torch-fidelity · libregistry